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