doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
OpenerDirector.error(proto, *args)
Handle an error of the given protocol. This will call the registered error handlers for the given protocol with the given arguments (which are protocol specific). The HTTP protocol is a special case which uses the HTTP response code to determine the specific error handler; refer to the http_error_<type>() methods of the handler classes. Return values and exceptions raised are the same as those of urlopen(). | python.library.urllib.request#urllib.request.OpenerDirector.error |
OpenerDirector.open(url, data=None[, timeout])
Open the given url (which can be a request object or a string), optionally passing the given data. Arguments, return values and exceptions raised are the same as those of urlopen() (which simply calls the open() method on the currently installed global OpenerDirector). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). The timeout feature actually works only for HTTP, HTTPS and FTP connections). | python.library.urllib.request#urllib.request.OpenerDirector.open |
urllib.request.pathname2url(path)
Convert the pathname path from the local syntax for a path to the form used in the path component of a URL. This does not produce a complete URL. The return value will already be quoted using the quote() function. | python.library.urllib.request#urllib.request.pathname2url |
class urllib.request.ProxyBasicAuthHandler(password_mgr=None)
Handle authentication with the proxy. password_mgr, if given, should be something that is compatible with HTTPPasswordMgr; refer to section HTTPPasswordMgr Objects for information on the interface that must be supported. | python.library.urllib.request#urllib.request.ProxyBasicAuthHandler |
ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs)
Retry the request with authentication information, if available. | python.library.urllib.request#urllib.request.ProxyBasicAuthHandler.http_error_407 |
class urllib.request.ProxyDigestAuthHandler(password_mgr=None)
Handle authentication with the proxy. password_mgr, if given, should be something that is compatible with HTTPPasswordMgr; refer to section HTTPPasswordMgr Objects for information on the interface that must be supported. | python.library.urllib.request#urllib.request.ProxyDigestAuthHandler |
ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs)
Retry the request with authentication information, if available. | python.library.urllib.request#urllib.request.ProxyDigestAuthHandler.http_error_407 |
class urllib.request.ProxyHandler(proxies=None)
Cause requests to go through a proxy. If proxies is given, it must be a dictionary mapping protocol names to URLs of proxies. The default is to read the list of proxies from the environment variables <protocol>_proxy. If no proxy environment variables are set, then in a Windows environment proxy settings are obtained from the registry’s Internet Settings section, and in a Mac OS X environment proxy information is retrieved from the OS X System Configuration Framework. To disable autodetected proxy pass an empty dictionary. The no_proxy environment variable can be used to specify hosts which shouldn’t be reached via proxy; if set, it should be a comma-separated list of hostname suffixes, optionally with :port appended, for example cern.ch,ncsa.uiuc.edu,some.host:8080. Note HTTP_PROXY will be ignored if a variable REQUEST_METHOD is set; see the documentation on getproxies(). | python.library.urllib.request#urllib.request.ProxyHandler |
class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
This class is an abstraction of a URL request. url should be a string containing a valid URL. data must be an object specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data. The supported object types include bytes, file-like objects, and iterables of bytes-like objects. If no Content-Length nor Transfer-Encoding header field has been provided, HTTPHandler will set these headers according to the type of data. Content-Length will be used to send bytes objects, while Transfer-Encoding: chunked as specified in RFC 7230, Section 3.3.1 will be used to send files and other iterables. For an HTTP POST request method, data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns an ASCII string in this format. It should be encoded to bytes before being used as the data parameter. headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments. This is often used to “spoof” the User-Agent header value, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as "Mozilla/5.0
(X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11", while urllib’s default user agent string is "Python-urllib/2.6" (on Python 2.6). An appropriate Content-Type header should be included if the data argument is present. If this header has not been provided and data is not None, Content-Type: application/x-www-form-urlencoded will be added as a default. The next two arguments are only of interest for correct handling of third-party HTTP cookies: origin_req_host should be the request-host of the origin transaction, as defined by RFC 2965. It defaults to http.cookiejar.request_host(self). This is the host name or IP address of the original request that was initiated by the user. For example, if the request is for an image in an HTML document, this should be the request-host of the request for the page containing the image. unverifiable should indicate whether the request is unverifiable, as defined by RFC 2965. It defaults to False. An unverifiable request is one whose URL the user did not have the option to approve. For example, if the request is for an image in an HTML document, and the user had no option to approve the automatic fetching of the image, this should be true. method should be a string that indicates the HTTP request method that will be used (e.g. 'HEAD'). If provided, its value is stored in the method attribute and is used by get_method(). The default is 'GET' if data is None or 'POST' otherwise. Subclasses may indicate a different default method by setting the method attribute in the class itself. Note The request will not work as expected if the data object is unable to deliver its content more than once (e.g. a file or an iterable that can produce the content only once) and the request is retried for HTTP redirects or authentication. The data is sent to the HTTP server right away after the headers. There is no support for a 100-continue expectation in the library. Changed in version 3.3: Request.method argument is added to the Request class. Changed in version 3.4: Default Request.method may be indicated at the class level. Changed in version 3.6: Do not raise an error if the Content-Length has not been provided and data is neither None nor a bytes object. Fall back to use chunked transfer encoding instead. | python.library.urllib.request#urllib.request.Request |
Request.add_header(key, val)
Add another header to the request. Headers are currently ignored by all handlers except HTTP handlers, where they are added to the list of headers sent to the server. Note that there cannot be more than one header with the same name, and later calls will overwrite previous calls in case the key collides. Currently, this is no loss of HTTP functionality, since all headers which have meaning when used more than once have a (header-specific) way of gaining the same functionality using only one header. | python.library.urllib.request#urllib.request.Request.add_header |
Request.add_unredirected_header(key, header)
Add a header that will not be added to a redirected request. | python.library.urllib.request#urllib.request.Request.add_unredirected_header |
Request.data
The entity body for the request, or None if not specified. Changed in version 3.4: Changing value of Request.data now deletes “Content-Length” header if it was previously set or calculated. | python.library.urllib.request#urllib.request.Request.data |
Request.full_url
The original URL passed to the constructor. Changed in version 3.4. Request.full_url is a property with setter, getter and a deleter. Getting full_url returns the original request URL with the fragment, if it was present. | python.library.urllib.request#urllib.request.Request.full_url |
Request.get_full_url()
Return the URL given in the constructor. Changed in version 3.4. Returns Request.full_url | python.library.urllib.request#urllib.request.Request.get_full_url |
Request.get_header(header_name, default=None)
Return the value of the given header. If the header is not present, return the default value. | python.library.urllib.request#urllib.request.Request.get_header |
Request.get_method()
Return a string indicating the HTTP request method. If Request.method is not None, return its value, otherwise return 'GET' if Request.data is None, or 'POST' if it’s not. This is only meaningful for HTTP requests. Changed in version 3.3: get_method now looks at the value of Request.method. | python.library.urllib.request#urllib.request.Request.get_method |
Request.has_header(header)
Return whether the instance has the named header (checks both regular and unredirected). | python.library.urllib.request#urllib.request.Request.has_header |
Request.header_items()
Return a list of tuples (header_name, header_value) of the Request headers. | python.library.urllib.request#urllib.request.Request.header_items |
Request.host
The URI authority, typically a host, but may also contain a port separated by a colon. | python.library.urllib.request#urllib.request.Request.host |
Request.method
The HTTP request method to use. By default its value is None, which means that get_method() will do its normal computation of the method to be used. Its value can be set (thus overriding the default computation in get_method()) either by providing a default value by setting it at the class level in a Request subclass, or by passing a value in to the Request constructor via the method argument. New in version 3.3. Changed in version 3.4: A default value can now be set in subclasses; previously it could only be set via the constructor argument. | python.library.urllib.request#urllib.request.Request.method |
Request.origin_req_host
The original host for the request, without port. | python.library.urllib.request#urllib.request.Request.origin_req_host |
Request.remove_header(header)
Remove named header from the request instance (both from regular and unredirected headers). New in version 3.4. | python.library.urllib.request#urllib.request.Request.remove_header |
Request.selector
The URI path. If the Request uses a proxy, then selector will be the full URL that is passed to the proxy. | python.library.urllib.request#urllib.request.Request.selector |
Request.set_proxy(host, type)
Prepare the request by connecting to a proxy server. The host and type will replace those of the instance, and the instance’s selector will be the original URL given in the constructor. | python.library.urllib.request#urllib.request.Request.set_proxy |
Request.type
The URI scheme. | python.library.urllib.request#urllib.request.Request.type |
Request.unverifiable
boolean, indicates whether the request is unverifiable as defined by RFC 2965. | python.library.urllib.request#urllib.request.Request.unverifiable |
class urllib.request.UnknownHandler
A catch-all class to handle unknown URLs. | python.library.urllib.request#urllib.request.UnknownHandler |
UnknownHandler.unknown_open()
Raise a URLError exception. | python.library.urllib.request#urllib.request.UnknownHandler.unknown_open |
urllib.request.url2pathname(path)
Convert the path component path from a percent-encoded URL to the local syntax for a path. This does not accept a complete URL. This function uses unquote() to decode path. | python.library.urllib.request#urllib.request.url2pathname |
urllib.request.urlcleanup()
Cleans up temporary files that may have been left behind by previous calls to urlretrieve(). | python.library.urllib.request#urllib.request.urlcleanup |
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
Open the URL url, which can be either a string or a Request object. data must be an object specifying additional data to be sent to the server, or None if no such data is needed. See Request for details. urllib.request module uses HTTP/1.1 and includes Connection:close header in its HTTP requests. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections. If context is specified, it must be a ssl.SSLContext instance describing the various SSL options. See HTTPSConnection for more details. The optional cafile and capath parameters specify a set of trusted CA certificates for HTTPS requests. cafile should point to a single file containing a bundle of CA certificates, whereas capath should point to a directory of hashed certificate files. More information can be found in ssl.SSLContext.load_verify_locations(). The cadefault parameter is ignored. This function always returns an object which can work as a context manager and has the properties url, headers, and status. See urllib.response.addinfourl for more detail on these properties. For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse object slightly modified. In addition to the three new methods above, the msg attribute contains the same information as the reason attribute — the reason phrase returned by server — instead of the response headers as it is specified in the documentation for HTTPResponse. For FTP, file, and data URLs and requests explicitly handled by legacy URLopener and FancyURLopener classes, this function returns a urllib.response.addinfourl object. Raises URLError on protocol errors. Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). In addition, if proxy settings are detected (for example, when a *_proxy environment variable like http_proxy is set), ProxyHandler is default installed and makes sure the requests are handled through the proxy. The legacy urllib.urlopen function from Python 2.6 and earlier has been discontinued; urllib.request.urlopen() corresponds to the old urllib2.urlopen. Proxy handling, which was done by passing a dictionary parameter to urllib.urlopen, can be obtained by using ProxyHandler objects.
The default opener raises an auditing event urllib.Request with arguments fullurl, data, headers, method taken from the request object. Changed in version 3.2: cafile and capath were added. Changed in version 3.2: HTTPS virtual hosts are now supported if possible (that is, if ssl.HAS_SNI is true). New in version 3.2: data can be an iterable object. Changed in version 3.3: cadefault was added. Changed in version 3.4.3: context was added. Deprecated since version 3.6: cafile, capath and cadefault are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you. | python.library.urllib.request#urllib.request.urlopen |
class urllib.request.URLopener(proxies=None, **x509)
Deprecated since version 3.3. Base class for opening and reading URLs. Unless you need to support opening objects using schemes other than http:, ftp:, or file:, you probably want to use FancyURLopener. By default, the URLopener class sends a User-Agent header of urllib/VVV, where VVV is the urllib version number. Applications can define their own User-Agent header by subclassing URLopener or FancyURLopener and setting the class attribute version to an appropriate string value in the subclass definition. The optional proxies parameter should be a dictionary mapping scheme names to proxy URLs, where an empty dictionary turns proxies off completely. Its default value is None, in which case environmental proxy settings will be used if present, as discussed in the definition of urlopen(), above. Additional keyword parameters, collected in x509, may be used for authentication of the client when using the https: scheme. The keywords key_file and cert_file are supported to provide an SSL key and certificate; both are needed to support client authentication. URLopener objects will raise an OSError exception if the server returns an error code.
open(fullurl, data=None)
Open fullurl using the appropriate protocol. This method sets up cache and proxy information, then calls the appropriate open method with its input arguments. If the scheme is not recognized, open_unknown() is called. The data argument has the same meaning as the data argument of urlopen(). This method always quotes fullurl using quote().
open_unknown(fullurl, data=None)
Overridable interface to open unknown URL types.
retrieve(url, filename=None, reporthook=None, data=None)
Retrieves the contents of url and places it in filename. The return value is a tuple consisting of a local filename and either an email.message.Message object containing the response headers (for remote URLs) or None (for local URLs). The caller must then open and read the contents of filename. If filename is not given and the URL refers to a local file, the input filename is returned. If the URL is non-local and filename is not given, the filename is the output of tempfile.mktemp() with a suffix that matches the suffix of the last path component of the input URL. If reporthook is given, it must be a function accepting three numeric parameters: A chunk number, the maximum size chunks are read in and the total size of the download (-1 if unknown). It will be called once at the start and after each chunk of data is read from the network. reporthook is ignored for local URLs. If the url uses the http: scheme identifier, the optional data argument may be given to specify a POST request (normally the request type is GET). The data argument must in standard application/x-www-form-urlencoded format; see the urllib.parse.urlencode() function.
version
Variable that specifies the user agent of the opener object. To get urllib to tell servers that it is a particular user agent, set this in a subclass as a class variable or in the constructor before calling the base constructor. | python.library.urllib.request#urllib.request.URLopener |
open(fullurl, data=None)
Open fullurl using the appropriate protocol. This method sets up cache and proxy information, then calls the appropriate open method with its input arguments. If the scheme is not recognized, open_unknown() is called. The data argument has the same meaning as the data argument of urlopen(). This method always quotes fullurl using quote(). | python.library.urllib.request#urllib.request.URLopener.open |
open_unknown(fullurl, data=None)
Overridable interface to open unknown URL types. | python.library.urllib.request#urllib.request.URLopener.open_unknown |
retrieve(url, filename=None, reporthook=None, data=None)
Retrieves the contents of url and places it in filename. The return value is a tuple consisting of a local filename and either an email.message.Message object containing the response headers (for remote URLs) or None (for local URLs). The caller must then open and read the contents of filename. If filename is not given and the URL refers to a local file, the input filename is returned. If the URL is non-local and filename is not given, the filename is the output of tempfile.mktemp() with a suffix that matches the suffix of the last path component of the input URL. If reporthook is given, it must be a function accepting three numeric parameters: A chunk number, the maximum size chunks are read in and the total size of the download (-1 if unknown). It will be called once at the start and after each chunk of data is read from the network. reporthook is ignored for local URLs. If the url uses the http: scheme identifier, the optional data argument may be given to specify a POST request (normally the request type is GET). The data argument must in standard application/x-www-form-urlencoded format; see the urllib.parse.urlencode() function. | python.library.urllib.request#urllib.request.URLopener.retrieve |
version
Variable that specifies the user agent of the opener object. To get urllib to tell servers that it is a particular user agent, set this in a subclass as a class variable or in the constructor before calling the base constructor. | python.library.urllib.request#urllib.request.URLopener.version |
urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)
Copy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple (filename, headers) where filename is the local file name under which the object can be found, and headers is whatever the info() method of the object returned by urlopen() returned (for a remote object). Exceptions are the same as for urlopen(). The second argument, if present, specifies the file location to copy to (if absent, the location will be a tempfile with a generated name). The third argument, if present, is a callable that will be called once on establishment of the network connection and once after each block read thereafter. The callable will be passed three arguments; a count of blocks transferred so far, a block size in bytes, and the total size of the file. The third argument may be -1 on older FTP servers which do not return a file size in response to a retrieval request. The following example illustrates the most common usage scenario: >>> import urllib.request
>>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
>>> html = open(local_filename)
>>> html.close()
If the url uses the http: scheme identifier, the optional data argument may be given to specify a POST request (normally the request type is GET). The data argument must be a bytes object in standard application/x-www-form-urlencoded format; see the urllib.parse.urlencode() function. urlretrieve() will raise ContentTooShortError when it detects that the amount of data available was less than the expected amount (which is the size reported by a Content-Length header). This can occur, for example, when the download is interrupted. The Content-Length is treated as a lower bound: if there’s more data to read, urlretrieve reads more data, but if less data is available, it raises the exception. You can still retrieve the downloaded data in this case, it is stored in the content attribute of the exception instance. If no Content-Length header was supplied, urlretrieve can not check the size of the data it has downloaded, and just returns it. In this case you just have to assume that the download was successful. | python.library.urllib.request#urllib.request.urlretrieve |
class urllib.response.addinfourl
url
URL of the resource retrieved, commonly used to determine if a redirect was followed.
headers
Returns the headers of the response in the form of an EmailMessage instance.
status
New in version 3.9. Status code returned by server.
geturl()
Deprecated since version 3.9: Deprecated in favor of url.
info()
Deprecated since version 3.9: Deprecated in favor of headers.
code
Deprecated since version 3.9: Deprecated in favor of status.
getstatus()
Deprecated since version 3.9: Deprecated in favor of status. | python.library.urllib.request#urllib.response.addinfourl |
code
Deprecated since version 3.9: Deprecated in favor of status. | python.library.urllib.request#urllib.response.addinfourl.code |
getstatus()
Deprecated since version 3.9: Deprecated in favor of status. | python.library.urllib.request#urllib.response.addinfourl.getstatus |
geturl()
Deprecated since version 3.9: Deprecated in favor of url. | python.library.urllib.request#urllib.response.addinfourl.geturl |
headers
Returns the headers of the response in the form of an EmailMessage instance. | python.library.urllib.request#urllib.response.addinfourl.headers |
info()
Deprecated since version 3.9: Deprecated in favor of headers. | python.library.urllib.request#urllib.response.addinfourl.info |
status
New in version 3.9. Status code returned by server. | python.library.urllib.request#urllib.response.addinfourl.status |
url
URL of the resource retrieved, commonly used to determine if a redirect was followed. | python.library.urllib.request#urllib.response.addinfourl.url |
urllib.robotparser — Parser for robots.txt Source code: Lib/urllib/robotparser.py This module provides a single class, RobotFileParser, which answers questions about whether or not a particular user agent can fetch a URL on the Web site that published the robots.txt file. For more details on the structure of robots.txt files, see http://www.robotstxt.org/orig.html.
class urllib.robotparser.RobotFileParser(url='')
This class provides methods to read, parse and answer questions about the robots.txt file at url.
set_url(url)
Sets the URL referring to a robots.txt file.
read()
Reads the robots.txt URL and feeds it to the parser.
parse(lines)
Parses the lines argument.
can_fetch(useragent, url)
Returns True if the useragent is allowed to fetch the url according to the rules contained in the parsed robots.txt file.
mtime()
Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically.
modified()
Sets the time the robots.txt file was last fetched to the current time.
crawl_delay(useragent)
Returns the value of the Crawl-delay parameter from robots.txt for the useragent in question. If there is no such parameter or it doesn’t apply to the useragent specified or the robots.txt entry for this parameter has invalid syntax, return None. New in version 3.6.
request_rate(useragent)
Returns the contents of the Request-rate parameter from robots.txt as a named tuple RequestRate(requests, seconds). If there is no such parameter or it doesn’t apply to the useragent specified or the robots.txt entry for this parameter has invalid syntax, return None. New in version 3.6.
site_maps()
Returns the contents of the Sitemap parameter from robots.txt in the form of a list(). If there is no such parameter or the robots.txt entry for this parameter has invalid syntax, return None. New in version 3.8.
The following example demonstrates basic use of the RobotFileParser class: >>> import urllib.robotparser
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url("http://www.musi-cal.com/robots.txt")
>>> rp.read()
>>> rrate = rp.request_rate("*")
>>> rrate.requests
3
>>> rrate.seconds
20
>>> rp.crawl_delay("*")
6
>>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
False
>>> rp.can_fetch("*", "http://www.musi-cal.com/")
True | python.library.urllib.robotparser |
class urllib.robotparser.RobotFileParser(url='')
This class provides methods to read, parse and answer questions about the robots.txt file at url.
set_url(url)
Sets the URL referring to a robots.txt file.
read()
Reads the robots.txt URL and feeds it to the parser.
parse(lines)
Parses the lines argument.
can_fetch(useragent, url)
Returns True if the useragent is allowed to fetch the url according to the rules contained in the parsed robots.txt file.
mtime()
Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically.
modified()
Sets the time the robots.txt file was last fetched to the current time.
crawl_delay(useragent)
Returns the value of the Crawl-delay parameter from robots.txt for the useragent in question. If there is no such parameter or it doesn’t apply to the useragent specified or the robots.txt entry for this parameter has invalid syntax, return None. New in version 3.6.
request_rate(useragent)
Returns the contents of the Request-rate parameter from robots.txt as a named tuple RequestRate(requests, seconds). If there is no such parameter or it doesn’t apply to the useragent specified or the robots.txt entry for this parameter has invalid syntax, return None. New in version 3.6.
site_maps()
Returns the contents of the Sitemap parameter from robots.txt in the form of a list(). If there is no such parameter or the robots.txt entry for this parameter has invalid syntax, return None. New in version 3.8. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser |
can_fetch(useragent, url)
Returns True if the useragent is allowed to fetch the url according to the rules contained in the parsed robots.txt file. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser.can_fetch |
crawl_delay(useragent)
Returns the value of the Crawl-delay parameter from robots.txt for the useragent in question. If there is no such parameter or it doesn’t apply to the useragent specified or the robots.txt entry for this parameter has invalid syntax, return None. New in version 3.6. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser.crawl_delay |
modified()
Sets the time the robots.txt file was last fetched to the current time. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser.modified |
mtime()
Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser.mtime |
parse(lines)
Parses the lines argument. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser.parse |
read()
Reads the robots.txt URL and feeds it to the parser. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser.read |
request_rate(useragent)
Returns the contents of the Request-rate parameter from robots.txt as a named tuple RequestRate(requests, seconds). If there is no such parameter or it doesn’t apply to the useragent specified or the robots.txt entry for this parameter has invalid syntax, return None. New in version 3.6. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser.request_rate |
set_url(url)
Sets the URL referring to a robots.txt file. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser.set_url |
site_maps()
Returns the contents of the Sitemap parameter from robots.txt in the form of a list(). If there is no such parameter or the robots.txt entry for this parameter has invalid syntax, return None. New in version 3.8. | python.library.urllib.robotparser#urllib.robotparser.RobotFileParser.site_maps |
exception UserWarning
Base class for warnings generated by user code. | python.library.exceptions#UserWarning |
uu — Encode and decode uuencode files Source code: Lib/uu.py This module encodes and decodes files in uuencode format, allowing arbitrary binary data to be transferred over ASCII-only connections. Wherever a file argument is expected, the methods accept a file-like object. For backwards compatibility, a string containing a pathname is also accepted, and the corresponding file will be opened for reading and writing; the pathname '-' is understood to mean the standard input or output. However, this interface is deprecated; it’s better for the caller to open the file itself, and be sure that, when required, the mode is 'rb' or 'wb' on Windows. This code was contributed by Lance Ellinghouse, and modified by Jack Jansen. The uu module defines the following functions:
uu.encode(in_file, out_file, name=None, mode=None, *, backtick=False)
Uuencode file in_file into file out_file. The uuencoded file will have the header specifying name and mode as the defaults for the results of decoding the file. The default defaults are taken from in_file, or '-' and 0o666 respectively. If backtick is true, zeros are represented by '`' instead of spaces. Changed in version 3.7: Added the backtick parameter.
uu.decode(in_file, out_file=None, mode=None, quiet=False)
This call decodes uuencoded file in_file placing the result on file out_file. If out_file is a pathname, mode is used to set the permission bits if the file must be created. Defaults for out_file and mode are taken from the uuencode header. However, if the file specified in the header already exists, a uu.Error is raised. decode() may print a warning to standard error if the input was produced by an incorrect uuencoder and Python could recover from that error. Setting quiet to a true value silences this warning.
exception uu.Error
Subclass of Exception, this can be raised by uu.decode() under various situations, such as described above, but also including a badly formatted header, or truncated input file.
See also
Module binascii
Support module containing ASCII-to-binary and binary-to-ASCII conversions. | python.library.uu |
uu.decode(in_file, out_file=None, mode=None, quiet=False)
This call decodes uuencoded file in_file placing the result on file out_file. If out_file is a pathname, mode is used to set the permission bits if the file must be created. Defaults for out_file and mode are taken from the uuencode header. However, if the file specified in the header already exists, a uu.Error is raised. decode() may print a warning to standard error if the input was produced by an incorrect uuencoder and Python could recover from that error. Setting quiet to a true value silences this warning. | python.library.uu#uu.decode |
uu.encode(in_file, out_file, name=None, mode=None, *, backtick=False)
Uuencode file in_file into file out_file. The uuencoded file will have the header specifying name and mode as the defaults for the results of decoding the file. The default defaults are taken from in_file, or '-' and 0o666 respectively. If backtick is true, zeros are represented by '`' instead of spaces. Changed in version 3.7: Added the backtick parameter. | python.library.uu#uu.encode |
exception uu.Error
Subclass of Exception, this can be raised by uu.decode() under various situations, such as described above, but also including a badly formatted header, or truncated input file. | python.library.uu#uu.Error |
uuid — UUID objects according to RFC 4122 Source code: Lib/uuid.py This module provides immutable UUID objects (the UUID class) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122. If all you want is a unique ID, you should probably call uuid1() or uuid4(). Note that uuid1() may compromise privacy since it creates a UUID containing the computer’s network address. uuid4() creates a random UUID. Depending on support from the underlying platform, uuid1() may or may not return a “safe” UUID. A safe UUID is one which is generated using synchronization methods that ensure no two processes can obtain the same UUID. All instances of UUID have an is_safe attribute which relays any information about the UUID’s safety, using this enumeration:
class uuid.SafeUUID
New in version 3.7.
safe
The UUID was generated by the platform in a multiprocessing-safe way.
unsafe
The UUID was not generated in a multiprocessing-safe way.
unknown
The platform does not provide information on whether the UUID was generated safely or not.
class uuid.UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=SafeUUID.unknown)
Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes in big-endian order as the bytes argument, a string of 16 bytes in little-endian order as the bytes_le argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the fields argument, or a single 128-bit integer as the int argument. When a string of hex digits is given, curly braces, hyphens, and a URN prefix are all optional. For example, these expressions all yield the same UUID: UUID('{12345678-1234-5678-1234-567812345678}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes=b'\x12\x34\x56\x78'*4)
UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' +
b'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)
Exactly one of hex, bytes, bytes_le, fields, or int must be given. The version argument is optional; if given, the resulting UUID will have its variant and version number set according to RFC 4122, overriding bits in the given hex, bytes, bytes_le, fields, or int. Comparison of UUID objects are made by way of comparing their UUID.int attributes. Comparison with a non-UUID object raises a TypeError. str(uuid) returns a string in the form 12345678-1234-5678-1234-567812345678 where the 32 hexadecimal digits represent the UUID.
UUID instances have these read-only attributes:
UUID.bytes
The UUID as a 16-byte string (containing the six integer fields in big-endian byte order).
UUID.bytes_le
The UUID as a 16-byte string (with time_low, time_mid, and time_hi_version in little-endian byte order).
UUID.fields
A tuple of the six integer fields of the UUID, which are also available as six individual attributes and two derived attributes:
Field Meaning
time_low the first 32 bits of the UUID
time_mid the next 16 bits of the UUID
time_hi_version the next 16 bits of the UUID
clock_seq_hi_variant the next 8 bits of the UUID
clock_seq_low the next 8 bits of the UUID
node the last 48 bits of the UUID
time the 60-bit timestamp
clock_seq the 14-bit sequence number
UUID.hex
The UUID as a 32-character hexadecimal string.
UUID.int
The UUID as a 128-bit integer.
UUID.urn
The UUID as a URN as specified in RFC 4122.
UUID.variant
The UUID variant, which determines the internal layout of the UUID. This will be one of the constants RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE.
UUID.version
The UUID version number (1 through 5, meaningful only when the variant is RFC_4122).
UUID.is_safe
An enumeration of SafeUUID which indicates whether the platform generated the UUID in a multiprocessing-safe way. New in version 3.7.
The uuid module defines the following functions:
uuid.getnode()
Get the hardware address as a 48-bit positive integer. The first time this runs, it may launch a separate program, which could be quite slow. If all attempts to obtain the hardware address fail, we choose a random 48-bit number with the multicast bit (least significant bit of the first octet) set to 1 as recommended in RFC 4122. “Hardware address” means the MAC address of a network interface. On a machine with multiple network interfaces, universally administered MAC addresses (i.e. where the second least significant bit of the first octet is unset) will be preferred over locally administered MAC addresses, but with no other ordering guarantees. Changed in version 3.7: Universally administered MAC addresses are preferred over locally administered MAC addresses, since the former are guaranteed to be globally unique, while the latter are not.
uuid.uuid1(node=None, clock_seq=None)
Generate a UUID from a host ID, sequence number, and the current time. If node is not given, getnode() is used to obtain the hardware address. If clock_seq is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen.
uuid.uuid3(namespace, name)
Generate a UUID based on the MD5 hash of a namespace identifier (which is a UUID) and a name (which is a string).
uuid.uuid4()
Generate a random UUID.
uuid.uuid5(namespace, name)
Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a UUID) and a name (which is a string).
The uuid module defines the following namespace identifiers for use with uuid3() or uuid5().
uuid.NAMESPACE_DNS
When this namespace is specified, the name string is a fully-qualified domain name.
uuid.NAMESPACE_URL
When this namespace is specified, the name string is a URL.
uuid.NAMESPACE_OID
When this namespace is specified, the name string is an ISO OID.
uuid.NAMESPACE_X500
When this namespace is specified, the name string is an X.500 DN in DER or a text output format.
The uuid module defines the following constants for the possible values of the variant attribute:
uuid.RESERVED_NCS
Reserved for NCS compatibility.
uuid.RFC_4122
Specifies the UUID layout given in RFC 4122.
uuid.RESERVED_MICROSOFT
Reserved for Microsoft compatibility.
uuid.RESERVED_FUTURE
Reserved for future definition.
See also
RFC 4122 - A Universally Unique IDentifier (UUID) URN Namespace
This specification defines a Uniform Resource Name namespace for UUIDs, the internal format of UUIDs, and methods of generating UUIDs. Example Here are some examples of typical usage of the uuid module: >>> import uuid
>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'
>>> # get the raw 16 bytes of the UUID
>>> x.bytes
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f') | python.library.uuid |
uuid.getnode()
Get the hardware address as a 48-bit positive integer. The first time this runs, it may launch a separate program, which could be quite slow. If all attempts to obtain the hardware address fail, we choose a random 48-bit number with the multicast bit (least significant bit of the first octet) set to 1 as recommended in RFC 4122. “Hardware address” means the MAC address of a network interface. On a machine with multiple network interfaces, universally administered MAC addresses (i.e. where the second least significant bit of the first octet is unset) will be preferred over locally administered MAC addresses, but with no other ordering guarantees. Changed in version 3.7: Universally administered MAC addresses are preferred over locally administered MAC addresses, since the former are guaranteed to be globally unique, while the latter are not. | python.library.uuid#uuid.getnode |
uuid.NAMESPACE_DNS
When this namespace is specified, the name string is a fully-qualified domain name. | python.library.uuid#uuid.NAMESPACE_DNS |
uuid.NAMESPACE_OID
When this namespace is specified, the name string is an ISO OID. | python.library.uuid#uuid.NAMESPACE_OID |
uuid.NAMESPACE_URL
When this namespace is specified, the name string is a URL. | python.library.uuid#uuid.NAMESPACE_URL |
uuid.NAMESPACE_X500
When this namespace is specified, the name string is an X.500 DN in DER or a text output format. | python.library.uuid#uuid.NAMESPACE_X500 |
uuid.RESERVED_FUTURE
Reserved for future definition. | python.library.uuid#uuid.RESERVED_FUTURE |
uuid.RESERVED_MICROSOFT
Reserved for Microsoft compatibility. | python.library.uuid#uuid.RESERVED_MICROSOFT |
uuid.RESERVED_NCS
Reserved for NCS compatibility. | python.library.uuid#uuid.RESERVED_NCS |
uuid.RFC_4122
Specifies the UUID layout given in RFC 4122. | python.library.uuid#uuid.RFC_4122 |
class uuid.SafeUUID
New in version 3.7.
safe
The UUID was generated by the platform in a multiprocessing-safe way.
unsafe
The UUID was not generated in a multiprocessing-safe way.
unknown
The platform does not provide information on whether the UUID was generated safely or not. | python.library.uuid#uuid.SafeUUID |
safe
The UUID was generated by the platform in a multiprocessing-safe way. | python.library.uuid#uuid.SafeUUID.safe |
unknown
The platform does not provide information on whether the UUID was generated safely or not. | python.library.uuid#uuid.SafeUUID.unknown |
unsafe
The UUID was not generated in a multiprocessing-safe way. | python.library.uuid#uuid.SafeUUID.unsafe |
class uuid.UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=SafeUUID.unknown)
Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes in big-endian order as the bytes argument, a string of 16 bytes in little-endian order as the bytes_le argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the fields argument, or a single 128-bit integer as the int argument. When a string of hex digits is given, curly braces, hyphens, and a URN prefix are all optional. For example, these expressions all yield the same UUID: UUID('{12345678-1234-5678-1234-567812345678}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes=b'\x12\x34\x56\x78'*4)
UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' +
b'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)
Exactly one of hex, bytes, bytes_le, fields, or int must be given. The version argument is optional; if given, the resulting UUID will have its variant and version number set according to RFC 4122, overriding bits in the given hex, bytes, bytes_le, fields, or int. Comparison of UUID objects are made by way of comparing their UUID.int attributes. Comparison with a non-UUID object raises a TypeError. str(uuid) returns a string in the form 12345678-1234-5678-1234-567812345678 where the 32 hexadecimal digits represent the UUID. | python.library.uuid#uuid.UUID |
UUID.bytes
The UUID as a 16-byte string (containing the six integer fields in big-endian byte order). | python.library.uuid#uuid.UUID.bytes |
UUID.bytes_le
The UUID as a 16-byte string (with time_low, time_mid, and time_hi_version in little-endian byte order). | python.library.uuid#uuid.UUID.bytes_le |
UUID.fields
A tuple of the six integer fields of the UUID, which are also available as six individual attributes and two derived attributes:
Field Meaning
time_low the first 32 bits of the UUID
time_mid the next 16 bits of the UUID
time_hi_version the next 16 bits of the UUID
clock_seq_hi_variant the next 8 bits of the UUID
clock_seq_low the next 8 bits of the UUID
node the last 48 bits of the UUID
time the 60-bit timestamp
clock_seq the 14-bit sequence number | python.library.uuid#uuid.UUID.fields |
UUID.hex
The UUID as a 32-character hexadecimal string. | python.library.uuid#uuid.UUID.hex |
UUID.int
The UUID as a 128-bit integer. | python.library.uuid#uuid.UUID.int |
UUID.is_safe
An enumeration of SafeUUID which indicates whether the platform generated the UUID in a multiprocessing-safe way. New in version 3.7. | python.library.uuid#uuid.UUID.is_safe |
UUID.urn
The UUID as a URN as specified in RFC 4122. | python.library.uuid#uuid.UUID.urn |
UUID.variant
The UUID variant, which determines the internal layout of the UUID. This will be one of the constants RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE. | python.library.uuid#uuid.UUID.variant |
UUID.version
The UUID version number (1 through 5, meaningful only when the variant is RFC_4122). | python.library.uuid#uuid.UUID.version |
uuid.uuid1(node=None, clock_seq=None)
Generate a UUID from a host ID, sequence number, and the current time. If node is not given, getnode() is used to obtain the hardware address. If clock_seq is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen. | python.library.uuid#uuid.uuid1 |
uuid.uuid3(namespace, name)
Generate a UUID based on the MD5 hash of a namespace identifier (which is a UUID) and a name (which is a string). | python.library.uuid#uuid.uuid3 |
uuid.uuid4()
Generate a random UUID. | python.library.uuid#uuid.uuid4 |
uuid.uuid5(namespace, name)
Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a UUID) and a name (which is a string). | python.library.uuid#uuid.uuid5 |
exception ValueError
Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError. | python.library.exceptions#ValueError |
vars([object])
Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a types.MappingProxyType to prevent direct dictionary updates). Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored. A TypeError exception is raised if an object is specified but it doesn’t have a __dict__ attribute (for example, if its class defines the __slots__ attribute). | python.library.functions#vars |
venv — Creation of virtual environments New in version 3.3. Source code: Lib/venv/ The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories. See PEP 405 for more information about Python virtual environments. See also Python Packaging User Guide: Creating and using virtual environments Creating virtual environments Creation of virtual environments is done by executing the command venv: python3 -m venv /path/to/new/virtual/environment
Running this command creates the target directory (creating any parent directories that don’t exist already) and places a pyvenv.cfg file in it with a home key pointing to the Python installation from which the command was run (a common name for the target directory is .venv). It also creates a bin (or Scripts on Windows) subdirectory containing a copy/symlink of the Python binary/binaries (as appropriate for the platform or arguments used at environment creation time). It also creates an (initially empty) lib/pythonX.Y/site-packages subdirectory (on Windows, this is Lib\site-packages). If an existing directory is specified, it will be re-used. Deprecated since version 3.6: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6. Changed in version 3.5: The use of venv is now recommended for creating virtual environments. On Windows, invoke the venv command as follows: c:\>c:\Python35\python -m venv c:\path\to\myenv
Alternatively, if you configured the PATH and PATHEXT variables for your Python installation: c:\>python -m venv c:\path\to\myenv
The command, if run with -h, will show the available options: usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
[--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
ENV_DIR [ENV_DIR ...]
Creates virtual Python environments in one or more target directories.
positional arguments:
ENV_DIR A directory to create the environment in.
optional arguments:
-h, --help show this help message and exit
--system-site-packages
Give the virtual environment access to the system
site-packages dir.
--symlinks Try to use symlinks rather than copies, when symlinks
are not the default for the platform.
--copies Try to use copies rather than symlinks, even when
symlinks are the default for the platform.
--clear Delete the contents of the environment directory if it
already exists, before environment creation.
--upgrade Upgrade the environment directory to use this version
of Python, assuming Python has been upgraded in-place.
--without-pip Skips installing or upgrading pip in the virtual
environment (pip is bootstrapped by default)
--prompt PROMPT Provides an alternative prompt prefix for this
environment.
--upgrade-deps Upgrade core dependencies: pip setuptools to the
latest version in PyPI
Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
Changed in version 3.9: Add --upgrade-deps option to upgrade pip + setuptools to the latest on PyPI Changed in version 3.4: Installs pip by default, added the --without-pip and --copies options Changed in version 3.4: In earlier versions, if the target directory already existed, an error was raised, unless the --clear or --upgrade option was provided. Note While symlinks are supported on Windows, they are not recommended. Of particular note is that double-clicking python.exe in File Explorer will resolve the symlink eagerly and ignore the virtual environment. Note On Microsoft Windows, it may be required to enable the Activate.ps1 script by setting the execution policy for the user. You can do this by issuing the following PowerShell command: PS C:> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser See About Execution Policies for more information. The created pyvenv.cfg file also includes the include-system-site-packages key, set to true if venv is run with the --system-site-packages option, false otherwise. Unless the --without-pip option is given, ensurepip will be invoked to bootstrap pip into the virtual environment. Multiple paths can be given to venv, in which case an identical virtual environment will be created, according to the given options, at each provided path. Once a virtual environment has been created, it can be “activated” using a script in the virtual environment’s binary directory. The invocation of the script is platform-specific (<venv> must be replaced by the path of the directory containing the virtual environment):
Platform Shell Command to activate virtual environment
POSIX bash/zsh $ source <venv>/bin/activate
fish $ source <venv>/bin/activate.fish
csh/tcsh $ source <venv>/bin/activate.csh
PowerShell Core $ <venv>/bin/Activate.ps1
Windows cmd.exe C:\> <venv>\Scripts\activate.bat
PowerShell PS C:\> <venv>\Scripts\Activate.ps1 When a virtual environment is active, the VIRTUAL_ENV environment variable is set to the path of the virtual environment. This can be used to check if one is running inside a virtual environment. You don’t specifically need to activate an environment; activation just prepends the virtual environment’s binary directory to your path, so that “python” invokes the virtual environment’s Python interpreter and you can run installed scripts without having to use their full path. However, all scripts installed in a virtual environment should be runnable without activating it, and run with the virtual environment’s Python automatically. You can deactivate a virtual environment by typing “deactivate” in your shell. The exact mechanism is platform-specific and is an internal implementation detail (typically a script or shell function will be used). New in version 3.4: fish and csh activation scripts. New in version 3.8: PowerShell activation scripts installed under POSIX for PowerShell Core support. Note A virtual environment is a Python environment such that the Python interpreter, libraries and scripts installed into it are isolated from those installed in other virtual environments, and (by default) any libraries installed in a “system” Python, i.e., one which is installed as part of your operating system. A virtual environment is a directory tree which contains Python executable files and other files which indicate that it is a virtual environment. Common installation tools such as setuptools and pip work as expected with virtual environments. In other words, when a virtual environment is active, they install Python packages into the virtual environment without needing to be told to do so explicitly. When a virtual environment is active (i.e., the virtual environment’s Python interpreter is running), the attributes sys.prefix and sys.exec_prefix point to the base directory of the virtual environment, whereas sys.base_prefix and sys.base_exec_prefix point to the non-virtual environment Python installation which was used to create the virtual environment. If a virtual environment is not active, then sys.prefix is the same as sys.base_prefix and sys.exec_prefix is the same as sys.base_exec_prefix (they all point to a non-virtual environment Python installation). When a virtual environment is active, any options that change the installation path will be ignored from all distutils configuration files to prevent projects being inadvertently installed outside of the virtual environment. When working in a command shell, users can make a virtual environment active by running an activate script in the virtual environment’s executables directory (the precise filename and command to use the file is shell-dependent), which prepends the virtual environment’s directory for executables to the PATH environment variable for the running shell. There should be no need in other circumstances to activate a virtual environment; scripts installed into virtual environments have a “shebang” line which points to the virtual environment’s Python interpreter. This means that the script will run with that interpreter regardless of the value of PATH. On Windows, “shebang” line processing is supported if you have the Python Launcher for Windows installed (this was added to Python in 3.3 - see PEP 397 for more details). Thus, double-clicking an installed script in a Windows Explorer window should run the script with the correct interpreter without there needing to be any reference to its virtual environment in PATH. API The high-level method described above makes use of a simple API which provides mechanisms for third-party virtual environment creators to customize environment creation according to their needs, the EnvBuilder class.
class venv.EnvBuilder(system_site_packages=False, clear=False, symlinks=False, upgrade=False, with_pip=False, prompt=None, upgrade_deps=False)
The EnvBuilder class accepts the following keyword arguments on instantiation:
system_site_packages – a Boolean value indicating that the system Python site-packages should be available to the environment (defaults to False).
clear – a Boolean value which, if true, will delete the contents of any existing target directory, before creating the environment.
symlinks – a Boolean value indicating whether to attempt to symlink the Python binary rather than copying.
upgrade – a Boolean value which, if true, will upgrade an existing environment with the running Python - for use when that Python has been upgraded in-place (defaults to False).
with_pip – a Boolean value which, if true, ensures pip is installed in the virtual environment. This uses ensurepip with the --default-pip option.
prompt – a String to be used after virtual environment is activated (defaults to None which means directory name of the environment would be used). If the special string "." is provided, the basename of the current directory is used as the prompt.
upgrade_deps – Update the base venv modules to the latest on PyPI Changed in version 3.4: Added the with_pip parameter New in version 3.6: Added the prompt parameter New in version 3.9: Added the upgrade_deps parameter Creators of third-party virtual environment tools will be free to use the provided EnvBuilder class as a base class. The returned env-builder is an object which has a method, create:
create(env_dir)
Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The create method will either create the environment in the specified directory, or raise an appropriate exception. The create method of the EnvBuilder class illustrates the hooks available for subclass customization: def create(self, env_dir):
"""
Create a virtualized Python environment in a directory.
env_dir is the target directory to create an environment in.
"""
env_dir = os.path.abspath(env_dir)
context = self.ensure_directories(env_dir)
self.create_configuration(context)
self.setup_python(context)
self.setup_scripts(context)
self.post_setup(context)
Each of the methods ensure_directories(), create_configuration(), setup_python(), setup_scripts() and post_setup() can be overridden.
ensure_directories(env_dir)
Creates the environment directory and all necessary directories, and returns a context object. This is just a holder for attributes (such as paths), for use by the other methods. The directories are allowed to exist already, as long as either clear or upgrade were specified to allow operating on an existing environment directory.
create_configuration(context)
Creates the pyvenv.cfg configuration file in the environment.
setup_python(context)
Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist.
setup_scripts(context)
Installs activation scripts appropriate to the platform into the virtual environment.
upgrade_dependencies(context)
Upgrades the core venv dependency packages (currently pip and setuptools) in the environment. This is done by shelling out to the pip executable in the environment. New in version 3.9.
post_setup(context)
A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps.
Changed in version 3.7.2: Windows now uses redirector scripts for python[w].exe instead of copying the actual binaries. In 3.7.2 only setup_python() does nothing unless running from a build in the source tree. Changed in version 3.7.3: Windows copies the redirector scripts as part of setup_python() instead of setup_scripts(). This was not the case in 3.7.2. When using symlinks, the original executables will be linked. In addition, EnvBuilder provides this utility method that can be called from setup_scripts() or post_setup() in subclasses to assist in installing custom scripts into the virtual environment.
install_scripts(context, path)
path is the path to a directory that should contain subdirectories “common”, “posix”, “nt”, each containing scripts destined for the bin directory in the environment. The contents of “common” and the directory corresponding to os.name are copied after some text replacement of placeholders:
__VENV_DIR__ is replaced with the absolute path of the environment directory.
__VENV_NAME__ is replaced with the environment name (final path segment of environment directory).
__VENV_PROMPT__ is replaced with the prompt (the environment name surrounded by parentheses and with a following space)
__VENV_BIN_NAME__ is replaced with the name of the bin directory (either bin or Scripts).
__VENV_PYTHON__ is replaced with the absolute path of the environment’s executable. The directories are allowed to exist (for when an existing environment is being upgraded).
There is also a module-level convenience function:
venv.create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None)
Create an EnvBuilder with the given keyword arguments, and call its create() method with the env_dir argument. New in version 3.3. Changed in version 3.4: Added the with_pip parameter Changed in version 3.6: Added the prompt parameter
An example of extending EnvBuilder
The following script shows how to extend EnvBuilder by implementing a subclass which installs setuptools and pip into a created virtual environment: import os
import os.path
from subprocess import Popen, PIPE
import sys
from threading import Thread
from urllib.parse import urlparse
from urllib.request import urlretrieve
import venv
class ExtendedEnvBuilder(venv.EnvBuilder):
"""
This builder installs setuptools and pip so that you can pip or
easy_install other packages into the created virtual environment.
:param nodist: If true, setuptools and pip are not installed into the
created virtual environment.
:param nopip: If true, pip is not installed into the created
virtual environment.
:param progress: If setuptools or pip are installed, the progress of the
installation can be monitored by passing a progress
callable. If specified, it is called with two
arguments: a string indicating some progress, and a
context indicating where the string is coming from.
The context argument can have one of three values:
'main', indicating that it is called from virtualize()
itself, and 'stdout' and 'stderr', which are obtained
by reading lines from the output streams of a subprocess
which is used to install the app.
If a callable is not specified, default progress
information is output to sys.stderr.
"""
def __init__(self, *args, **kwargs):
self.nodist = kwargs.pop('nodist', False)
self.nopip = kwargs.pop('nopip', False)
self.progress = kwargs.pop('progress', None)
self.verbose = kwargs.pop('verbose', False)
super().__init__(*args, **kwargs)
def post_setup(self, context):
"""
Set up any packages which need to be pre-installed into the
virtual environment being created.
:param context: The information for the virtual environment
creation request being processed.
"""
os.environ['VIRTUAL_ENV'] = context.env_dir
if not self.nodist:
self.install_setuptools(context)
# Can't install pip without setuptools
if not self.nopip and not self.nodist:
self.install_pip(context)
def reader(self, stream, context):
"""
Read lines from a subprocess' output stream and either pass to a progress
callable (if specified) or write progress information to sys.stderr.
"""
progress = self.progress
while True:
s = stream.readline()
if not s:
break
if progress is not None:
progress(s, context)
else:
if not self.verbose:
sys.stderr.write('.')
else:
sys.stderr.write(s.decode('utf-8'))
sys.stderr.flush()
stream.close()
def install_script(self, context, name, url):
_, _, path, _, _, _ = urlparse(url)
fn = os.path.split(path)[-1]
binpath = context.bin_path
distpath = os.path.join(binpath, fn)
# Download script into the virtual environment's binaries folder
urlretrieve(url, distpath)
progress = self.progress
if self.verbose:
term = '\n'
else:
term = ''
if progress is not None:
progress('Installing %s ...%s' % (name, term), 'main')
else:
sys.stderr.write('Installing %s ...%s' % (name, term))
sys.stderr.flush()
# Install in the virtual environment
args = [context.env_exe, fn]
p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
t1.start()
t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
t2.start()
p.wait()
t1.join()
t2.join()
if progress is not None:
progress('done.', 'main')
else:
sys.stderr.write('done.\n')
# Clean up - no longer needed
os.unlink(distpath)
def install_setuptools(self, context):
"""
Install setuptools in the virtual environment.
:param context: The information for the virtual environment
creation request being processed.
"""
url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
self.install_script(context, 'setuptools', url)
# clear up the setuptools archive which gets downloaded
pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
files = filter(pred, os.listdir(context.bin_path))
for f in files:
f = os.path.join(context.bin_path, f)
os.unlink(f)
def install_pip(self, context):
"""
Install pip in the virtual environment.
:param context: The information for the virtual environment
creation request being processed.
"""
url = 'https://bootstrap.pypa.io/get-pip.py'
self.install_script(context, 'pip', url)
def main(args=None):
compatible = True
if sys.version_info < (3, 3):
compatible = False
elif not hasattr(sys, 'base_prefix'):
compatible = False
if not compatible:
raise ValueError('This script is only for use with '
'Python 3.3 or later')
else:
import argparse
parser = argparse.ArgumentParser(prog=__name__,
description='Creates virtual Python '
'environments in one or '
'more target '
'directories.')
parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
help='A directory in which to create the
'virtual environment.')
parser.add_argument('--no-setuptools', default=False,
action='store_true', dest='nodist',
help="Don't install setuptools or pip in the "
"virtual environment.")
parser.add_argument('--no-pip', default=False,
action='store_true', dest='nopip',
help="Don't install pip in the virtual "
"environment.")
parser.add_argument('--system-site-packages', default=False,
action='store_true', dest='system_site',
help='Give the virtual environment access to the '
'system site-packages dir.')
if os.name == 'nt':
use_symlinks = False
else:
use_symlinks = True
parser.add_argument('--symlinks', default=use_symlinks,
action='store_true', dest='symlinks',
help='Try to use symlinks rather than copies, '
'when symlinks are not the default for '
'the platform.')
parser.add_argument('--clear', default=False, action='store_true',
dest='clear', help='Delete the contents of the '
'virtual environment '
'directory if it already '
'exists, before virtual '
'environment creation.')
parser.add_argument('--upgrade', default=False, action='store_true',
dest='upgrade', help='Upgrade the virtual '
'environment directory to '
'use this version of '
'Python, assuming Python '
'has been upgraded '
'in-place.')
parser.add_argument('--verbose', default=False, action='store_true',
dest='verbose', help='Display the output '
'from the scripts which '
'install setuptools and pip.')
options = parser.parse_args(args)
if options.upgrade and options.clear:
raise ValueError('you cannot supply --upgrade and --clear together.')
builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
clear=options.clear,
symlinks=options.symlinks,
upgrade=options.upgrade,
nodist=options.nodist,
nopip=options.nopip,
verbose=options.verbose)
for d in options.dirs:
builder.create(d)
if __name__ == '__main__':
rc = 1
try:
main()
rc = 0
except Exception as e:
print('Error: %s' % e, file=sys.stderr)
sys.exit(rc)
This script is also available for download online. | python.library.venv |
venv.create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None)
Create an EnvBuilder with the given keyword arguments, and call its create() method with the env_dir argument. New in version 3.3. Changed in version 3.4: Added the with_pip parameter Changed in version 3.6: Added the prompt parameter | python.library.venv#venv.create |
class venv.EnvBuilder(system_site_packages=False, clear=False, symlinks=False, upgrade=False, with_pip=False, prompt=None, upgrade_deps=False)
The EnvBuilder class accepts the following keyword arguments on instantiation:
system_site_packages – a Boolean value indicating that the system Python site-packages should be available to the environment (defaults to False).
clear – a Boolean value which, if true, will delete the contents of any existing target directory, before creating the environment.
symlinks – a Boolean value indicating whether to attempt to symlink the Python binary rather than copying.
upgrade – a Boolean value which, if true, will upgrade an existing environment with the running Python - for use when that Python has been upgraded in-place (defaults to False).
with_pip – a Boolean value which, if true, ensures pip is installed in the virtual environment. This uses ensurepip with the --default-pip option.
prompt – a String to be used after virtual environment is activated (defaults to None which means directory name of the environment would be used). If the special string "." is provided, the basename of the current directory is used as the prompt.
upgrade_deps – Update the base venv modules to the latest on PyPI Changed in version 3.4: Added the with_pip parameter New in version 3.6: Added the prompt parameter New in version 3.9: Added the upgrade_deps parameter Creators of third-party virtual environment tools will be free to use the provided EnvBuilder class as a base class. The returned env-builder is an object which has a method, create:
create(env_dir)
Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The create method will either create the environment in the specified directory, or raise an appropriate exception. The create method of the EnvBuilder class illustrates the hooks available for subclass customization: def create(self, env_dir):
"""
Create a virtualized Python environment in a directory.
env_dir is the target directory to create an environment in.
"""
env_dir = os.path.abspath(env_dir)
context = self.ensure_directories(env_dir)
self.create_configuration(context)
self.setup_python(context)
self.setup_scripts(context)
self.post_setup(context)
Each of the methods ensure_directories(), create_configuration(), setup_python(), setup_scripts() and post_setup() can be overridden.
ensure_directories(env_dir)
Creates the environment directory and all necessary directories, and returns a context object. This is just a holder for attributes (such as paths), for use by the other methods. The directories are allowed to exist already, as long as either clear or upgrade were specified to allow operating on an existing environment directory.
create_configuration(context)
Creates the pyvenv.cfg configuration file in the environment.
setup_python(context)
Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist.
setup_scripts(context)
Installs activation scripts appropriate to the platform into the virtual environment.
upgrade_dependencies(context)
Upgrades the core venv dependency packages (currently pip and setuptools) in the environment. This is done by shelling out to the pip executable in the environment. New in version 3.9.
post_setup(context)
A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps.
Changed in version 3.7.2: Windows now uses redirector scripts for python[w].exe instead of copying the actual binaries. In 3.7.2 only setup_python() does nothing unless running from a build in the source tree. Changed in version 3.7.3: Windows copies the redirector scripts as part of setup_python() instead of setup_scripts(). This was not the case in 3.7.2. When using symlinks, the original executables will be linked. In addition, EnvBuilder provides this utility method that can be called from setup_scripts() or post_setup() in subclasses to assist in installing custom scripts into the virtual environment.
install_scripts(context, path)
path is the path to a directory that should contain subdirectories “common”, “posix”, “nt”, each containing scripts destined for the bin directory in the environment. The contents of “common” and the directory corresponding to os.name are copied after some text replacement of placeholders:
__VENV_DIR__ is replaced with the absolute path of the environment directory.
__VENV_NAME__ is replaced with the environment name (final path segment of environment directory).
__VENV_PROMPT__ is replaced with the prompt (the environment name surrounded by parentheses and with a following space)
__VENV_BIN_NAME__ is replaced with the name of the bin directory (either bin or Scripts).
__VENV_PYTHON__ is replaced with the absolute path of the environment’s executable. The directories are allowed to exist (for when an existing environment is being upgraded). | python.library.venv#venv.EnvBuilder |
create(env_dir)
Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The create method will either create the environment in the specified directory, or raise an appropriate exception. The create method of the EnvBuilder class illustrates the hooks available for subclass customization: def create(self, env_dir):
"""
Create a virtualized Python environment in a directory.
env_dir is the target directory to create an environment in.
"""
env_dir = os.path.abspath(env_dir)
context = self.ensure_directories(env_dir)
self.create_configuration(context)
self.setup_python(context)
self.setup_scripts(context)
self.post_setup(context)
Each of the methods ensure_directories(), create_configuration(), setup_python(), setup_scripts() and post_setup() can be overridden. | python.library.venv#venv.EnvBuilder.create |
create_configuration(context)
Creates the pyvenv.cfg configuration file in the environment. | python.library.venv#venv.EnvBuilder.create_configuration |
ensure_directories(env_dir)
Creates the environment directory and all necessary directories, and returns a context object. This is just a holder for attributes (such as paths), for use by the other methods. The directories are allowed to exist already, as long as either clear or upgrade were specified to allow operating on an existing environment directory. | python.library.venv#venv.EnvBuilder.ensure_directories |
install_scripts(context, path)
path is the path to a directory that should contain subdirectories “common”, “posix”, “nt”, each containing scripts destined for the bin directory in the environment. The contents of “common” and the directory corresponding to os.name are copied after some text replacement of placeholders:
__VENV_DIR__ is replaced with the absolute path of the environment directory.
__VENV_NAME__ is replaced with the environment name (final path segment of environment directory).
__VENV_PROMPT__ is replaced with the prompt (the environment name surrounded by parentheses and with a following space)
__VENV_BIN_NAME__ is replaced with the name of the bin directory (either bin or Scripts).
__VENV_PYTHON__ is replaced with the absolute path of the environment’s executable. The directories are allowed to exist (for when an existing environment is being upgraded). | python.library.venv#venv.EnvBuilder.install_scripts |
post_setup(context)
A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps. | python.library.venv#venv.EnvBuilder.post_setup |
setup_python(context)
Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist. | python.library.venv#venv.EnvBuilder.setup_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.