@@ -1249,7 +1249,10 @@ It is also possible to achieve the same result without using the
1249
1249
1250
1250
>>> import urllib.request
1251
1251
>>> f = urllib.request.urlopen('http://www.python.org/')
1252
- >>> print(f.read(100).decode('utf-8'))
1252
+ >>> try:
1253
+ ... print(f.read(100).decode('utf-8'))
1254
+ ... finally:
1255
+ ... f.close()
1253
1256
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1254
1257
"http://www.w3.org/TR/xhtml1/DTD/xhtm
1255
1258
@@ -1294,7 +1297,8 @@ Use of Basic HTTP Authentication::
1294
1297
opener = urllib.request.build_opener(auth_handler)
1295
1298
# ...and install it globally so it can be used with urlopen.
1296
1299
urllib.request.install_opener(opener)
1297
- urllib.request.urlopen('http://www.example.com/login.html')
1300
+ with urllib.request.urlopen('http://www.example.com/login.html') as f:
1301
+ print(f.read().decode('utf-8'))
1298
1302
1299
1303
:func: `build_opener ` provides many handlers by default, including a
1300
1304
:class: `ProxyHandler `. By default, :class: `ProxyHandler ` uses the environment
@@ -1312,7 +1316,8 @@ programmatically supplied proxy URLs, and adds proxy authorization support with
1312
1316
1313
1317
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
1314
1318
# This time, rather than install the OpenerDirector, we use it directly:
1315
- opener.open('http://www.example.com/login.html')
1319
+ with opener.open('http://www.example.com/login.html') as f:
1320
+ print(f.read().decode('utf-8'))
1316
1321
1317
1322
Adding HTTP headers:
1318
1323
@@ -1323,15 +1328,18 @@ Use the *headers* argument to the :class:`Request` constructor, or::
1323
1328
req.add_header('Referer', 'http://www.python.org/')
1324
1329
# Customize the default User-Agent header value:
1325
1330
req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
1326
- r = urllib.request.urlopen(req)
1331
+ with urllib.request.urlopen(req) as f:
1332
+ print(f.read().decode('utf-8'))
1333
+
1327
1334
1328
1335
:class: `OpenerDirector ` automatically adds a :mailheader: `User-Agent ` header to
1329
1336
every :class: `Request `. To change this::
1330
1337
1331
1338
import urllib.request
1332
1339
opener = urllib.request.build_opener()
1333
1340
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
1334
- opener.open('http://www.example.com/')
1341
+ with opener.open('http://www.example.com/') as f:
1342
+ print(f.read().decode('utf-8'))
1335
1343
1336
1344
Also, remember that a few standard headers (:mailheader: `Content-Length `,
1337
1345
:mailheader: `Content-Type ` and :mailheader: `Host `)
0 commit comments