Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1725fea

Browse files
committed
default: closes Issue12365 - Add an example explaining the context manager use case of urllib.urlopen
2 parents e24f96a + 21c71ba commit 1725fea

1 file changed

Lines changed: 13 additions & 5 deletions

File tree

Doc/library/urllib.request.rst

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ The :mod:`urllib.request` module defines the following functions:
4646
If neither *cafile* nor *capath* is specified, an HTTPS request
4747
will not do any verification of the server's certificate.
4848

49-
This function returns a file-like object with two additional methods from
50-
the :mod:`urllib.response` module
49+
This function returns a file-like object that works as a :term:`context manager`,
50+
with two additional methods from the :mod:`urllib.response` module
5151

5252
* :meth:`geturl` --- return the URL of the resource retrieved,
5353
commonly used to determine if a redirect was followed
@@ -998,16 +998,24 @@ The following W3C document, http://www.w3.org/International/O-charset , lists
998998
the various ways in which a (X)HTML or a XML document could have specified its
999999
encoding information.
10001000

1001-
As python.org website uses *utf-8* encoding as specified in it's meta tag, we
1002-
will use same for decoding the bytes object. ::
1001+
As the python.org website uses *utf-8* encoding as specified in it's meta tag, we
1002+
will use the same for decoding the bytes object. ::
1003+
1004+
>>> with urllib.request.urlopen('http://www.python.org/') as f:
1005+
... print(f.read(100).decode('utf-8'))
1006+
...
1007+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1008+
"http://www.w3.org/TR/xhtml1/DTD/xhtm
1009+
1010+
It is also possible to achieve the same result without using the
1011+
:term:`context manager` approach. ::
10031012

10041013
>>> import urllib.request
10051014
>>> f = urllib.request.urlopen('http://www.python.org/')
10061015
>>> print(f.read(100).decode('utf-8'))
10071016
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
10081017
"http://www.w3.org/TR/xhtml1/DTD/xhtm
10091018

1010-
10111019
In the following example, we are sending a data-stream to the stdin of a CGI
10121020
and reading the data it returns to us. Note that this example will only work
10131021
when the Python installation supports SSL. ::

0 commit comments

Comments
 (0)