@@ -1233,7 +1233,10 @@ It is also possible to achieve the same result without using the
1233
1233
1234
1234
>>> import urllib.request
1235
1235
>>> f = urllib.request.urlopen('http://www.python.org/')
1236
- >>> print(f.read(100).decode('utf-8'))
1236
+ >>> try:
1237
+ ... print(f.read(100).decode('utf-8'))
1238
+ ... finally:
1239
+ ... f.close()
1237
1240
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1238
1241
"http://www.w3.org/TR/xhtml1/DTD/xhtm
1239
1242
@@ -1278,7 +1281,8 @@ Use of Basic HTTP Authentication::
1278
1281
opener = urllib.request.build_opener(auth_handler)
1279
1282
# ...and install it globally so it can be used with urlopen.
1280
1283
urllib.request.install_opener(opener)
1281
- urllib.request.urlopen('http://www.example.com/login.html')
1284
+ with urllib.request.urlopen('http://www.example.com/login.html') as f:
1285
+ print(f.read().decode('utf-8'))
1282
1286
1283
1287
:func: `build_opener ` provides many handlers by default, including a
1284
1288
:class: `ProxyHandler `. By default, :class: `ProxyHandler ` uses the environment
@@ -1296,7 +1300,8 @@ programmatically supplied proxy URLs, and adds proxy authorization support with
1296
1300
1297
1301
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
1298
1302
# This time, rather than install the OpenerDirector, we use it directly:
1299
- opener.open('http://www.example.com/login.html')
1303
+ with opener.open('http://www.example.com/login.html') as f:
1304
+ print(f.read().decode('utf-8'))
1300
1305
1301
1306
Adding HTTP headers:
1302
1307
@@ -1307,15 +1312,18 @@ Use the *headers* argument to the :class:`Request` constructor, or::
1307
1312
req.add_header('Referer', 'http://www.python.org/')
1308
1313
# Customize the default User-Agent header value:
1309
1314
req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
1310
- r = urllib.request.urlopen(req)
1315
+ with urllib.request.urlopen(req) as f:
1316
+ print(f.read().decode('utf-8'))
1317
+
1311
1318
1312
1319
:class: `OpenerDirector ` automatically adds a :mailheader: `User-Agent ` header to
1313
1320
every :class: `Request `. To change this::
1314
1321
1315
1322
import urllib.request
1316
1323
opener = urllib.request.build_opener()
1317
1324
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
1318
- opener.open('http://www.example.com/')
1325
+ with opener.open('http://www.example.com/') as f:
1326
+ print(f.read().decode('utf-8'))
1319
1327
1320
1328
Also, remember that a few standard headers (:mailheader: `Content-Length `,
1321
1329
:mailheader: `Content-Type ` and :mailheader: `Host `)
0 commit comments