@@ -1233,7 +1233,10 @@ It is also possible to achieve the same result without using the
12331233
12341234 >>> import urllib.request
12351235 >>> 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()
12371240 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
12381241 "http://www.w3.org/TR/xhtml1/DTD/xhtm
12391242
@@ -1278,7 +1281,8 @@ Use of Basic HTTP Authentication::
12781281 opener = urllib.request.build_opener(auth_handler)
12791282 # ...and install it globally so it can be used with urlopen.
12801283 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'))
12821286
12831287:func: `build_opener ` provides many handlers by default, including a
12841288:class: `ProxyHandler `. By default, :class: `ProxyHandler ` uses the environment
@@ -1296,7 +1300,8 @@ programmatically supplied proxy URLs, and adds proxy authorization support with
12961300
12971301 opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
12981302 # 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'))
13001305
13011306Adding HTTP headers:
13021307
@@ -1307,15 +1312,18 @@ Use the *headers* argument to the :class:`Request` constructor, or::
13071312 req.add_header('Referer', 'http://www.python.org/')
13081313 # Customize the default User-Agent header value:
13091314 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+
13111318
13121319:class: `OpenerDirector ` automatically adds a :mailheader: `User-Agent ` header to
13131320every :class: `Request `. To change this::
13141321
13151322 import urllib.request
13161323 opener = urllib.request.build_opener()
13171324 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'))
13191327
13201328Also, remember that a few standard headers (:mailheader: `Content-Length `,
13211329:mailheader: `Content-Type ` and :mailheader: `Host `)
0 commit comments