eventlet.green package¶
Subpackages¶
- eventlet.green.OpenSSL package
- eventlet.green.http package
- Submodules
- eventlet.green.http.client module
BadStatusLine
CannotSendHeader
CannotSendRequest
HTTPConnection
HTTPConnection.auto_open
HTTPConnection.close()
HTTPConnection.connect()
HTTPConnection.debuglevel
HTTPConnection.default_port
HTTPConnection.endheaders()
HTTPConnection.getresponse()
HTTPConnection.putheader()
HTTPConnection.putrequest()
HTTPConnection.request()
HTTPConnection.response_class
HTTPConnection.send()
HTTPConnection.set_debuglevel()
HTTPConnection.set_tunnel()
HTTPException
HTTPResponse
HTTPResponse.begin()
HTTPResponse.close()
HTTPResponse.fileno()
HTTPResponse.flush()
HTTPResponse.getcode()
HTTPResponse.getheader()
HTTPResponse.getheaders()
HTTPResponse.geturl()
HTTPResponse.info()
HTTPResponse.isclosed()
HTTPResponse.peek()
HTTPResponse.read()
HTTPResponse.read1()
HTTPResponse.readable()
HTTPResponse.readinto()
HTTPResponse.readline()
HTTPSConnection
ImproperConnectionState
IncompleteRead
InvalidURL
LineTooLong
NotConnected
RemoteDisconnected
ResponseNotReady
UnimplementedFileMode
UnknownProtocol
UnknownTransferEncoding
error
- eventlet.green.http.cookiejar module
Cookie
CookieJar
CookieJar.add_cookie_header()
CookieJar.clear()
CookieJar.clear_expired_cookies()
CookieJar.clear_session_cookies()
CookieJar.domain_re
CookieJar.dots_re
CookieJar.extract_cookies()
CookieJar.magic_re
CookieJar.make_cookies()
CookieJar.non_word_re
CookieJar.quote_re
CookieJar.set_cookie()
CookieJar.set_cookie_if_ok()
CookieJar.set_policy()
CookieJar.strict_domain_re
CookiePolicy
DefaultCookiePolicy
DefaultCookiePolicy.DomainLiberal
DefaultCookiePolicy.DomainRFC2965Match
DefaultCookiePolicy.DomainStrict
DefaultCookiePolicy.DomainStrictNoDots
DefaultCookiePolicy.DomainStrictNonDomain
DefaultCookiePolicy.allowed_domains()
DefaultCookiePolicy.blocked_domains()
DefaultCookiePolicy.domain_return_ok()
DefaultCookiePolicy.is_blocked()
DefaultCookiePolicy.is_not_allowed()
DefaultCookiePolicy.path_return_ok()
DefaultCookiePolicy.return_ok()
DefaultCookiePolicy.return_ok_domain()
DefaultCookiePolicy.return_ok_expires()
DefaultCookiePolicy.return_ok_port()
DefaultCookiePolicy.return_ok_secure()
DefaultCookiePolicy.return_ok_verifiability()
DefaultCookiePolicy.return_ok_version()
DefaultCookiePolicy.set_allowed_domains()
DefaultCookiePolicy.set_blocked_domains()
DefaultCookiePolicy.set_ok()
DefaultCookiePolicy.set_ok_domain()
DefaultCookiePolicy.set_ok_name()
DefaultCookiePolicy.set_ok_path()
DefaultCookiePolicy.set_ok_port()
DefaultCookiePolicy.set_ok_verifiability()
DefaultCookiePolicy.set_ok_version()
FileCookieJar
LWPCookieJar
LoadError
MozillaCookieJar
- eventlet.green.http.cookies module
- eventlet.green.http.server module
- Notes on CGIHTTPRequestHandler
BaseHTTPRequestHandler
BaseHTTPRequestHandler.MessageClass
BaseHTTPRequestHandler.address_string()
BaseHTTPRequestHandler.date_time_string()
BaseHTTPRequestHandler.default_request_version
BaseHTTPRequestHandler.end_headers()
BaseHTTPRequestHandler.error_content_type
BaseHTTPRequestHandler.error_message_format
BaseHTTPRequestHandler.flush_headers()
BaseHTTPRequestHandler.handle()
BaseHTTPRequestHandler.handle_expect_100()
BaseHTTPRequestHandler.handle_one_request()
BaseHTTPRequestHandler.log_date_time_string()
BaseHTTPRequestHandler.log_error()
BaseHTTPRequestHandler.log_message()
BaseHTTPRequestHandler.log_request()
BaseHTTPRequestHandler.monthname
BaseHTTPRequestHandler.parse_request()
BaseHTTPRequestHandler.protocol_version
BaseHTTPRequestHandler.responses
BaseHTTPRequestHandler.send_error()
BaseHTTPRequestHandler.send_header()
BaseHTTPRequestHandler.send_response()
BaseHTTPRequestHandler.send_response_only()
BaseHTTPRequestHandler.server_version
BaseHTTPRequestHandler.sys_version
BaseHTTPRequestHandler.version_string()
BaseHTTPRequestHandler.weekdayname
CGIHTTPRequestHandler
CGIHTTPRequestHandler.cgi_directories
CGIHTTPRequestHandler.do_POST()
CGIHTTPRequestHandler.have_fork
CGIHTTPRequestHandler.is_cgi()
CGIHTTPRequestHandler.is_executable()
CGIHTTPRequestHandler.is_python()
CGIHTTPRequestHandler.rbufsize
CGIHTTPRequestHandler.run_cgi()
CGIHTTPRequestHandler.send_head()
HTTPServer
SimpleHTTPRequestHandler
SimpleHTTPRequestHandler.copyfile()
SimpleHTTPRequestHandler.do_GET()
SimpleHTTPRequestHandler.do_HEAD()
SimpleHTTPRequestHandler.extensions_map
SimpleHTTPRequestHandler.guess_type()
SimpleHTTPRequestHandler.list_directory()
SimpleHTTPRequestHandler.send_head()
SimpleHTTPRequestHandler.server_version
SimpleHTTPRequestHandler.translate_path()
- Module contents
HTTPStatus
HTTPStatus.ACCEPTED
HTTPStatus.ALREADY_REPORTED
HTTPStatus.BAD_GATEWAY
HTTPStatus.BAD_REQUEST
HTTPStatus.CONFLICT
HTTPStatus.CONTINUE
HTTPStatus.CREATED
HTTPStatus.EXPECTATION_FAILED
HTTPStatus.FAILED_DEPENDENCY
HTTPStatus.FORBIDDEN
HTTPStatus.FOUND
HTTPStatus.GATEWAY_TIMEOUT
HTTPStatus.GONE
HTTPStatus.HTTP_VERSION_NOT_SUPPORTED
HTTPStatus.IM_USED
HTTPStatus.INSUFFICIENT_STORAGE
HTTPStatus.INTERNAL_SERVER_ERROR
HTTPStatus.LENGTH_REQUIRED
HTTPStatus.LOCKED
HTTPStatus.LOOP_DETECTED
HTTPStatus.METHOD_NOT_ALLOWED
HTTPStatus.MOVED_PERMANENTLY
HTTPStatus.MULTIPLE_CHOICES
HTTPStatus.MULTI_STATUS
HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED
HTTPStatus.NON_AUTHORITATIVE_INFORMATION
HTTPStatus.NOT_ACCEPTABLE
HTTPStatus.NOT_EXTENDED
HTTPStatus.NOT_FOUND
HTTPStatus.NOT_IMPLEMENTED
HTTPStatus.NOT_MODIFIED
HTTPStatus.NO_CONTENT
HTTPStatus.OK
HTTPStatus.PARTIAL_CONTENT
HTTPStatus.PAYMENT_REQUIRED
HTTPStatus.PERMANENT_REDIRECT
HTTPStatus.PRECONDITION_FAILED
HTTPStatus.PRECONDITION_REQUIRED
HTTPStatus.PROCESSING
HTTPStatus.PROXY_AUTHENTICATION_REQUIRED
HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE
HTTPStatus.REQUEST_ENTITY_TOO_LARGE
HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE
HTTPStatus.REQUEST_TIMEOUT
HTTPStatus.REQUEST_URI_TOO_LONG
HTTPStatus.RESET_CONTENT
HTTPStatus.SEE_OTHER
HTTPStatus.SERVICE_UNAVAILABLE
HTTPStatus.SWITCHING_PROTOCOLS
HTTPStatus.TEMPORARY_REDIRECT
HTTPStatus.TOO_MANY_REQUESTS
HTTPStatus.UNAUTHORIZED
HTTPStatus.UNPROCESSABLE_ENTITY
HTTPStatus.UNSUPPORTED_MEDIA_TYPE
HTTPStatus.UPGRADE_REQUIRED
HTTPStatus.USE_PROXY
HTTPStatus.VARIANT_ALSO_NEGOTIATES
- eventlet.green.urllib package
- Submodules
- eventlet.green.urllib.error module
- eventlet.green.urllib.parse module
- eventlet.green.urllib.request module
AbstractBasicAuthHandler
AbstractDigestAuthHandler
AbstractDigestAuthHandler.get_algorithm_impls()
AbstractDigestAuthHandler.get_authorization()
AbstractDigestAuthHandler.get_cnonce()
AbstractDigestAuthHandler.get_entity_digest()
AbstractDigestAuthHandler.http_error_auth_reqed()
AbstractDigestAuthHandler.reset_retry_count()
AbstractDigestAuthHandler.retry_http_digest_auth()
BaseHandler
CacheFTPHandler
DataHandler
FTPHandler
FancyURLopener
FancyURLopener.get_user_passwd()
FancyURLopener.http_error_301()
FancyURLopener.http_error_302()
FancyURLopener.http_error_303()
FancyURLopener.http_error_307()
FancyURLopener.http_error_308()
FancyURLopener.http_error_401()
FancyURLopener.http_error_407()
FancyURLopener.http_error_default()
FancyURLopener.prompt_user_passwd()
FancyURLopener.redirect_internal()
FancyURLopener.retry_http_basic_auth()
FancyURLopener.retry_https_basic_auth()
FancyURLopener.retry_proxy_http_basic_auth()
FancyURLopener.retry_proxy_https_basic_auth()
FileHandler
HTTPBasicAuthHandler
HTTPCookieProcessor
HTTPDefaultErrorHandler
HTTPDigestAuthHandler
HTTPErrorProcessor
HTTPHandler
HTTPPasswordMgr
HTTPPasswordMgrWithDefaultRealm
HTTPPasswordMgrWithPriorAuth
HTTPRedirectHandler
HTTPRedirectHandler.http_error_301()
HTTPRedirectHandler.http_error_302()
HTTPRedirectHandler.http_error_303()
HTTPRedirectHandler.http_error_307()
HTTPRedirectHandler.http_error_308()
HTTPRedirectHandler.inf_msg
HTTPRedirectHandler.max_redirections
HTTPRedirectHandler.max_repeats
HTTPRedirectHandler.redirect_request()
HTTPSHandler
OpenerDirector
ProxyBasicAuthHandler
ProxyDigestAuthHandler
ProxyHandler
Request
URLopener
URLopener.addheader()
URLopener.cleanup()
URLopener.close()
URLopener.http_error()
URLopener.http_error_default()
URLopener.open()
URLopener.open_data()
URLopener.open_file()
URLopener.open_ftp()
URLopener.open_http()
URLopener.open_https()
URLopener.open_local_file()
URLopener.open_unknown()
URLopener.open_unknown_proxy()
URLopener.retrieve()
URLopener.version
UnknownHandler
build_opener()
getproxies()
install_opener()
pathname2url()
url2pathname()
urlcleanup()
urlopen()
urlretrieve()
- eventlet.green.urllib.response module
- Module contents
Submodules¶
eventlet.green.BaseHTTPServer module¶
HTTP server classes.
Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST, and CGIHTTPRequestHandler for CGI scripts.
It does, however, optionally implement HTTP/1.1 persistent connections, as of version 0.3.
Notes on CGIHTTPRequestHandler¶
This class implements GET and POST requests to cgi-bin scripts.
If the os.fork() function is not present (e.g. on Windows), subprocess.Popen() is used as a fallback, with slightly altered semantics.
In all cases, the implementation is intentionally naive -- all requests are executed synchronously.
SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL -- it may execute arbitrary Python code or external programs.
Note that status code 200 is sent prior to execution of a CGI script, so scripts cannot send other status codes such as 302 (redirect).
XXX To do:
log requests even later (to capture byte count)
log user-agent header and other interesting goodies
send error log to separate file
- class eventlet.green.BaseHTTPServer.BaseHTTPRequestHandler(request, client_address, server)¶
-
HTTP request handler base class.
The following explanation of HTTP serves to guide you through the code as well as to expose any misunderstandings I may have about HTTP (so you don't need to read the code to figure out I'm wrong :-).
HTTP (HyperText Transfer Protocol) is an extensible protocol on top of a reliable stream transport (e.g. TCP/IP). The protocol recognizes three parts to a request:
One line identifying the request type and path
An optional set of RFC-822-style headers
An optional data part
The headers and data are separated by a blank line.
The first line of the request has the form
<command> <path> <version>
where <command> is a (case-sensitive) keyword such as GET or POST, <path> is a string containing path information for the request, and <version> should be the string "HTTP/1.0" or "HTTP/1.1". <path> is encoded using the URL encoding scheme (using %xx to signify the ASCII character with hex code xx).
The specification specifies that lines are separated by CRLF but for compatibility with the widest range of clients recommends servers also handle LF. Similarly, whitespace in the request line is treated sensibly (allowing multiple spaces between components and allowing trailing whitespace).
Similarly, for output, lines ought to be separated by CRLF pairs but most clients grok LF characters just fine.
If the first line of the request has the form
<command> <path>
(i.e. <version> is left out) then this is assumed to be an HTTP 0.9 request; this form has no optional headers and data part and the reply consists of just the data.
The reply form of the HTTP 1.x protocol again has three parts:
One line giving the response code
An optional set of RFC-822-style headers
The data
Again, the headers and data are separated by a blank line.
The response code line has the form
<version> <responsecode> <responsestring>
where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"), <responsecode> is a 3-digit response code indicating success or failure of the request, and <responsestring> is an optional human-readable string explaining what the response code means.
This server parses the request and the headers, and then calls a function specific to the request type (<command>). Specifically, a request SPAM will be handled by a method do_SPAM(). If no such method exists the server sends an error response to the client. If it exists, it is called with no arguments:
do_SPAM()
Note that the request name is case sensitive (i.e. SPAM and spam are different requests).
The various request details are stored in instance variables:
client_address is the client IP address in the form (host,
port);
command, path and version are the broken-down request line;
headers is an instance of email.message.Message (or a derived
class) containing the header information;
rfile is a file object open for reading positioned at the
start of the optional input data part;
wfile is a file object open for writing.
IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
The first thing to be written must be the response line. Then follow 0 or more header lines, then a blank line, and then the actual data (if any). The meaning of the header lines depends on the command executed by the server; in most cases, when data is returned, there should be at least one header line of the form
Content-type: <type>/<subtype>
where <type> and <subtype> should be registered MIME types, e.g. "text/html" or "text/plain".
- MessageClass¶
HTTPMessage
的别名
- address_string()¶
Return the client address.
- date_time_string(timestamp=None)¶
Return the current date and time formatted for a message header.
- default_request_version = 'HTTP/0.9'¶
- end_headers()¶
Send the blank line ending the MIME headers.
- error_content_type = 'text/html;charset=utf-8'¶
- error_message_format = '<!DOCTYPE HTML>\n<html lang="en">\n <head>\n <meta charset="utf-8">\n <title>Error response</title>\n </head>\n <body>\n <h1>Error response</h1>\n <p>Error code: %(code)d</p>\n <p>Message: %(message)s.</p>\n <p>Error code explanation: %(code)s - %(explain)s.</p>\n </body>\n</html>\n'¶
- flush_headers()¶
- handle()¶
Handle multiple requests if necessary.
- handle_expect_100()¶
Decide what to do with an "Expect: 100-continue" header.
If the client is expecting a 100 Continue response, we must respond with either a 100 Continue or a final response before waiting for the request body. The default is to always respond with a 100 Continue. You can behave differently (for example, reject unauthorized requests) by overriding this method.
This method should either return True (possibly after sending a 100 Continue response) or send an error response and return False.
- handle_one_request()¶
Handle a single HTTP request.
You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST.
- log_date_time_string()¶
Return the current time formatted for logging.
- log_error(format, *args)¶
Log an error.
This is called when a request cannot be fulfilled. By default it passes the message on to log_message().
Arguments are the same as for log_message().
XXX This should go to the separate error log.
- log_message(format, *args)¶
Log an arbitrary message.
This is used by all other logging functions. Override it if you have specific logging wishes.
The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it's just like printf!).
The client ip and current date/time are prefixed to every message.
Unicode control characters are replaced with escaped hex before writing the output to stderr.
- log_request(code='-', size='-')¶
Log an accepted request.
This is called by send_response().
- monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']¶
- parse_request()¶
Parse a request (internal).
The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers.
Return True for success, False for failure; on failure, any relevant error response has already been sent back.
- protocol_version = 'HTTP/1.0'¶
- responses = {HTTPStatus.CONTINUE: ('Continue', 'Request received, please continue'), HTTPStatus.SWITCHING_PROTOCOLS: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), HTTPStatus.PROCESSING: ('Processing', ''), HTTPStatus.EARLY_HINTS: ('Early Hints', ''), HTTPStatus.OK: ('OK', 'Request fulfilled, document follows'), HTTPStatus.CREATED: ('Created', 'Document created, URL follows'), HTTPStatus.ACCEPTED: ('Accepted', 'Request accepted, processing continues off-line'), HTTPStatus.NON_AUTHORITATIVE_INFORMATION: ('Non-Authoritative Information', 'Request fulfilled from cache'), HTTPStatus.NO_CONTENT: ('No Content', 'Request fulfilled, nothing follows'), HTTPStatus.RESET_CONTENT: ('Reset Content', 'Clear input form for further input'), HTTPStatus.PARTIAL_CONTENT: ('Partial Content', 'Partial content follows'), HTTPStatus.MULTI_STATUS: ('Multi-Status', ''), HTTPStatus.ALREADY_REPORTED: ('Already Reported', ''), HTTPStatus.IM_USED: ('IM Used', ''), HTTPStatus.MULTIPLE_CHOICES: ('Multiple Choices', 'Object has several resources -- see URI list'), HTTPStatus.MOVED_PERMANENTLY: ('Moved Permanently', 'Object moved permanently -- see URI list'), HTTPStatus.FOUND: ('Found', 'Object moved temporarily -- see URI list'), HTTPStatus.SEE_OTHER: ('See Other', 'Object moved -- see Method and URL list'), HTTPStatus.NOT_MODIFIED: ('Not Modified', 'Document has not changed since given time'), HTTPStatus.USE_PROXY: ('Use Proxy', 'You must use proxy specified in Location to access this resource'), HTTPStatus.TEMPORARY_REDIRECT: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), HTTPStatus.PERMANENT_REDIRECT: ('Permanent Redirect', 'Object moved permanently -- see URI list'), HTTPStatus.BAD_REQUEST: ('Bad Request', 'Bad request syntax or unsupported method'), HTTPStatus.UNAUTHORIZED: ('Unauthorized', 'No permission -- see authorization schemes'), HTTPStatus.PAYMENT_REQUIRED: ('Payment Required', 'No payment -- see charging schemes'), HTTPStatus.FORBIDDEN: ('Forbidden', 'Request forbidden -- authorization will not help'), HTTPStatus.NOT_FOUND: ('Not Found', 'Nothing matches the given URI'), HTTPStatus.METHOD_NOT_ALLOWED: ('Method Not Allowed', 'Specified method is invalid for this resource'), HTTPStatus.NOT_ACCEPTABLE: ('Not Acceptable', 'URI not available in preferred format'), HTTPStatus.PROXY_AUTHENTICATION_REQUIRED: ('Proxy Authentication Required', 'You must authenticate with this proxy before proceeding'), HTTPStatus.REQUEST_TIMEOUT: ('Request Timeout', 'Request timed out; try again later'), HTTPStatus.CONFLICT: ('Conflict', 'Request conflict'), HTTPStatus.GONE: ('Gone', 'URI no longer exists and has been permanently removed'), HTTPStatus.LENGTH_REQUIRED: ('Length Required', 'Client must specify Content-Length'), HTTPStatus.PRECONDITION_FAILED: ('Precondition Failed', 'Precondition in headers is false'), HTTPStatus.REQUEST_ENTITY_TOO_LARGE: ('Request Entity Too Large', 'Entity is too large'), HTTPStatus.REQUEST_URI_TOO_LONG: ('Request-URI Too Long', 'URI is too long'), HTTPStatus.UNSUPPORTED_MEDIA_TYPE: ('Unsupported Media Type', 'Entity body in unsupported format'), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE: ('Requested Range Not Satisfiable', 'Cannot satisfy request range'), HTTPStatus.EXPECTATION_FAILED: ('Expectation Failed', 'Expect condition could not be satisfied'), HTTPStatus.IM_A_TEAPOT: ("I'm a Teapot", 'Server refuses to brew coffee because it is a teapot.'), HTTPStatus.MISDIRECTED_REQUEST: ('Misdirected Request', 'Server is not able to produce a response'), HTTPStatus.UNPROCESSABLE_ENTITY: ('Unprocessable Entity', ''), HTTPStatus.LOCKED: ('Locked', ''), HTTPStatus.FAILED_DEPENDENCY: ('Failed Dependency', ''), HTTPStatus.TOO_EARLY: ('Too Early', ''), HTTPStatus.UPGRADE_REQUIRED: ('Upgrade Required', ''), HTTPStatus.PRECONDITION_REQUIRED: ('Precondition Required', 'The origin server requires the request to be conditional'), HTTPStatus.TOO_MANY_REQUESTS: ('Too Many Requests', 'The user has sent too many requests in a given amount of time ("rate limiting")'), HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE: ('Request Header Fields Too Large', 'The server is unwilling to process the request because its header fields are too large'), HTTPStatus.UNAVAILABLE_FOR_LEGAL_REASONS: ('Unavailable For Legal Reasons', 'The server is denying access to the resource as a consequence of a legal demand'), HTTPStatus.INTERNAL_SERVER_ERROR: ('Internal Server Error', 'Server got itself in trouble'), HTTPStatus.NOT_IMPLEMENTED: ('Not Implemented', 'Server does not support this operation'), HTTPStatus.BAD_GATEWAY: ('Bad Gateway', 'Invalid responses from another server/proxy'), HTTPStatus.SERVICE_UNAVAILABLE: ('Service Unavailable', 'The server cannot process the request due to a high load'), HTTPStatus.GATEWAY_TIMEOUT: ('Gateway Timeout', 'The gateway server did not receive a timely response'), HTTPStatus.HTTP_VERSION_NOT_SUPPORTED: ('HTTP Version Not Supported', 'Cannot fulfill request'), HTTPStatus.VARIANT_ALSO_NEGOTIATES: ('Variant Also Negotiates', ''), HTTPStatus.INSUFFICIENT_STORAGE: ('Insufficient Storage', ''), HTTPStatus.LOOP_DETECTED: ('Loop Detected', ''), HTTPStatus.NOT_EXTENDED: ('Not Extended', ''), HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED: ('Network Authentication Required', 'The client needs to authenticate to gain network access')}¶
- send_error(code, message=None, explain=None)¶
Send and log an error reply.
Arguments are * code: an HTTP error code
3 digits
- message: a simple optional 1 line reason phrase.
*( HTAB / SP / VCHAR / %x80-FF ) defaults to short entry matching the response code
- explain: a detailed message defaults to the long entry
matching the response code.
This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user.
- send_header(keyword, value)¶
Send a MIME header to the headers buffer.
- send_response(code, message=None)¶
Add the response header to the headers buffer and log the response code.
Also send two standard headers with the server software version and the current date.
- send_response_only(code, message=None)¶
Send the response header only.
- server_version = 'BaseHTTP/0.6'¶
- sys_version = 'Python/3.12.7'¶
- version_string()¶
Return the server software version string.
- weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']¶
- class eventlet.green.BaseHTTPServer.CGIHTTPRequestHandler(*args, directory=None, **kwargs)¶
-
Complete HTTP server with GET, HEAD and POST commands.
GET and HEAD also support running CGI scripts.
The POST command is only implemented for CGI scripts.
- cgi_directories = ['/cgi-bin', '/htbin']¶
- do_POST()¶
Serve a POST request.
This is only implemented for CGI scripts.
- have_fork = True¶
- is_cgi()¶
Test whether self.path corresponds to a CGI script.
Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise.
If any exception is raised, the caller should assume that self.path was rejected as invalid and act accordingly.
The default implementation tests whether the normalized url path begins with one of the strings in self.cgi_directories (and the next character is a '/' or the end of the string).
- is_executable(path)¶
Test whether argument path is an executable file.
- is_python(path)¶
Test whether argument path is a Python script.
- rbufsize = 0¶
- run_cgi()¶
Execute a CGI script.
- send_head()¶
Version of send_head that support CGI scripts
- class eventlet.green.BaseHTTPServer.HTTPServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
基类:
TCPServer
- allow_reuse_address = 1¶
- server_bind()¶
Override server_bind to store the server name.
- class eventlet.green.BaseHTTPServer.SimpleHTTPRequestHandler(*args, directory=None, **kwargs)¶
-
Simple HTTP request handler with GET and HEAD commands.
This serves files from the current directory and any of its subdirectories. The MIME type for files is determined by calling the .guess_type() method.
The GET and HEAD requests are identical except that the HEAD request omits the actual contents of the file.
- copyfile(source, outputfile)¶
Copy all data between two file objects.
The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method).
The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well.
- do_GET()¶
Serve a GET request.
- do_HEAD()¶
Serve a HEAD request.
- extensions_map = {'.Z': 'application/octet-stream', '.bz2': 'application/x-bzip2', '.gz': 'application/gzip', '.xz': 'application/x-xz'}¶
- guess_type(path)¶
Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype, usable for a MIME Content-type header.
The default implementation looks the file's extension up in the table self.extensions_map, using application/octet-stream as a default; however it would be permissible (if slow) to look inside the data to make a better guess.
- index_pages = ('index.html', 'index.htm')¶
- list_directory(path)¶
Helper to produce a directory listing (absent index.html).
Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head().
- send_head()¶
Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do.
- server_version = 'SimpleHTTP/0.6'¶
- translate_path(path)¶
Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)
eventlet.green.CGIHTTPServer module¶
eventlet.green.MySQLdb module¶
eventlet.green.Queue module¶
- exception eventlet.green.Queue.Empty¶
基类:
Exception
Exception raised by Queue.get(block=0)/get_nowait().
- exception eventlet.green.Queue.Full¶
基类:
Exception
Exception raised by Queue.put(block=0)/put_nowait().
- class eventlet.green.Queue.PriorityQueue(maxsize=0)¶
eventlet.green.SimpleHTTPServer module¶
eventlet.green.SocketServer module¶
Generic socket server classes.
This module tries to capture the various aspects of defining a server:
For socket-based servers:
- address family:
AF_INET{,6}: IP (Internet Protocol) sockets (default)
AF_UNIX: Unix domain sockets
others, e.g. AF_DECNET are conceivable (see <socket.h>
- socket type:
SOCK_STREAM (reliable stream, e.g. TCP)
SOCK_DGRAM (datagrams, e.g. UDP)
For request-based servers (including socket-based):
- client address verification before further looking at the request
- (This is actually a hook for any processing that needs to look
at the request before anything else, e.g. logging)
- how to handle multiple requests:
synchronous (one request is handled at a time)
forking (each request is handled by a new process)
threading (each request is handled by a new thread)
The classes in this module favor the server type that is simplest to write: a synchronous TCP/IP server. This is bad class design, but saves some typing. (There's also the issue that a deep class hierarchy slows down method lookups.)
There are five classes in an inheritance diagram, four of which represent synchronous servers of four types:
BaseServer
v
+-----------+ +------------------+ | TCPServer |------->| UnixStreamServer | +-----------+ +------------------+
v
+-----------+ +--------------------+ | UDPServer |------->| UnixDatagramServer | +-----------+ +--------------------+
Note that UnixDatagramServer derives from UDPServer, not from UnixStreamServer -- the only difference between an IP and a Unix stream server is the address family, which is simply repeated in both unix server classes.
Forking and threading versions of each type of server can be created using the ForkingMixIn and ThreadingMixIn mix-in classes. For instance, a threading UDP server class is created as follows:
class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
The Mix-in class must come first, since it overrides a method defined in UDPServer! Setting the various member variables also changes the behavior of the underlying server mechanism.
To implement a service, you must derive a class from BaseRequestHandler and redefine its handle() method. You can then run various versions of the service by combining one of the server classes with your request handler class.
The request handler class must be different for datagram or stream services. This can be hidden by using the request handler subclasses StreamRequestHandler or DatagramRequestHandler.
Of course, you still have to use your head!
For instance, it makes no sense to use a forking server if the service contains state in memory that can be modified by requests (since the modifications in the child process would never reach the initial state kept in the parent process and passed to each child). In this case, you can use a threading server, but you will probably have to use locks to avoid two requests that come in nearly simultaneous to apply conflicting changes to the server state.
On the other hand, if you are building e.g. an HTTP server, where all data is stored externally (e.g. in the file system), a synchronous class will essentially render the service "deaf" while one request is being handled -- which may be for a very long time if a client is slow to read all the data it has requested. Here a threading or forking server is appropriate.
In some cases, it may be appropriate to process part of a request synchronously, but to finish processing in a forked child depending on the request data. This can be implemented by using a synchronous server and doing an explicit fork in the request handler class handle() method.
Another approach to handling multiple simultaneous requests in an environment that supports neither threads nor fork (or where these are too expensive or inappropriate for the service) is to maintain an explicit table of partially finished requests and to use a selector to decide which request to work on next (or whether to handle a new incoming request). This is particularly important for stream services where each client can potentially be connected for a long time (if threads or subprocesses cannot be used).
Future work: - Standard classes for Sun RPC (which uses either UDP or TCP) - Standard mix-in classes to implement various authentication
and encryption schemes
XXX Open problems: - What to do with out-of-band data?
BaseServer: - split generic "request" functionality out into BaseServer class.
Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
example: read entries from a SQL database (requires overriding get_request() to return a table entry from the database). entry is processed by a RequestHandlerClass.
- class eventlet.green.SocketServer.BaseRequestHandler(request, client_address, server)¶
基类:
object
Base class for request handler classes.
This class is instantiated for each request to be handled. The constructor sets the instance variables request, client_address and server, and then calls the handle() method. To implement a specific service, all you need to do is to derive a class which defines a handle() method.
The handle() method can find the request as self.request, the client address as self.client_address, and the server (in case it needs access to per-server information) as self.server. Since a separate instance is created for each request, the handle() method can define other arbitrary instance variables.
- finish()¶
- handle()¶
- setup()¶
- class eventlet.green.SocketServer.BaseServer(server_address, RequestHandlerClass)¶
基类:
object
Base class for server classes.
Methods for the caller:
__init__(server_address, RequestHandlerClass)
serve_forever(poll_interval=0.5)
shutdown()
handle_request() # if you do not use serve_forever()
fileno() -> int # for selector
Methods that may be overridden:
server_bind()
server_activate()
get_request() -> request, client_address
handle_timeout()
verify_request(request, client_address)
server_close()
process_request(request, client_address)
shutdown_request(request)
close_request(request)
service_actions()
handle_error()
Methods for derived classes:
finish_request(request, client_address)
Class variables that may be overridden by derived classes or instances:
timeout
address_family
socket_type
allow_reuse_address
allow_reuse_port
Instance variables:
RequestHandlerClass
socket
- close_request(request)¶
Called to clean up an individual request.
- finish_request(request, client_address)¶
Finish one request by instantiating RequestHandlerClass.
- handle_error(request, client_address)¶
Handle an error gracefully. May be overridden.
The default is to print a traceback and continue.
- handle_request()¶
Handle one request, possibly blocking.
Respects self.timeout.
- handle_timeout()¶
Called if no new request arrives within self.timeout.
Overridden by ForkingMixIn.
- process_request(request, client_address)¶
Call finish_request.
Overridden by ForkingMixIn and ThreadingMixIn.
- serve_forever(poll_interval=0.5)¶
Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread.
- server_activate()¶
Called by constructor to activate the server.
May be overridden.
- server_close()¶
Called to clean-up the server.
May be overridden.
- service_actions()¶
Called by the serve_forever() loop.
May be overridden by a subclass / Mixin to implement any code that needs to be run during the loop.
- shutdown()¶
Stops the serve_forever loop.
Blocks until the loop has finished. This must be called while serve_forever() is running in another thread, or it will deadlock.
- shutdown_request(request)¶
Called to shutdown and close an individual request.
- timeout = None¶
- verify_request(request, client_address)¶
Verify the request. May be overridden.
Return True if we should proceed with this request.
- class eventlet.green.SocketServer.DatagramRequestHandler(request, client_address, server)¶
-
Define self.rfile and self.wfile for datagram sockets.
- finish()¶
- setup()¶
- class eventlet.green.SocketServer.ForkingMixIn¶
基类:
object
Mix-in class to handle each request in a new process.
- active_children = None¶
- block_on_close = True¶
- collect_children(*, blocking=False)¶
Internal routine to wait for children that have exited.
- handle_timeout()¶
Wait for zombies after self.timeout seconds of inactivity.
May be extended, do not override.
- max_children = 40¶
- process_request(request, client_address)¶
Fork a new subprocess to process the request.
- server_close()¶
- service_actions()¶
Collect the zombie child processes regularly in the ForkingMixIn.
service_actions is called in the BaseServer's serve_forever loop.
- timeout = 300¶
- class eventlet.green.SocketServer.ForkingTCPServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
- class eventlet.green.SocketServer.ForkingUDPServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
- class eventlet.green.SocketServer.ForkingUnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
- class eventlet.green.SocketServer.ForkingUnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
- class eventlet.green.SocketServer.StreamRequestHandler(request, client_address, server)¶
-
Define self.rfile and self.wfile for stream sockets.
- disable_nagle_algorithm = False¶
- finish()¶
- rbufsize = -1¶
- setup()¶
- timeout = None¶
- wbufsize = 0¶
- class eventlet.green.SocketServer.TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
基类:
BaseServer
Base class for various socket-based server classes.
Defaults to synchronous IP stream (i.e., TCP).
Methods for the caller:
__init__(server_address, RequestHandlerClass, bind_and_activate=True)
serve_forever(poll_interval=0.5)
shutdown()
handle_request() # if you don't use serve_forever()
fileno() -> int # for selector
Methods that may be overridden:
server_bind()
server_activate()
get_request() -> request, client_address
handle_timeout()
verify_request(request, client_address)
process_request(request, client_address)
shutdown_request(request)
close_request(request)
handle_error()
Methods for derived classes:
finish_request(request, client_address)
Class variables that may be overridden by derived classes or instances:
timeout
address_family
socket_type
request_queue_size (only for stream sockets)
allow_reuse_address
allow_reuse_port
Instance variables:
server_address
RequestHandlerClass
socket
- address_family = 2¶
- allow_reuse_address = False¶
- allow_reuse_port = False¶
- close_request(request)¶
Called to clean up an individual request.
- fileno()¶
Return socket file number.
Interface required by selector.
- get_request()¶
Get the request and client address from the socket.
May be overridden.
- request_queue_size = 5¶
- server_activate()¶
Called by constructor to activate the server.
May be overridden.
- server_bind()¶
Called by constructor to bind the socket.
May be overridden.
- server_close()¶
Called to clean-up the server.
May be overridden.
- shutdown_request(request)¶
Called to shutdown and close an individual request.
- socket_type = 1¶
- class eventlet.green.SocketServer.ThreadingMixIn¶
基类:
object
Mix-in class to handle each request in a new thread.
- block_on_close = True¶
- daemon_threads = False¶
- process_request(request, client_address)¶
Start a new thread to process the request.
- process_request_thread(request, client_address)¶
Same as in BaseServer but as a thread.
In addition, exception handling is done here.
- server_close()¶
- class eventlet.green.SocketServer.ThreadingTCPServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
- class eventlet.green.SocketServer.ThreadingUDPServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
- class eventlet.green.SocketServer.ThreadingUnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
- class eventlet.green.SocketServer.ThreadingUnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
- class eventlet.green.SocketServer.UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)¶
基类:
TCPServer
UDP server class.
- allow_reuse_address = False¶
- allow_reuse_port = False¶
- close_request(request)¶
Called to clean up an individual request.
- get_request()¶
Get the request and client address from the socket.
May be overridden.
- max_packet_size = 8192¶
- server_activate()¶
Called by constructor to activate the server.
May be overridden.
- shutdown_request(request)¶
Called to shutdown and close an individual request.
- socket_type = 2¶
eventlet.green.asynchat module¶
eventlet.green.asyncore module¶
eventlet.green.builtin module¶
In order to detect a filehandle that's been closed, our only clue may be the operating system returning the same filehandle in response to some other operation.
The builtins 'file' and 'open' are patched to collaborate with the notify_opened protocol.
- eventlet.green.builtin.clear() None. Remove all items from D. ¶
- eventlet.green.builtin.copy() a shallow copy of D ¶
- eventlet.green.builtin.fromkeys(iterable, value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
- eventlet.green.builtin.get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
- eventlet.green.builtin.items() a set-like object providing a view on D's items ¶
- eventlet.green.builtin.keys() a set-like object providing a view on D's keys ¶
- eventlet.green.builtin.pop(k[, d]) v, remove specified key and return the corresponding value. ¶
If the key is not found, return the default if given; otherwise, raise a KeyError.
- eventlet.green.builtin.popitem()¶
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- eventlet.green.builtin.setdefault(key, default=None, /)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- eventlet.green.builtin.update([E, ]**F) None. Update D from dict/iterable E and F. ¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- eventlet.green.builtin.values() an object providing a view on D's values ¶
eventlet.green.ftplib module¶
An FTP client class and some helper functions.
Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
Example:
>>> from ftplib import FTP
>>> ftp = FTP('ftp.python.org') # connect to host, default port
>>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
'230 Guest login ok, access restrictions apply.'
>>> ftp.retrlines('LIST') # list directory contents
total 9
drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
'226 Transfer complete.'
>>> ftp.quit()
'221 Goodbye.'
>>>
A nice test that reveals some of the network dialogue would be: python ftplib.py -d localhost -l -p -l
- class eventlet.green.ftplib.FTP(host='', user='', passwd='', acct='', timeout=<object object>, source_address=None, *, encoding='utf-8')¶
基类:
object
An FTP client class.
- To create a connection, call the class using these arguments:
host, user, passwd, acct, timeout, source_address, encoding
The first four arguments are all strings, and have default value ''. The parameter ´timeout´ must be numeric and defaults to None if not passed, meaning that no timeout will be set on any ftp socket(s). If a timeout is passed, then this is now the default timeout for all ftp socket operations for this instance. The last parameter is the encoding of filenames, which defaults to utf-8.
Then use self.connect() with optional host and port argument.
To download a file, use ftp.retrlines('RETR ' + filename), or ftp.retrbinary() with slightly different arguments. To upload a file, use ftp.storlines() or ftp.storbinary(), which have an open file as argument (see their definitions below for details). The download/upload functions first issue appropriate TYPE and PORT or PASV commands.
- abort()¶
Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.
- acct(password)¶
Send new account name.
- close()¶
Close the connection without assuming anything about it.
- connect(host='', port=0, timeout=-999, source_address=None)¶
Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) - timeout: the timeout to set against the ftp socket(s) - source_address: a 2-tuple (host, port) for the socket to bind
to as its source address before connecting.
- cwd(dirname)¶
Change to a directory.
- debug(level)¶
Set the debugging level. The required argument level means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF
- debugging = 0¶
- delete(filename)¶
Delete a file.
- dir(*args)¶
List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This should only be used for a pathname.)
- file = None¶
- getline()¶
- getmultiline()¶
- getresp()¶
- getwelcome()¶
Get the welcome message from the server. (this is read and squirreled away by connect())
- host = ''¶
- login(user='', passwd='', acct='')¶
Login, default anonymous.
- makepasv()¶
Internal: Does the PASV or EPSV handshake -> (address, port)
- makeport()¶
Create a new socket and send a PORT command for it.
- maxline = 8192¶
- mkd(dirname)¶
Make a directory, return its full pathname.
- mlsd(path='', facts=[])¶
List a directory in a standardized format by using MLSD command (RFC-3659). If path is omitted the current directory is assumed. "facts" is a list of strings representing the type of information desired (e.g. ["type", "size", "perm"]).
Return a generator object yielding a tuple of two elements for every file found in path. First element is the file name, the second one is a dictionary including a variable number of "facts" depending on the server and whether "facts" argument has been provided.
- nlst(*args)¶
Return a list of files in a given directory (default the current).
- ntransfercmd(cmd, rest=None)¶
Initiate a transfer over the data connection.
If the transfer is active, send a port command and the transfer command, and accept the connection. If the server is passive, send a pasv command, connect to it, and start the transfer command. Either way, return the socket for the connection and the expected size of the transfer. The expected size may be None if it could not be determined.
Optional `rest' argument can be a string that is sent as the argument to a REST command. This is essentially a server marker used to tell the server to skip over any data up to the given marker.
- passiveserver = True¶
- port = 21¶
- putcmd(line)¶
- putline(line)¶
- pwd()¶
Return current working directory.
- quit()¶
Quit, and close the connection.
- rename(fromname, toname)¶
Rename a file.
- retrbinary(cmd, callback, blocksize=8192, rest=None)¶
Retrieve data in binary mode. A new port is created for you.
- Args:
cmd: A RETR command. callback: A single parameter callable to be called on each
block of data read.
- blocksize: The maximum number of bytes to read from the
socket at one time. [default: 8192]
rest: Passed to transfercmd(). [default: None]
- Returns:
The response code.
- retrlines(cmd, callback=None)¶
Retrieve data in line mode. A new port is created for you.
- Args:
cmd: A RETR, LIST, or NLST command. callback: An optional single parameter callable that is called
for each line with the trailing CRLF stripped. [default: print_line()]
- Returns:
The response code.
- rmd(dirname)¶
Remove a directory.
- sanitize(s)¶
- sendcmd(cmd)¶
Send a command and return the response.
- sendeprt(host, port)¶
Send an EPRT command with the current host and the given port number.
- sendport(host, port)¶
Send a PORT command with the current host and the given port number.
- set_debuglevel(level)¶
Set the debugging level. The required argument level means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF
- set_pasv(val)¶
Use passive or active mode for data transfers. With a false argument, use the normal PORT mode, With a true argument, use the PASV command.
- size(filename)¶
Retrieve the size of a file.
- sock = None¶
- storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)¶
Store a file in binary mode. A new port is created for you.
- Args:
cmd: A STOR command. fp: A file-like object with a read(num_bytes) method. blocksize: The maximum data size to read from fp and send over
the connection at once. [default: 8192]
- callback: An optional single parameter callable that is called on
each block of data after it is sent. [default: None]
rest: Passed to transfercmd(). [default: None]
- Returns:
The response code.
- storlines(cmd, fp, callback=None)¶
Store a file in line mode. A new port is created for you.
- Args:
cmd: A STOR command. fp: A file-like object with a readline() method. callback: An optional single parameter callable that is called on
each line after it is sent. [default: None]
- Returns:
The response code.
- transfercmd(cmd, rest=None)¶
Like ntransfercmd() but returns only the socket.
- trust_server_pasv_ipv4_address = False¶
- voidcmd(cmd)¶
Send a command and expect a response beginning with '2'.
- voidresp()¶
Expect a response beginning with '2'.
- welcome = None¶
- class eventlet.green.ftplib.FTP_TLS(host='', user='', passwd='', acct='', *, context=None, timeout=<object object>, source_address=None, encoding='utf-8')¶
基类:
FTP
A FTP subclass which adds TLS support to FTP as described in RFC-4217.
Connect as usual to port 21 implicitly securing the FTP control connection before authenticating.
Securing the data connection requires user to explicitly ask for it by calling prot_p() method.
Usage example: >>> from ftplib import FTP_TLS >>> ftps = FTP_TLS('ftp.python.org') >>> ftps.login() # login anonymously previously securing control channel '230 Guest login ok, access restrictions apply.' >>> ftps.prot_p() # switch to secure data connection '200 Protection level set to P' >>> ftps.retrlines('LIST') # list directory content securely total 9 drwxr-xr-x 8 root wheel 1024 Jan 3 1994 . drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .. drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg '226 Transfer complete.' >>> ftps.quit() '221 Goodbye.' >>>
- abort()¶
Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.
- auth()¶
Set up secure control connection by using TLS/SSL.
- ccc()¶
Switch back to a clear-text control connection.
- login(user='', passwd='', acct='', secure=True)¶
Login, default anonymous.
- ntransfercmd(cmd, rest=None)¶
Initiate a transfer over the data connection.
If the transfer is active, send a port command and the transfer command, and accept the connection. If the server is passive, send a pasv command, connect to it, and start the transfer command. Either way, return the socket for the connection and the expected size of the transfer. The expected size may be None if it could not be determined.
Optional `rest' argument can be a string that is sent as the argument to a REST command. This is essentially a server marker used to tell the server to skip over any data up to the given marker.
- prot_c()¶
Set up clear text data connection.
- prot_p()¶
Set up secure data connection.
- exception eventlet.green.ftplib.error_perm¶
基类:
Error
- exception eventlet.green.ftplib.error_proto¶
基类:
Error
- exception eventlet.green.ftplib.error_reply¶
基类:
Error
- exception eventlet.green.ftplib.error_temp¶
基类:
Error
eventlet.green.httplib module¶
HTTP/1.1 client library
<intro stuff goes here> <other stuff, too>
HTTPConnection goes through a number of "states", which define when a client may legally make another request or fetch the response for a particular request. This diagram details these state transitions:
- (null)
HTTPConnection()v
- Idle
putrequest()v
- Request-started
( putheader() )* endheaders()v
- Request-sent
|_____________________________ | | getresponse() raises | response = getresponse() | ConnectionError v v
Unread-response Idle [Response-headers-read]
|____________________ | | | response.read() | putrequest() v v
- Idle Req-started-unread-response
______/|
/ |
- response.read() | | ( putheader() )* endheaders()
v v
- Request-started Req-sent-unread-response
response.read()v
Request-sent
- This diagram presents the following rules:
-- a second request may not be started until {response-headers-read} -- a response [object] cannot be retrieved until {request-sent} -- there is no differentiation between an unread response body and a
partially read response body
- Note: this enforcement is applied by the HTTPConnection class. The
HTTPResponse class does not enforce this state machine, which implies sophisticated clients may accelerate the request/response pipeline. Caution should be taken, though: accelerating the states beyond the above pattern may imply knowledge of the server's connection-close behavior for certain requests. For example, it is impossible to tell whether the server will close the connection UNTIL the response headers have been read; this means that further requests cannot be placed into the pipeline until it is known that the server will NOT be closing the connection.
Logical State __state __response ------------- ------- ---------- Idle _CS_IDLE None Request-started _CS_REQ_STARTED None Request-sent _CS_REQ_SENT None Unread-response _CS_IDLE <response_class> Req-started-unread-response _CS_REQ_STARTED <response_class> Req-sent-unread-response _CS_REQ_SENT <response_class>
- exception eventlet.green.httplib.BadStatusLine(line)¶
- exception eventlet.green.httplib.CannotSendHeader¶
- exception eventlet.green.httplib.CannotSendRequest¶
- class eventlet.green.httplib.HTTPConnection(host, port=None, timeout=<object object>, source_address=None)¶
基类:
object
- auto_open = 1¶
- close()¶
Close the connection to the HTTP server.
- connect()¶
Connect to the host and port specified in __init__.
- debuglevel = 0¶
- default_port = 80¶
- endheaders(message_body=None, **kwds)¶
Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional message_body argument can be used to pass a message body associated with the request.
- getresponse()¶
Get the response from the server.
If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable.
If a request has not been sent or if a previous response has not be handled, ResponseNotReady is raised. If the HTTP response indicates that the connection should be closed, then it will be closed before the response is returned. When the connection is closed, the underlying socket is closed.
- putheader(header, *values)¶
Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
- putrequest(method, url, skip_host=0, skip_accept_encoding=0)¶
Send a request to the server.
`method' specifies an HTTP request method, e.g. 'GET'. `url' specifies the object being requested, e.g. '/index.html'. `skip_host' if True does not add automatically a 'Host:' header `skip_accept_encoding' if True does not add automatically an
'Accept-Encoding:' header
- request(method, url, body=None, headers={}, **kwds)¶
Send a complete request to the server.
- response_class¶
HTTPResponse
的别名
- send(data)¶
Send data' to the server. ``data` can be a string object, a bytes object, an array object, a file-like object that supports a .read() method, or an iterable object.
- set_debuglevel(level)¶
- set_tunnel(host, port=None, headers=None)¶
Set up host and port for HTTP CONNECT tunnelling.
In a connection that uses HTTP CONNECT tunneling, the host passed to the constructor is used as a proxy server that relays all communication to the endpoint passed to set_tunnel. This done by sending an HTTP CONNECT request to the proxy server when the connection is established.
This method must be called before the HTML connection has been established.
The headers argument should be a mapping of extra HTTP headers to send with the CONNECT request.
- class eventlet.green.httplib.HTTPResponse(sock, debuglevel=0, method=None, url=None)¶
-
- begin()¶
- close()¶
Flush and close the IO object.
This method has no effect if the file is already closed.
- fileno()¶
Return underlying file descriptor if one exists.
Raise OSError if the IO object does not use a file descriptor.
- flush()¶
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- getcode()¶
Return the HTTP status code that was sent with the response, or None if the URL is not an HTTP URL.
- getheader(name, default=None)¶
Returns the value of the header matching name.
If there are multiple matching headers, the values are combined into a single string separated by commas and spaces.
If no matching header is found, returns default or None if the default is not specified.
If the headers are unknown, raises http.client.ResponseNotReady.
- getheaders()¶
Return list of (header, value) tuples.
- geturl()¶
Return the real URL of the page.
In some cases, the HTTP server redirects a client to another URL. The urlopen() function handles this transparently, but in some cases the caller needs to know which URL the client was redirected to. The geturl() method can be used to get at this redirected URL.
- info()¶
Returns an instance of the class mimetools.Message containing meta-information associated with the URL.
When the method is HTTP, these headers are those returned by the server at the head of the retrieved HTML page (including Content-Length and Content-Type).
When the method is FTP, a Content-Length header will be present if (as is now usual) the server passed back a file length in response to the FTP retrieval request. A Content-Type header will be present if the MIME type can be guessed.
When the method is local-file, returned headers will include a Date representing the file's last-modified time, a Content-Length giving file size, and a Content-Type containing a guess at the file's type. See also the description of the mimetools module.
- isclosed()¶
True if the connection is closed.
- peek(n=-1)¶
- read(amt=None)¶
Read and return up to n bytes.
If the size argument is omitted, None, or negative, read and return all data until EOF.
If the size argument is positive, and the underlying raw stream is not 'interactive', multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). However, for interactive raw streams (as well as sockets and pipes), at most one raw read will be issued, and a short result does not imply that EOF is imminent.
Return an empty bytes object on EOF.
Return None if the underlying raw stream was open in non-blocking mode and no data is available at the moment.
- read1(n=-1)¶
Read with at most one underlying system call. If at least one byte is buffered, return that instead.
- readable()¶
Always returns True
- readinto(b)¶
Read up to len(b) bytes into bytearray b and return the number of bytes read.
- readline(limit=-1)¶
Read and return a line from the stream.
If size is specified, at most size bytes will be read.
The line terminator is always b'n' for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized.
- class eventlet.green.httplib.HTTPSConnection(host, port=None, key_file=None, cert_file=None, timeout=<object object>, source_address=None, *, context=None, check_hostname=None)¶
-
This class allows communication via SSL.
- connect()¶
Connect to a host on a given (SSL) port.
- default_port = 443¶
- exception eventlet.green.httplib.ImproperConnectionState¶
- exception eventlet.green.httplib.IncompleteRead(partial, expected=None)¶
- exception eventlet.green.httplib.InvalidURL¶
- exception eventlet.green.httplib.LineTooLong(line_type)¶
- exception eventlet.green.httplib.NotConnected¶
- exception eventlet.green.httplib.RemoteDisconnected(*pos, **kw)¶
- exception eventlet.green.httplib.ResponseNotReady¶
- exception eventlet.green.httplib.UnimplementedFileMode¶
- exception eventlet.green.httplib.UnknownProtocol(version)¶
- exception eventlet.green.httplib.UnknownTransferEncoding¶
- eventlet.green.httplib.error¶
HTTPException
的别名
eventlet.green.os module¶
- class eventlet.green.os.DirEntry¶
基类:
object
- inode()¶
Return inode of the entry; cached per entry.
- is_dir(*, follow_symlinks=True)¶
Return True if the entry is a directory; cached per entry.
- is_file(*, follow_symlinks=True)¶
Return True if the entry is a file; cached per entry.
- is_junction()¶
Return True if the entry is a junction; cached per entry.
- is_symlink()¶
Return True if the entry is a symbolic link; cached per entry.
- name¶
the entry's base filename, relative to scandir() "path" argument
- path¶
the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)
- stat(*, follow_symlinks=True)¶
Return stat_result object for the entry; cached per entry.
- eventlet.green.os.WCOREDUMP(status, /)¶
Return True if the process returning status was dumped to a core file.
- eventlet.green.os.WEXITSTATUS(status)¶
Return the process return code from status.
- eventlet.green.os.WIFCONTINUED(status)¶
Return True if a particular process was continued from a job control stop.
Return True if the process returning status was continued from a job control stop.
- eventlet.green.os.WIFEXITED(status)¶
Return True if the process returning status exited via the exit() system call.
- eventlet.green.os.WIFSIGNALED(status)¶
Return True if the process returning status was terminated by a signal.
- eventlet.green.os.WIFSTOPPED(status)¶
Return True if the process returning status was stopped.
- eventlet.green.os.WSTOPSIG(status)¶
Return the signal that stopped the process that provided the status value.
- eventlet.green.os.WTERMSIG(status)¶
Return the signal that terminated the process that provided the status value.
- eventlet.green.os.abort()¶
Abort the interpreter immediately.
This function 'dumps core' or otherwise fails in the hardest way possible on the hosting operating system. This function never returns.
- eventlet.green.os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)¶
Use the real uid/gid to test for access to a path.
- path
Path to be tested; can be string, bytes, or a path-like object.
- mode
Operating-system mode bitfield. Can be F_OK to test existence, or the inclusive-OR of R_OK, W_OK, and X_OK.
- dir_fd
If not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory.
- effective_ids
If True, access will use the effective uid/gid instead of the real uid/gid.
- follow_symlinks
If False, and the last element of the path is a symbolic link, access will examine the symbolic link itself instead of the file the link points to.
- dir_fd, effective_ids, and follow_symlinks may not be implemented
on your platform. If they are unavailable, using them will raise a NotImplementedError.
- Note that most operations will use the effective uid/gid, therefore this
routine can be used in a suid/sgid environment to test if the invoking user has the specified access to the path.
- eventlet.green.os.chdir(path)¶
Change the current working directory to the specified path.
path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
- eventlet.green.os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)¶
Change the access permissions of a file.
- path
Path to be modified. May always be specified as a str, bytes, or a path-like object. On some platforms, path may also be specified as an open file descriptor. If this functionality is unavailable, using it raises an exception.
- mode
Operating-system mode bitfield. Be careful when using number literals for mode. The conventional UNIX notation for numeric modes uses an octal base, which needs to be indicated with a
0o
prefix in Python.- dir_fd
If not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory.
- follow_symlinks
If False, and the last element of the path is a symbolic link, chmod will modify the symbolic link itself instead of the file the link points to.
- It is an error to use dir_fd or follow_symlinks when specifying path as
an open file descriptor.
- dir_fd and follow_symlinks may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
- eventlet.green.os.chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)¶
Change the owner and group id of path to the numeric uid and gid.
- path
Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
- dir_fd
If not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory.
- follow_symlinks
If False, and the last element of the path is a symbolic link, stat will examine the symbolic link itself instead of the file the link points to.
path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
- If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
- If follow_symlinks is False, and the last element of the path is a symbolic
link, chown will modify the symbolic link itself instead of the file the link points to.
- It is an error to use dir_fd or follow_symlinks when specifying path as
an open file descriptor.
- dir_fd and follow_symlinks may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
- eventlet.green.os.chroot(path)¶
Change root directory to path.
- eventlet.green.os.close(fd)¶
Close a file descriptor.
- eventlet.green.os.closerange(fd_low, fd_high, /)¶
Closes all file descriptors in [fd_low, fd_high), ignoring errors.
- eventlet.green.os.confstr(name, /)¶
Return a string-valued system configuration variable.
- eventlet.green.os.copy_file_range(src, dst, count, offset_src=None, offset_dst=None)¶
Copy count bytes from one file descriptor to another.
- src
Source file descriptor.
- dst
Destination file descriptor.
- count
Number of bytes to copy.
- offset_src
Starting offset in src.
- offset_dst
Starting offset in dst.
If offset_src is None, then src is read from the current position; respectively for offset_dst.
- eventlet.green.os.cpu_count()¶
Return the number of CPUs in the system; return None if indeterminable.
This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with
len(os.sched_getaffinity(0))
- eventlet.green.os.ctermid()¶
Return the name of the controlling terminal for this process.
- eventlet.green.os.device_encoding(fd)¶
Return a string describing the encoding of a terminal's file descriptor.
The file descriptor must be attached to a terminal. If the device is not a terminal, return None.
- eventlet.green.os.dup(fd, /)¶
Return a duplicate of a file descriptor.
- eventlet.green.os.dup2(fd, fd2, inheritable=True)¶
Duplicate file descriptor.
- eventlet.green.os.eventfd(initval, flags=524288)¶
Creates and returns an event notification file descriptor.
- eventlet.green.os.eventfd_read(fd)¶
Read eventfd value
- eventlet.green.os.eventfd_write(fd, value)¶
Write eventfd value.
- eventlet.green.os.execl(file, *args)¶
Execute the executable file with argument list args, replacing the current process.
- eventlet.green.os.execle(file, *args, env)¶
Execute the executable file with argument list args and environment env, replacing the current process.
- eventlet.green.os.execlp(file, *args)¶
Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process.
- eventlet.green.os.execlpe(file, *args, env)¶
Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process.
- eventlet.green.os.execv(path, argv, /)¶
Execute an executable path with arguments, replacing current process.
- path
Path of executable file.
- argv
Tuple or list of strings.
- eventlet.green.os.execve(path, argv, env)¶
Execute an executable path with arguments, replacing current process.
- path
Path of executable file.
- argv
Tuple or list of strings.
- env
Dictionary of strings mapping to strings.
- eventlet.green.os.execvp(file, args)¶
Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. args may be a list or tuple of strings.
- eventlet.green.os.execvpe(file, args, env)¶
Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process. args may be a list or tuple of strings.
- eventlet.green.os.fchdir(fd)¶
Change to the directory of the given file descriptor.
fd must be opened on a directory, not a file. Equivalent to os.chdir(fd).
- eventlet.green.os.fchmod(fd, mode)¶
Change the access permissions of the file given by file descriptor fd.
- fd
The file descriptor of the file to be modified.
- mode
Operating-system mode bitfield. Be careful when using number literals for mode. The conventional UNIX notation for numeric modes uses an octal base, which needs to be indicated with a
0o
prefix in Python.
Equivalent to os.chmod(fd, mode).
- eventlet.green.os.fchown(fd, uid, gid)¶
Change the owner and group id of the file specified by file descriptor.
Equivalent to os.chown(fd, uid, gid).
- eventlet.green.os.fdatasync(fd)¶
Force write of fd to disk without forcing update of metadata.
- eventlet.green.os.fdopen(fd[, mode='r'[, bufsize]]) file_object ¶
Return an open file object connected to a file descriptor.
- eventlet.green.os.fork()¶
Fork a child process.
Return 0 to child process and PID of child to parent process.
- eventlet.green.os.forkpty()¶
Fork a new process with a new pseudo-terminal as controlling tty.
Returns a tuple of (pid, master_fd). Like fork(), return pid of 0 to the child process, and pid of child to the parent process. To both, return fd of newly opened pseudo-terminal.
- eventlet.green.os.fpathconf(fd, name, /)¶
Return the configuration limit name for the file descriptor fd.
If there is no limit, return -1.
- eventlet.green.os.fsdecode(filename)¶
Decode filename (an os.PathLike, bytes, or str) from the filesystem encoding with 'surrogateescape' error handler, return str unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding).
- eventlet.green.os.fsencode(filename)¶
Encode filename (an os.PathLike, bytes, or str) to the filesystem encoding with 'surrogateescape' error handler, return bytes unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding).
- eventlet.green.os.fspath(path)¶
Return the file system path representation of the object.
If the object is str or bytes, then allow it to pass through as-is. If the object defines __fspath__(), then return the result of that method. All other types raise a TypeError.
- eventlet.green.os.fstat(fd)¶
Perform a stat system call on the given file descriptor.
Like stat(), but for an open file descriptor. Equivalent to os.stat(fd).
- eventlet.green.os.fstatvfs(fd, /)¶
Perform an fstatvfs system call on the given fd.
Equivalent to statvfs(fd).
- eventlet.green.os.fsync(fd)¶
Force write of fd to disk.
- eventlet.green.os.ftruncate(fd, length, /)¶
Truncate a file, specified by file descriptor, to a specific length.
- eventlet.green.os.fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)¶
Directory tree generator.
This behaves exactly like walk(), except that it yields a 4-tuple
dirpath, dirnames, filenames, dirfd
dirpath, dirnames and filenames are identical to walk() output, and dirfd is a file descriptor referring to the directory dirpath.
The advantage of fwalk() over walk() is that it's safe against symlink races (when follow_symlinks is False).
- If dir_fd is not None, it should be a file descriptor open to a directory,
and top should be relative; top will then be relative to that directory. (dir_fd is always supported for fwalk.)
Caution: Since fwalk() yields file descriptors, those are only valid until the next iteration step, so you should dup() them if you want to keep them for a longer period.
Example:
import os for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
print(root, "consumes", end="") print(sum(os.stat(name, dir_fd=rootfd).st_size for name in files),
end="")
print("bytes in", len(files), "non-directory files") if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
- eventlet.green.os.get_blocking(fd, /)¶
Get the blocking mode of the file descriptor.
Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
- eventlet.green.os.get_exec_path(env=None)¶
Returns the sequence of directories that will be searched for the named executable (similar to a shell) when launching a process.
env must be an environment variable dict or None. If env is None, os.environ will be used.
- eventlet.green.os.get_inheritable(fd, /)¶
Get the close-on-exe flag of the specified file descriptor.
- eventlet.green.os.get_terminal_size()¶
Return the size of the terminal window as (columns, lines).
The optional argument fd (default standard output) specifies which file descriptor should be queried.
If the file descriptor is not connected to a terminal, an OSError is thrown.
This function will only be defined if an implementation is available for this system.
shutil.get_terminal_size is the high-level function which should normally be used, os.get_terminal_size is the low-level implementation.
- eventlet.green.os.getcwd()¶
Return a unicode string representing the current working directory.
- eventlet.green.os.getcwdb()¶
Return a bytes string representing the current working directory.
- eventlet.green.os.getegid()¶
Return the current process's effective group id.
- eventlet.green.os.getenv(key, default=None)¶
Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are str.
- eventlet.green.os.getenvb(key, default=None)¶
Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are bytes.
- eventlet.green.os.geteuid()¶
Return the current process's effective user id.
- eventlet.green.os.getgid()¶
Return the current process's group id.
- eventlet.green.os.getgrouplist(user, group, /)¶
Returns a list of groups to which a user belongs.
- user
username to lookup
- group
base group id of the user
- eventlet.green.os.getgroups()¶
Return list of supplemental group IDs for the process.
- eventlet.green.os.getloadavg()¶
Return average recent system load information.
Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes as a tuple of three floats. Raises OSError if the load average was unobtainable.
- eventlet.green.os.getlogin()¶
Return the actual login name.
- eventlet.green.os.getpgid(pid)¶
Call the system call getpgid(), and return the result.
- eventlet.green.os.getpgrp()¶
Return the current process group id.
- eventlet.green.os.getpid()¶
Return the current process id.
- eventlet.green.os.getppid()¶
Return the parent's process id.
If the parent process has already exited, Windows machines will still return its id; others systems will return the id of the 'init' process (1).
- eventlet.green.os.getpriority(which, who)¶
Return program scheduling priority.
- eventlet.green.os.getrandom(size, flags=0)¶
Obtain a series of random bytes.
- eventlet.green.os.getresgid()¶
Return a tuple of the current process's real, effective, and saved group ids.
- eventlet.green.os.getresuid()¶
Return a tuple of the current process's real, effective, and saved user ids.
- eventlet.green.os.getsid(pid, /)¶
Call the system call getsid(pid) and return the result.
- eventlet.green.os.getuid()¶
Return the current process's user id.
- eventlet.green.os.getxattr(path, attribute, *, follow_symlinks=True)¶
Return the value of extended attribute attribute on path.
path may be either a string, a path-like object, or an open file descriptor. If follow_symlinks is False, and the last element of the path is a symbolic
link, getxattr will examine the symbolic link itself instead of the file the link points to.
- eventlet.green.os.initgroups(username, gid, /)¶
Initialize the group access list.
Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified group id.
- eventlet.green.os.isatty(fd, /)¶
Return True if the fd is connected to a terminal.
Return True if the file descriptor is an open file descriptor connected to the slave end of a terminal.
- eventlet.green.os.kill(pid, signal, /)¶
Kill a process with a signal.
- eventlet.green.os.killpg(pgid, signal, /)¶
Kill a process group with a signal.
- eventlet.green.os.lchown(path, uid, gid)¶
Change the owner and group id of path to the numeric uid and gid.
This function will not follow symbolic links. Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
- eventlet.green.os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)¶
Create a hard link to a file.
- If either src_dir_fd or dst_dir_fd is not None, it should be a file
descriptor open to a directory, and the respective path string (src or dst) should be relative; the path will then be relative to that directory.
- If follow_symlinks is False, and the last element of src is a symbolic
link, link will create a link to the symbolic link itself instead of the file the link points to.
- src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
platform. If they are unavailable, using them will raise a NotImplementedError.
- eventlet.green.os.listdir(path=None)¶
Return a list containing the names of the files in the directory.
- path can be specified as either str, bytes, or a path-like object. If path is bytes,
the filenames returned will also be bytes; in all other circumstances the filenames returned will be str.
If path is None, uses the path='.'. On some platforms, path may also be specified as an open file descriptor;
the file descriptor must refer to a directory. If this functionality is unavailable, using it raises NotImplementedError.
The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
- eventlet.green.os.listxattr(path=None, *, follow_symlinks=True)¶
Return a list of extended attributes on path.
path may be either None, a string, a path-like object, or an open file descriptor. if path is None, listxattr will examine the current directory. If follow_symlinks is False, and the last element of the path is a symbolic
link, listxattr will examine the symbolic link itself instead of the file the link points to.
- eventlet.green.os.lockf(fd, command, length, /)¶
Apply, test or remove a POSIX lock on an open file descriptor.
- fd
An open file descriptor.
- command
One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
- length
The number of bytes to lock, starting at the current position.
- eventlet.green.os.login_tty(fd, /)¶
Prepare the tty of which fd is a file descriptor for a new login session.
Make the calling process a session leader; make the tty the controlling tty, the stdin, the stdout, and the stderr of the calling process; close fd.
- eventlet.green.os.lseek(fd, position, whence, /)¶
Set the position of a file descriptor. Return the new position.
- fd
An open file descriptor, as returned by os.open().
- position
Position, interpreted relative to 'whence'.
- whence
The relative position to seek from. Valid values are: - SEEK_SET: seek from the start of the file. - SEEK_CUR: seek from the current file position. - SEEK_END: seek from the end of the file.
The return value is the number of bytes relative to the beginning of the file.
- eventlet.green.os.lstat(path, *, dir_fd=None)¶
Perform a stat system call on the given path, without following symbolic links.
Like stat(), but do not follow symbolic links. Equivalent to stat(path, follow_symlinks=False).
- eventlet.green.os.major(device, /)¶
Extracts a device major number from a raw device number.
- eventlet.green.os.makedev(major, minor, /)¶
Composes a raw device number from the major and minor device numbers.
- eventlet.green.os.makedirs(name [, mode=0o777][, exist_ok=False])¶
Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. If the target directory already exists, raise an OSError if exist_ok is False. Otherwise no exception is raised. This is recursive.
- eventlet.green.os.memfd_create(name, flags=1)¶
- eventlet.green.os.minor(device, /)¶
Extracts a device minor number from a raw device number.
- eventlet.green.os.mkdir(path, mode=511, *, dir_fd=None)¶
Create a directory.
- If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
- dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
The mode argument is ignored on Windows. Where it is used, the current umask value is first masked out.
- eventlet.green.os.mkfifo(path, mode=438, *, dir_fd=None)¶
Create a "fifo" (a POSIX named pipe).
- If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
- dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
- eventlet.green.os.mknod(path, mode=384, device=0, *, dir_fd=None)¶
Create a node in the file system.
Create a node in the file system (file, device special file or named pipe) at path. mode specifies both the permissions to use and the type of node to be created, being combined (bitwise OR) with one of S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode, device defines the newly created device special file (probably using os.makedev()). Otherwise device is ignored.
- If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
- dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
- eventlet.green.os.nice(increment, /)¶
Add increment to the priority of process and return the new priority.
- eventlet.green.os.open(file, flags, mode=511, dir_fd=None)¶
Wrap os.open This behaves identically, but collaborates with the hub's notify_opened protocol.
- eventlet.green.os.openpty()¶
Open a pseudo-terminal.
Return a tuple of (master_fd, slave_fd) containing open file descriptors for both the master and slave ends.
- eventlet.green.os.pathconf(path, name)¶
Return the configuration limit name for the file or directory path.
If there is no limit, return -1. On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
- eventlet.green.os.pidfd_open(pid, flags=0)¶
Return a file descriptor referring to the process pid.
The descriptor can be used to perform process management without races and signals.
- eventlet.green.os.pipe()¶
Create a pipe.
- Returns a tuple of two file descriptors:
(read_fd, write_fd)
- eventlet.green.os.pipe2(flags, /)¶
Create a pipe with flags set atomically.
- Returns a tuple of two file descriptors:
(read_fd, write_fd)
flags can be constructed by ORing together one or more of these values: O_NONBLOCK, O_CLOEXEC.
- eventlet.green.os.popen(cmd, mode='r', buffering=-1)¶
- eventlet.green.os.posix_fadvise(fd, offset, length, advice, /)¶
Announce an intention to access data in a specific pattern.
Announce an intention to access data in a specific pattern, thus allowing the kernel to make optimizations. The advice applies to the region of the file specified by fd starting at offset and continuing for length bytes. advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL, POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or POSIX_FADV_DONTNEED.
- eventlet.green.os.posix_fallocate(fd, offset, length, /)¶
Ensure a file has allocated at least a particular number of bytes on disk.
Ensure that the file specified by fd encompasses a range of bytes starting at offset bytes from the beginning and continuing for length bytes.
- eventlet.green.os.posix_spawn()¶
Execute the program specified by path in a new process.
- path
Path of executable file.
- argv
Tuple or list of strings.
- env
Dictionary of strings mapping to strings.
- file_actions
A sequence of file action tuples.
- setpgroup
The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
- resetids
If the value is true the POSIX_SPAWN_RESETIDS will be activated.
- setsid
If the value is true the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
- setsigmask
The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
- setsigdef
The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
- scheduler
A tuple with the scheduler policy (optional) and parameters.
- eventlet.green.os.posix_spawnp()¶
Execute the program specified by path in a new process.
- path
Path of executable file.
- argv
Tuple or list of strings.
- env
Dictionary of strings mapping to strings.
- file_actions
A sequence of file action tuples.
- setpgroup
The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
- resetids
If the value is True the POSIX_SPAWN_RESETIDS will be activated.
- setsid
If the value is True the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
- setsigmask
The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
- setsigdef
The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
- scheduler
A tuple with the scheduler policy (optional) and parameters.
- eventlet.green.os.pread(fd, length, offset, /)¶
Read a number of bytes from a file descriptor starting at a particular offset.
Read length bytes from file descriptor fd, starting at offset bytes from the beginning of the file. The file offset remains unchanged.
- eventlet.green.os.preadv(fd, buffers, offset, flags=0, /)¶
Reads from a file descriptor into a number of mutable bytes-like objects.
Combines the functionality of readv() and pread(). As readv(), it will transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data. Its fourth argument, specifies the file offset at which the input operation is to be performed. It will return the total number of bytes read (which can be less than the total capacity of all the objects).
The flags argument contains a bitwise OR of zero or more of the following flags:
RWF_HIPRI
RWF_NOWAIT
Using non-zero flags requires Linux 4.6 or newer.
- eventlet.green.os.putenv(name, value, /)¶
Change or add an environment variable.
- eventlet.green.os.pwrite(fd, buffer, offset, /)¶
Write bytes to a file descriptor starting at a particular offset.
Write buffer to fd, starting at offset bytes from the beginning of the file. Returns the number of bytes writte. Does not change the current file offset.
- eventlet.green.os.pwritev(fd, buffers, offset, flags=0, /)¶
Writes the contents of bytes-like objects to a file descriptor at a given offset.
Combines the functionality of writev() and pwrite(). All buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of first buffer is written before proceeding to second, and so on. The operating system may set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used. This function writes the contents of each object to the file descriptor and returns the total number of bytes written.
The flags argument contains a bitwise OR of zero or more of the following flags:
RWF_DSYNC
RWF_SYNC
RWF_APPEND
Using non-zero flags requires Linux 4.7 or newer.
- eventlet.green.os.read(fd, buffersize) string ¶
Read a file descriptor.
- eventlet.green.os.readlink(path, *, dir_fd=None)¶
Return a string representing the path to which the symbolic link points.
If dir_fd is not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform. If it is unavailable, using it will raise a NotImplementedError.
- eventlet.green.os.readv(fd, buffers, /)¶
Read from a file descriptor fd into an iterable of buffers.
The buffers should be mutable buffers accepting bytes. readv will transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.
readv returns the total number of bytes read, which may be less than the total capacity of all the buffers.
- eventlet.green.os.register_at_fork()¶
Register callables to be called when forking a new process.
- before
A callable to be called in the parent before the fork() syscall.
- after_in_child
A callable to be called in the child after fork().
- after_in_parent
A callable to be called in the parent after fork().
'before' callbacks are called in reverse order. 'after_in_child' and 'after_in_parent' callbacks are called in order.
- eventlet.green.os.remove(path, *, dir_fd=None)¶
Remove a file (same as unlink()).
- If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
- dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
- eventlet.green.os.removedirs(name)¶
Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is consumed or an error occurs. Errors during this latter phase are ignored -- they generally mean that a directory was not empty.
- eventlet.green.os.removexattr(path, attribute, *, follow_symlinks=True)¶
Remove extended attribute attribute on path.
path may be either a string, a path-like object, or an open file descriptor. If follow_symlinks is False, and the last element of the path is a symbolic
link, removexattr will modify the symbolic link itself instead of the file the link points to.
- eventlet.green.os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶
Rename a file or directory.
- If either src_dir_fd or dst_dir_fd is not None, it should be a file
descriptor open to a directory, and the respective path string (src or dst) should be relative; the path will then be relative to that directory.
- src_dir_fd and dst_dir_fd, may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
- eventlet.green.os.renames(old, new)¶
Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned until either the whole path is consumed or a nonempty directory is found.
Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file.
- eventlet.green.os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶
Rename a file or directory, overwriting the destination.
- If either src_dir_fd or dst_dir_fd is not None, it should be a file
descriptor open to a directory, and the respective path string (src or dst) should be relative; the path will then be relative to that directory.
- src_dir_fd and dst_dir_fd, may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
- eventlet.green.os.rmdir(path, *, dir_fd=None)¶
Remove a directory.
- If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
- dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
- eventlet.green.os.scandir(path=None)¶
Return an iterator of DirEntry objects for given path.
path can be specified as either str, bytes, or a path-like object. If path is bytes, the names of yielded DirEntry objects will also be bytes; in all other circumstances they will be str.
If path is None, uses the path='.'.
- eventlet.green.os.sched_get_priority_max(policy)¶
Get the maximum scheduling priority for policy.
- eventlet.green.os.sched_get_priority_min(policy)¶
Get the minimum scheduling priority for policy.
- eventlet.green.os.sched_getaffinity(pid, /)¶
Return the affinity of the process identified by pid (or the current process if zero).
The affinity is returned as a set of CPU identifiers.
- eventlet.green.os.sched_getparam(pid, /)¶
Returns scheduling parameters for the process identified by pid.
If pid is 0, returns parameters for the calling process. Return value is an instance of sched_param.
- eventlet.green.os.sched_getscheduler(pid, /)¶
Get the scheduling policy for the process identified by pid.
Passing 0 for pid returns the scheduling policy for the calling process.
- class eventlet.green.os.sched_param(sched_priority)¶
基类:
tuple
Currently has only one field: sched_priority
- sched_priority
A scheduling parameter.
- n_fields = 1¶
- n_sequence_fields = 1¶
- n_unnamed_fields = 0¶
- sched_priority¶
the scheduling priority
- eventlet.green.os.sched_rr_get_interval(pid, /)¶
Return the round-robin quantum for the process identified by pid, in seconds.
Value returned is a float.
- eventlet.green.os.sched_setaffinity(pid, mask, /)¶
Set the CPU affinity of the process identified by pid to mask.
mask should be an iterable of integers identifying CPUs.
- eventlet.green.os.sched_setparam(pid, param, /)¶
Set scheduling parameters for the process identified by pid.
If pid is 0, sets parameters for the calling process. param should be an instance of sched_param.
- eventlet.green.os.sched_setscheduler(pid, policy, param, /)¶
Set the scheduling policy for the process identified by pid.
If pid is 0, the calling process is changed. param is an instance of sched_param.
- eventlet.green.os.sched_yield()¶
Voluntarily relinquish the CPU.
- eventlet.green.os.sendfile(out_fd, in_fd, offset, count)¶
Copy count bytes from file descriptor in_fd to file descriptor out_fd.
- eventlet.green.os.set_blocking(fd, blocking, /)¶
Set the blocking mode of the specified file descriptor.
Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag otherwise.
- eventlet.green.os.set_inheritable(fd, inheritable, /)¶
Set the inheritable flag of the specified file descriptor.
- eventlet.green.os.setegid(egid, /)¶
Set the current process's effective group id.
- eventlet.green.os.seteuid(euid, /)¶
Set the current process's effective user id.
- eventlet.green.os.setgid(gid, /)¶
Set the current process's group id.
- eventlet.green.os.setgroups(groups, /)¶
Set the groups of the current process to list.
- eventlet.green.os.setns(fd, nstype=0)¶
Move the calling thread into different namespaces.
- fd
A file descriptor to a namespace.
- nstype
Type of namespace.
- eventlet.green.os.setpgid(pid, pgrp, /)¶
Call the system call setpgid(pid, pgrp).
- eventlet.green.os.setpgrp()¶
Make the current process the leader of its process group.
- eventlet.green.os.setpriority(which, who, priority)¶
Set program scheduling priority.
- eventlet.green.os.setregid(rgid, egid, /)¶
Set the current process's real and effective group ids.
- eventlet.green.os.setresgid(rgid, egid, sgid, /)¶
Set the current process's real, effective, and saved group ids.
- eventlet.green.os.setresuid(ruid, euid, suid, /)¶
Set the current process's real, effective, and saved user ids.
- eventlet.green.os.setreuid(ruid, euid, /)¶
Set the current process's real and effective user ids.
- eventlet.green.os.setsid()¶
Call the system call setsid().
- eventlet.green.os.setuid(uid, /)¶
Set the current process's user id.
- eventlet.green.os.setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)¶
Set extended attribute attribute on path to value.
path may be either a string, a path-like object, or an open file descriptor. If follow_symlinks is False, and the last element of the path is a symbolic
link, setxattr will modify the symbolic link itself instead of the file the link points to.
- eventlet.green.os.spawnl(mode, file, *args) integer ¶
Execute file with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
- eventlet.green.os.spawnle(mode, file, *args, env) integer ¶
Execute file with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
- eventlet.green.os.spawnlp(mode, file, *args) integer ¶
Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
- eventlet.green.os.spawnlpe(mode, file, *args, env) integer ¶
Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
- eventlet.green.os.spawnv(mode, file, args) integer ¶
Execute file with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
- eventlet.green.os.spawnve(mode, file, args, env) integer ¶
Execute file with arguments from args in a subprocess with the specified environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
- eventlet.green.os.spawnvp(mode, file, args) integer ¶
Execute file (which is looked for along $PATH) with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
- eventlet.green.os.spawnvpe(mode, file, args, env) integer ¶
Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
- eventlet.green.os.splice(src, dst, count, offset_src=None, offset_dst=None, flags=0)¶
Transfer count bytes from one pipe to a descriptor or vice versa.
- src
Source file descriptor.
- dst
Destination file descriptor.
- count
Number of bytes to copy.
- offset_src
Starting offset in src.
- offset_dst
Starting offset in dst.
- flags
Flags to modify the semantics of the call.
If offset_src is None, then src is read from the current position; respectively for offset_dst. The offset associated to the file descriptor that refers to a pipe must be None.
- eventlet.green.os.stat(path, *, dir_fd=None, follow_symlinks=True)¶
Perform a stat system call on the given path.
- path
Path to be examined; can be string, bytes, a path-like object or open-file-descriptor int.
- dir_fd
If not None, it should be a file descriptor open to a directory, and path should be a relative string; path will then be relative to that directory.
- follow_symlinks
If False, and the last element of the path is a symbolic link, stat will examine the symbolic link itself instead of the file the link points to.
- dir_fd and follow_symlinks may not be implemented
on your platform. If they are unavailable, using them will raise a NotImplementedError.
- It's an error to use dir_fd or follow_symlinks when specifying path as
an open file descriptor.
- class eventlet.green.os.stat_result(iterable=(), /)¶
基类:
tuple
stat_result: Result from stat, fstat, or lstat.
- This object may be accessed either as a tuple of
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.
Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev, or st_flags, they are available as attributes only.
See os.stat for more information.
- n_fields = 19¶
- n_sequence_fields = 10¶
- n_unnamed_fields = 3¶
- st_atime¶
time of last access
- st_atime_ns¶
time of last access in nanoseconds
- st_blksize¶
blocksize for filesystem I/O
- st_blocks¶
number of blocks allocated
- st_ctime¶
time of last change
- st_ctime_ns¶
time of last change in nanoseconds
- st_dev¶
device
- st_gid¶
group ID of owner
- st_ino¶
inode
- st_mode¶
protection bits
- st_mtime¶
time of last modification
- st_mtime_ns¶
time of last modification in nanoseconds
- st_nlink¶
number of hard links
- st_rdev¶
device type (if inode device)
- st_size¶
total size, in bytes
- st_uid¶
user ID of owner
- eventlet.green.os.statvfs(path)¶
Perform a statvfs system call on the given path.
path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
- class eventlet.green.os.statvfs_result(iterable=(), /)¶
基类:
tuple
statvfs_result: Result from statvfs or fstatvfs.
- This object may be accessed either as a tuple of
(bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),
or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.
See os.statvfs for more information.
- f_bavail¶
- f_bfree¶
- f_blocks¶
- f_bsize¶
- f_favail¶
- f_ffree¶
- f_files¶
- f_flag¶
- f_frsize¶
- f_fsid¶
- f_namemax¶
- n_fields = 11¶
- n_sequence_fields = 10¶
- n_unnamed_fields = 0¶
- eventlet.green.os.strerror(code, /)¶
Translate an error code to a message string.
- eventlet.green.os.symlink(src, dst, target_is_directory=False, *, dir_fd=None)¶
Create a symbolic link pointing to src named dst.
- target_is_directory is required on Windows if the target is to be
interpreted as a directory. (On Windows, symlink requires Windows 6.0 or greater, and raises a NotImplementedError otherwise.) target_is_directory is ignored on non-Windows platforms.
- If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
- dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
- eventlet.green.os.sync()¶
Force write of everything to disk.
- eventlet.green.os.sysconf(name, /)¶
Return an integer-valued system configuration variable.
- eventlet.green.os.system(command)¶
Execute the command in a subshell.
- eventlet.green.os.tcgetpgrp(fd, /)¶
Return the process group associated with the terminal specified by fd.
- eventlet.green.os.tcsetpgrp(fd, pgid, /)¶
Set the process group associated with the terminal specified by fd.
- class eventlet.green.os.terminal_size(iterable=(), /)¶
基类:
tuple
A tuple of (columns, lines) for holding terminal window size
- columns¶
width of the terminal window in characters
- lines¶
height of the terminal window in characters
- n_fields = 2¶
- n_sequence_fields = 2¶
- n_unnamed_fields = 0¶
- eventlet.green.os.times()¶
Return a collection containing process timing information.
- The object returned behaves like a named tuple with these fields:
(utime, stime, cutime, cstime, elapsed_time)
All fields are floating-point numbers.
- class eventlet.green.os.times_result(iterable=(), /)¶
基类:
tuple
times_result: Result from os.times().
- This object may be accessed either as a tuple of
(user, system, children_user, children_system, elapsed),
or via the attributes user, system, children_user, children_system, and elapsed.
See os.times for more information.
- children_system¶
system time of children
- children_user¶
user time of children
- elapsed¶
elapsed time since an arbitrary point in the past
- n_fields = 5¶
- n_sequence_fields = 5¶
- n_unnamed_fields = 0¶
- system¶
system time
- user¶
user time
- eventlet.green.os.truncate(path, length)¶
Truncate a file, specified by path, to a specific length.
- On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
- eventlet.green.os.ttyname(fd, /)¶
Return the name of the terminal device connected to 'fd'.
- fd
Integer file descriptor handle.
- eventlet.green.os.umask(mask, /)¶
Set the current numeric umask and return the previous umask.
- eventlet.green.os.uname()¶
Return an object identifying the current operating system.
- The object behaves like a named tuple with the following fields:
(sysname, nodename, release, version, machine)
- class eventlet.green.os.uname_result(iterable=(), /)¶
基类:
tuple
uname_result: Result from os.uname().
- This object may be accessed either as a tuple of
(sysname, nodename, release, version, machine),
or via the attributes sysname, nodename, release, version, and machine.
See os.uname for more information.
- machine¶
hardware identifier
- n_fields = 5¶
- n_sequence_fields = 5¶
- n_unnamed_fields = 0¶
- nodename¶
name of machine on network (implementation-defined)
- release¶
operating system release
- sysname¶
operating system name
- version¶
operating system version
- eventlet.green.os.unlink(path, *, dir_fd=None)¶
Remove a file (same as remove()).
- If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
- dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
- eventlet.green.os.unsetenv(name, /)¶
Delete an environment variable.
Disassociate parts of a process (or thread) execution context.
- flags
Namespaces to be unshared.
- eventlet.green.os.urandom(size, /)¶
Return a bytes object containing random bytes suitable for cryptographic use.
- eventlet.green.os.utime()¶
Set the access and modified time of path.
path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
- If times is not None, it must be a tuple (atime, mtime);
atime and mtime should be expressed as float seconds since the epoch.
- If ns is specified, it must be a tuple (atime_ns, mtime_ns);
atime_ns and mtime_ns should be expressed as integer nanoseconds since the epoch.
If times is None and ns is unspecified, utime uses the current time. Specifying tuples for both times and ns is an error.
- If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
- If follow_symlinks is False, and the last element of the path is a symbolic
link, utime will modify the symbolic link itself instead of the file the link points to.
- It is an error to use dir_fd or follow_symlinks when specifying path
as an open file descriptor.
- dir_fd and follow_symlinks may not be available on your platform.
If they are unavailable, using them will raise a NotImplementedError.
- eventlet.green.os.wait()¶
Wait for completion of a child process.
- eventlet.green.os.wait3(options)¶
Wait for completion of a child process.
- Returns a tuple of information about the child process:
(pid, status, rusage)
- eventlet.green.os.wait4(pid, options)¶
Wait for completion of a specific child process.
- Returns a tuple of information about the child process:
(pid, status, rusage)
- eventlet.green.os.waitid(idtype, id, options, /)¶
Returns the result of waiting for a process or processes.
- idtype
Must be one of be P_PID, P_PGID or P_ALL.
- id
The id to wait on.
- options
Constructed from the ORing of one or more of WEXITED, WSTOPPED or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
Returns either waitid_result or None if WNOHANG is specified and there are no children in a waitable state.
- class eventlet.green.os.waitid_result(iterable=(), /)¶
基类:
tuple
waitid_result: Result from waitid.
- This object may be accessed either as a tuple of
(si_pid, si_uid, si_signo, si_status, si_code),
or via the attributes si_pid, si_uid, and so on.
See os.waitid for more information.
- n_fields = 5¶
- n_sequence_fields = 5¶
- n_unnamed_fields = 0¶
- si_code¶
- si_pid¶
- si_signo¶
- si_status¶
- si_uid¶
- eventlet.green.os.waitpid(...)¶
- eventlet.green.os.waitpid(pid, options) None
Wait for completion of a given child process.
- eventlet.green.os.waitstatus_to_exitcode(status)¶
Convert a wait status to an exit code.
On Unix:
If WIFEXITED(status) is true, return WEXITSTATUS(status).
If WIFSIGNALED(status) is true, return -WTERMSIG(status).
Otherwise, raise a ValueError.
On Windows, return status shifted right by 8 bits.
On Unix, if the process is being traced or if waitpid() was called with WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true. This function must not be called if WIFSTOPPED(status) is true.
- eventlet.green.os.walk(top, topdown=True, onerror=None, followlinks=False)¶
Directory tree generator.
For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple
dirpath, dirnames, filenames
dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (including symlinks to directories, and excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).
If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up).
When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false has no effect on the behavior of os.walk(), since the directories in dirnames have already been generated by the time dirnames itself is generated. No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.
By default errors from the os.scandir() call are ignored. If optional arg 'onerror' is specified, it should be a function; it will be called with one argument, an OSError instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object.
By default, os.walk does not follow symbolic links to subdirectories on systems that support them. In order to get this functionality, set the optional argument 'followlinks' to true.
Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either.
Example:
import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'):
print(root, "consumes ") print(sum(getsize(join(root, name)) for name in files), end=" ") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
- eventlet.green.os.write(fd, string) byteswritten ¶
Write a string to a file descriptor.
- eventlet.green.os.writev(fd, buffers, /)¶
Iterate over buffers, and write the contents of each to a file descriptor.
Returns the total number of bytes written. buffers must be a sequence of bytes-like objects.
eventlet.green.profile module¶
This module is API-equivalent to the standard library profile
module
lbut it is greenthread-aware as well as thread-aware. Use this module
to profile Eventlet-based applications in preference to either profile
or cProfile
.
FIXME: No testcases for this module.
- class eventlet.green.profile.Profile(timer=None, bias=None)¶
基类:
Profile
- SwitchTasklet(t0, t1, t)¶
- TallyTimings()¶
- Unwind(cur, timings)¶
A function to unwind a 'cur' frame and tally the results
- dispatch = {'c_call': <function Profile.trace_dispatch_c_call>, 'c_exception': <function Profile.trace_dispatch_return>, 'c_return': <function Profile.trace_dispatch_c_return_extend_back>, 'call': <function Profile.trace_dispatch_call>, 'exception': <function Profile.trace_dispatch_exception>, 'return': <function Profile.trace_dispatch_return_extend_back>}¶
- runcall(func, *args, **kw)¶
- runctx(cmd, globals, locals)¶
- start(name='start')¶
- stop()¶
- trace_dispatch_c_return_extend_back(frame, t)¶
- trace_dispatch_return_extend_back(frame, t)¶
A hack function to override error checking in parent class. It allows invalid returns (where frames weren't preveiously entered into the profiler) which can happen for all the tasklets that suddenly start to get monitored. This means that the time will eventually be attributed to a call high in the chain, when there is a tasklet switch
- eventlet.green.profile.run(statement, filename=None, sort=-1)¶
Run statement under profiler optionally saving results in filename
This function takes a single argument that can be passed to the "exec" statement, and an optional file name. In all cases this routine attempts to "exec" its first argument and gather profiling statistics from the execution. If no file name is present, then this function automatically prints a simple profiling report, sorted by the standard name string (file/line/function-name) that is presented in each line.
- eventlet.green.profile.runctx(statement, globals, locals, filename=None)¶
Run statement under profiler, supplying your own globals and locals, optionally saving results in filename.
statement and filename have the same semantics as profile.run
eventlet.green.select module¶
- eventlet.green.select.get_fileno(obj)¶
- eventlet.green.select.select(read_list, write_list, error_list, timeout=None)¶
eventlet.green.selectors module¶
Selectors module.
This module allows high-level and efficient I/O multiplexing, built upon the select module primitives.
eventlet.green.socket module¶
- class eventlet.green.socket.AddressFamily(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
基类:
IntEnum
An enumeration.
- AF_ALG = 38¶
- AF_APPLETALK = 5¶
- AF_ASH = 18¶
- AF_ATMPVC = 8¶
- AF_ATMSVC = 20¶
- AF_AX25 = 3¶
- AF_BRIDGE = 7¶
- AF_CAN = 29¶
- AF_ECONET = 19¶
- AF_INET = 2¶
- AF_INET6 = 10¶
- AF_IPX = 4¶
- AF_IRDA = 23¶
- AF_KEY = 15¶
- AF_LLC = 26¶
- AF_NETBEUI = 13¶
- AF_NETLINK = 16¶
- AF_NETROM = 6¶
- AF_PACKET = 17¶
- AF_PPPOX = 24¶
- AF_QIPCRTR = 42¶
- AF_RDS = 21¶
- AF_ROSE = 11¶
- AF_ROUTE = 16¶
- AF_SECURITY = 14¶
- AF_SNA = 22¶
- AF_TIPC = 30¶
- AF_UNIX = 1¶
- AF_UNSPEC = 0¶
- AF_VSOCK = 40¶
- AF_WANPIPE = 25¶
- AF_X25 = 9¶
- eventlet.green.socket.CMSG_LEN(length) control message length ¶
Return the total length, without trailing padding, of an ancillary data item with associated data of the given length. This value can often be used as the buffer size for recvmsg() to receive a single item of ancillary data, but RFC 3542 requires portable applications to use CMSG_SPACE() and thus include space for padding, even when the item will be the last in the buffer. Raises OverflowError if length is outside the permissible range of values.
- eventlet.green.socket.CMSG_SPACE(length) buffer size ¶
Return the buffer size needed for recvmsg() to receive an ancillary data item with associated data of the given length, along with any trailing padding. The buffer space needed to receive multiple items is the sum of the CMSG_SPACE() values for their associated data lengths. Raises OverflowError if length is outside the permissible range of values.
- class eventlet.green.socket.SocketKind(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)¶
基类:
IntEnum
An enumeration.
- SOCK_CLOEXEC = 524288¶
- SOCK_DGRAM = 2¶
- SOCK_NONBLOCK = 2048¶
- SOCK_RAW = 3¶
- SOCK_RDM = 4¶
- SOCK_SEQPACKET = 5¶
- SOCK_STREAM = 1¶
- eventlet.green.socket.SocketType¶
socket
的别名
- eventlet.green.socket.close(integer) None ¶
Close an integer socket file descriptor. This is like os.close(), but for sockets; on some platforms os.close() won't work for socket file descriptors.
- eventlet.green.socket.create_connection(address, timeout=<object object>, source_address=None)¶
Connect to address and return the socket object.
Convenience function. Connect to address (a 2-tuple
(host, port)
) and return the socket object. Passing the optional timeout parameter will set the timeout on the socket instance before attempting to connect. If no timeout is supplied, the global default timeout setting returned bygetdefaulttimeout()
is used.
- eventlet.green.socket.create_server(address, *, family=AddressFamily.AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False)¶
Convenience function which creates a SOCK_STREAM type socket bound to address (a 2-tuple (host, port)) and return the socket object.
family should be either AF_INET or AF_INET6. backlog is the queue size passed to socket.listen(). reuse_port dictates whether to use the SO_REUSEPORT socket option. dualstack_ipv6: if true and the platform supports it, it will create an AF_INET6 socket able to accept both IPv4 or IPv6 connections. When false it will explicitly disable this option on platforms that enable it by default (e.g. Linux).
>>> with create_server(('', 8000)) as server: ... while True: ... conn, addr = server.accept() ... # handle new connection
- eventlet.green.socket.dup(integer) integer ¶
Duplicate an integer socket file descriptor. This is like os.dup(), but for sockets; on some platforms os.dup() won't work for socket file descriptors.
- eventlet.green.socket.fromfd(*args)¶
- eventlet.green.socket.getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)¶
Replacement for Python's socket.getaddrinfo
This does the A and AAAA lookups asynchronously after which it calls the OS' getaddrinfo(3) using the AI_NUMERICHOST flag. This flag ensures getaddrinfo(3) does not use the network itself and allows us to respect all the other arguments like the native OS.
- eventlet.green.socket.getdefaulttimeout() timeout ¶
Returns the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.
- eventlet.green.socket.getfqdn(name='')¶
Get fully qualified domain name from name.
An empty argument is interpreted as meaning the local host.
First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available and name was given, it is returned unchanged. If name was empty, '0.0.0.0' or '::', hostname from gethostname() is returned.
- eventlet.green.socket.gethostbyaddr(host)¶
Return the true host name, a list of aliases, and a list of IP addresses, for a host. The host argument is a string giving a host name or IP number.
- eventlet.green.socket.gethostbyname(hostname)¶
Replacement for Python's socket.gethostbyname
- eventlet.green.socket.gethostbyname_ex(hostname)¶
Replacement for Python's socket.gethostbyname_ex
- eventlet.green.socket.gethostname() string ¶
Return the current host name.
- eventlet.green.socket.getnameinfo(sockaddr, flags)¶
Replacement for Python's socket.getnameinfo.
Currently only supports IPv4.
- eventlet.green.socket.getprotobyname(name) integer ¶
Return the protocol number for the named protocol. (Rarely used.)
- eventlet.green.socket.getservbyname(servicename[, protocolname]) integer ¶
Return a port number from a service name and protocol name. The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match.
- eventlet.green.socket.getservbyport(port[, protocolname]) string ¶
Return the service name from a port number and protocol name. The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match.
- eventlet.green.socket.has_dualstack_ipv6()¶
Return True if the platform supports creating a SOCK_STREAM socket which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections.
- eventlet.green.socket.htonl(integer) integer ¶
Convert a 32-bit integer from host to network byte order.
- eventlet.green.socket.htons(integer) integer ¶
Convert a 16-bit unsigned integer from host to network byte order.
- eventlet.green.socket.if_indextoname(if_index)¶
Returns the interface name corresponding to the interface index if_index.
- eventlet.green.socket.if_nameindex()¶
Returns a list of network interface information (index, name) tuples.
- eventlet.green.socket.if_nametoindex(if_name)¶
Returns the interface index corresponding to the interface name if_name.
- eventlet.green.socket.inet_aton(string) bytes giving packed 32-bit IP representation ¶
Convert an IP address in string format (123.45.67.89) to the 32-bit packed binary format used in low-level network functions.
- eventlet.green.socket.inet_ntoa(packed_ip) ip_address_string ¶
Convert an IP address from 32-bit packed binary format to string format
- eventlet.green.socket.inet_ntop(af, packed_ip) string formatted IP address ¶
Convert a packed IP address of the given family to string format.
- eventlet.green.socket.inet_pton(af, ip) packed IP address string ¶
Convert an IP address from string format to a packed string suitable for use with low-level network functions.
- eventlet.green.socket.ntohl(integer) integer ¶
Convert a 32-bit integer from network to host byte order.
- eventlet.green.socket.ntohs(integer) integer ¶
Convert a 16-bit unsigned integer from network to host byte order.
- eventlet.green.socket.recv_fds(sock, bufsize, maxfds[, flags]) (data, list of file ¶
descriptors, msg_flags, address)
Receive up to maxfds file descriptors returning the message data and a list containing the descriptors.
- eventlet.green.socket.send_fds(sock, buffers, fds[, flags[, address]]) integer ¶
Send the list of file descriptors fds over an AF_UNIX socket.
- eventlet.green.socket.setdefaulttimeout(timeout)¶
Set the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.
- eventlet.green.socket.sethostname(name)¶
Sets the hostname to name.
- eventlet.green.socket.socket¶
GreenSocket
的别名
- eventlet.green.socket.socketpair(*args)¶
- eventlet.green.socket.timeout¶
TimeoutError
的别名
eventlet.green.ssl module¶
- class eventlet.green.ssl.GreenSSLContext(protocol=None, *args, **kwargs)¶
基类:
SSLContext
- property maximum_version¶
- property minimum_version¶
- property options¶
- property verify_flags¶
- property verify_mode¶
- wrap_socket(sock, *a, **kw)¶
- class eventlet.green.ssl.GreenSSLSocket(sock=None, keyfile=None, certfile=None, server_side=False, cert_reqs=VerifyMode.CERT_NONE, ssl_version=_SSLMethod.PROTOCOL_TLS, ca_certs=None, do_handshake_on_connect=True, *args, **kw)¶
基类:
SSLSocket
This is a green version of the SSLSocket class from the ssl module added in 2.6. For documentation on it, please see the Python standard documentation.
Python nonblocking ssl objects don't give errors when the other end of the socket is closed (they do notice when the other end is shutdown, though). Any write/read operations will simply hang if the socket is closed from the other end. There is no obvious fix for this problem; it appears to be a limitation of Python's ssl object implementation. A workaround is to set a reasonable timeout on the socket using settimeout(), and to close/reopen the connection when a timeout occurs at an unexpected juncture in the code.
- accept()¶
Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.
- connect(addr)¶
Connects to remote ADDR, and then wraps the connection in an SSL channel.
- do_handshake()¶
Perform a TLS/SSL handshake.
- dup() socket object ¶
Duplicate the socket. Return a new socket object connected to the same system resource. The new socket is non-inheritable.
- gettimeout() timeout ¶
Returns the timeout in seconds (float) associated with socket operations. A timeout of None indicates that timeouts on socket operations are disabled.
- read(len=1024, buffer=None)¶
Read up to LEN bytes and return them. Return zero-length string on EOF.
- recv(buffersize[, flags]) data ¶
Receive up to buffersize bytes from the socket. For the optional flags argument, see the Unix manual. When no data is available, block until at least one byte is available or until the remote end is closed. When the remote end is closed and all data is read, return the empty string.
- recv_into(buffer[, nbytes[, flags]]) nbytes_read ¶
A version of recv() that stores its data into a buffer rather than creating a new string. Receive up to buffersize bytes from the socket. If buffersize is not specified (or 0), receive up to the size available in the given buffer.
See recv() for documentation about the flags.
- recvfrom(buffersize[, flags]) -> (data, address info)¶
Like recv(buffersize, flags) but also return the sender's address info.
- recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)¶
Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.
- send(data[, flags]) count ¶
Send a data string to the socket. For the optional flags argument, see the Unix manual. Return the number of bytes sent; this may be less than len(data) if the network is busy.
- sendall(data[, flags])¶
Send a data string to the socket. For the optional flags argument, see the Unix manual. This calls send() repeatedly until all data is sent. If an error occurs, it's impossible to tell how much data has been sent.
- sendto(data, [flags, ]address) count ¶
Like send(data, flags) but allows specifying the destination address. For IP sockets, the address is a pair (hostaddr, port).
- setblocking(flag)¶
Set the socket to blocking (flag is true) or non-blocking (false). setblocking(True) is equivalent to settimeout(None); setblocking(False) is equivalent to settimeout(0.0).
- settimeout(timeout)¶
Set a timeout on socket operations. 'timeout' can be a float, giving in seconds, or None. Setting a timeout of None disables the timeout feature and is equivalent to setblocking(1). Setting a timeout of zero is the same as setblocking(0).
- unwrap()¶
Start the SSL shutdown handshake.
- write(data)¶
Write DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.
- eventlet.green.ssl.SSLContext¶
GreenSSLContext
的别名
- eventlet.green.ssl.SSLSocket¶
GreenSSLSocket
的别名
- eventlet.green.ssl.create_default_context(*a, **kw)¶
- eventlet.green.ssl.green_create_default_context(*a, **kw)¶
- eventlet.green.ssl.wrap_socket(sock, *a, **kw)¶
eventlet.green.subprocess module¶
Subprocesses with accessible I/O streams
This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes.
For a complete description of this module see the Python documentation.
Main API¶
- run(...): Runs a command, waits for it to complete, then returns a
CompletedProcess instance.
Popen(...): A class for flexibly executing a command in a new process
Constants¶
DEVNULL: Special value that indicates that os.devnull should be used PIPE: Special value that indicates a pipe should be created STDOUT: Special value that indicates that stderr should go to stdout
Older API¶
- call(...): Runs a command, waits for it to complete, then returns
the return code.
- check_call(...): Same as call() but raises CalledProcessError()
if return code is not 0
- check_output(...): Same as check_call() but returns the contents of
stdout instead of a return code
- getoutput(...): Runs a command in the shell, waits for it to complete,
then returns the output
- getstatusoutput(...): Runs a command in the shell, waits for it to complete,
then returns a (exitcode, output) tuple
- exception eventlet.green.subprocess.CalledProcessError(returncode, cmd, output=None, stderr=None)¶
-
Raised when run() is called with check=True and the process returns a non-zero exit status.
- Attributes:
cmd, returncode, stdout, stderr, output
- property stdout¶
Alias for output attribute, to match stderr
- class eventlet.green.subprocess.CompletedProcess(args, returncode, stdout=None, stderr=None)¶
基类:
object
A process that has finished running.
This is returned by run().
- Attributes:
args: The list or str args passed to run(). returncode: The exit code of the process, negative for signals. stdout: The standard output (None if not captured). stderr: The standard error (None if not captured).
- check_returncode()¶
Raise CalledProcessError if the exit code is non-zero.
- class eventlet.green.subprocess.Popen(args, bufsize=0, *argss, **kwds)¶
基类:
Popen
eventlet-friendly version of subprocess.Popen
- wait(timeout=None, check_interval=0.01)¶
Wait for child process to terminate; returns self.returncode.
- exception eventlet.green.subprocess.TimeoutExpired(cmd, timeout, output=None, stderr=None)¶
-
This exception is raised when the timeout expires while waiting for a child process.
- Attributes:
cmd, output, stdout, stderr, timeout
- property stdout¶
- eventlet.green.subprocess.call(*popenargs, timeout=None, **kwargs)¶
Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
- eventlet.green.subprocess.check_call(*popenargs, **kwargs)¶
Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.
The arguments are the same as for the call function. Example:
check_call(["ls", "-l"])
- eventlet.green.subprocess.check_output(*popenargs, timeout=None, **kwargs)¶
Run command with arguments and return its output.
If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"]) b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) b'ls: non_existent_file: No such file or directory\n'
There is an additional optional argument, "input", allowing you to pass a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument, as it too will be used internally. Example:
>>> check_output(["sed", "-e", "s/foo/bar/"], ... input=b"when in the course of fooman events\n") b'when in the course of barman events\n'
By default, all communication is in bytes, and therefore any "input" should be bytes, and the return value will be bytes. If in text mode, any "input" should be a string, and the return value will be a string decoded according to locale encoding, or by "encoding" if set. Text mode is triggered by setting any of text, encoding, errors or universal_newlines.
- eventlet.green.subprocess.getoutput(cmd, *, encoding=None, errors=None)¶
Return output (stdout or stderr) of executing cmd in a shell.
Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command's output. Example:
>>> import subprocess >>> subprocess.getoutput('ls /bin/ls') '/bin/ls'
- eventlet.green.subprocess.getstatusoutput(cmd, *, encoding=None, errors=None)¶
Return (exitcode, output) of executing cmd in a shell.
Execute the string 'cmd' in a shell with 'check_output' and return a 2-tuple (status, output). The locale encoding is used to decode the output and process newlines.
A trailing newline is stripped from the output. The exit status for the command can be interpreted according to the rules for the function 'wait'. Example:
>>> import subprocess >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> subprocess.getstatusoutput('cat /bin/junk') (1, 'cat: /bin/junk: No such file or directory') >>> subprocess.getstatusoutput('/bin/junk') (127, 'sh: /bin/junk: not found') >>> subprocess.getstatusoutput('/bin/kill $$') (-15, '')
- eventlet.green.subprocess.run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs)¶
Run command with arguments and return a CompletedProcess instance.
The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them, or pass capture_output=True to capture both.
If check is True and the exit code was non-zero, it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute, and output & stderr attributes if those streams were captured.
If timeout is given, and the process takes too long, a TimeoutExpired exception will be raised.
There is an optional argument "input", allowing you to pass bytes or a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument, as it will be used internally.
By default, all communication is in bytes, and therefore any "input" should be bytes, and the stdout and stderr will be bytes. If in text mode, any "input" should be a string, and stdout and stderr will be strings decoded according to locale encoding, or by "encoding" if set. Text mode is triggered by setting any of text, encoding, errors or universal_newlines.
The other arguments are the same as for the Popen constructor.
eventlet.green.thread module¶
Implements the standard thread module, using greenthreads.
- eventlet.green.thread.allocate(*a)¶
- eventlet.green.thread.allocate_lock(*a)¶
- eventlet.green.thread.exit()¶
- eventlet.green.thread.get_ident(gr=None)¶
- eventlet.green.thread.interrupt_main()¶
- eventlet.green.thread.stack_size(size=None)¶
- eventlet.green.thread.start_new(function, args=(), kwargs=None)¶
- eventlet.green.thread.start_new_thread(function, args=(), kwargs=None)¶
eventlet.green.threading module¶
Thread module emulating a subset of Java's threading model.
- class eventlet.green.threading.Barrier(parties, action=None, timeout=None)¶
基类:
object
Implements a Barrier.
Useful for synchronizing a fixed number of threads at known synchronization points. Threads block on 'wait()' and are simultaneously awoken once they have all made that call.
- abort()¶
Place the barrier into a 'broken' state.
Useful in case of error. Any currently waiting threads and threads attempting to 'wait()' will have BrokenBarrierError raised.
- property broken¶
Return True if the barrier is in a broken state.
- property n_waiting¶
Return the number of threads currently waiting at the barrier.
- property parties¶
Return the number of threads required to trip the barrier.
- reset()¶
Reset the barrier to the initial state.
Any threads currently waiting will get the BrokenBarrier exception raised.
- wait(timeout=None)¶
Wait for the barrier.
When the specified number of threads have started waiting, they are all simultaneously awoken. If an 'action' was provided for the barrier, one of the threads will have executed that callback prior to returning. Returns an individual index number from 0 to 'parties-1'.
- class eventlet.green.threading.BoundedSemaphore(value=1)¶
基类:
Semaphore
Implements a bounded semaphore.
A bounded semaphore checks to make sure its current value doesn't exceed its initial value. If it does, ValueError is raised. In most situations semaphores are used to guard resources with limited capacity.
If the semaphore is released too many times it's a sign of a bug. If not given, value defaults to 1.
Like regular semaphores, bounded semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1.
- release(n=1)¶
Release a semaphore, incrementing the internal counter by one or more.
When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread.
If the number of releases exceeds the number of acquires, raise a ValueError.
- exception eventlet.green.threading.BrokenBarrierError¶
基类:
RuntimeError
- class eventlet.green.threading.Condition(lock=None)¶
基类:
object
Class that implements a condition variable.
A condition variable allows one or more threads to wait until they are notified by another thread.
If the lock argument is given and not None, it must be a Lock or RLock object, and it is used as the underlying lock. Otherwise, a new RLock object is created and used as the underlying lock.
- notify(n=1)¶
Wake up one or more threads waiting on this condition, if any.
If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.
This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting.
- notifyAll()¶
Wake up all threads waiting on this condition.
This method is deprecated, use notify_all() instead.
- notify_all()¶
Wake up all threads waiting on this condition.
If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.
- wait(timeout=None)¶
Wait until notified or until a timeout occurs.
If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call for the same condition variable in another thread, or until the optional timeout occurs. Once awakened or timed out, it re-acquires the lock and returns.
When the timeout argument is present and not None, it should be a floating-point number specifying a timeout for the operation in seconds (or fractions thereof).
When the underlying lock is an RLock, it is not released using its release() method, since this may not actually unlock the lock when it was acquired multiple times recursively. Instead, an internal interface of the RLock class is used, which really unlocks it even when it has been recursively acquired several times. Another internal interface is then used to restore the recursion level when the lock is reacquired.
- wait_for(predicate, timeout=None)¶
Wait until a condition evaluates to True.
predicate should be a callable which result will be interpreted as a boolean value. A timeout may be provided giving the maximum time to wait.
- class eventlet.green.threading.Event¶
基类:
object
Class implementing event objects.
Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. The flag is initially false.
- clear()¶
Reset the internal flag to false.
Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.
- isSet()¶
Return true if and only if the internal flag is true.
This method is deprecated, use is_set() instead.
- is_set()¶
Return true if and only if the internal flag is true.
- set()¶
Set the internal flag to true.
All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.
- wait(timeout=None)¶
Block until the internal flag is true.
If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.
When the timeout argument is present and not None, it should be a floating-point number specifying a timeout for the operation in seconds (or fractions thereof).
This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.
- eventlet.green.threading.ExceptHookArgs(args)¶
- eventlet.green.threading.Lock(*a)¶
- eventlet.green.threading.RLock(*args, **kwargs)¶
Factory function that returns a new reentrant lock.
A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it.
- class eventlet.green.threading.Semaphore(value=1)¶
基类:
object
This class implements semaphore objects.
Semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1.
- acquire(blocking=True, timeout=None)¶
Acquire a semaphore, decrementing the internal counter by one.
When invoked without arguments: if the internal counter is larger than zero on entry, decrement it by one and return immediately. If it is zero on entry, block, waiting until some other thread has called release() to make it larger than zero. This is done with proper interlocking so that if multiple acquire() calls are blocked, release() will wake exactly one of them up. The implementation may pick one at random, so the order in which blocked threads are awakened should not be relied on. There is no return value in this case.
When invoked with blocking set to true, do the same thing as when called without arguments, and return true.
When invoked with blocking set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true.
When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return false. Return true otherwise.
- release(n=1)¶
Release a semaphore, incrementing the internal counter by one or more.
When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread.
- class eventlet.green.threading.Thread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)¶
基类:
object
A class that represents a thread of control.
This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass.
- property daemon¶
A boolean value indicating whether this thread is a daemon thread.
This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.
The entire Python program exits when only daemon threads are left.
- getName()¶
Return a string used for identification purposes only.
This method is deprecated, use the name attribute instead.
- property ident¶
Thread identifier of this thread or None if it has not been started.
This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.
- isDaemon()¶
Return whether this thread is a daemon.
This method is deprecated, use the daemon attribute instead.
- is_alive()¶
Return whether the thread is alive.
This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().
- join(timeout=None)¶
Wait until the thread terminates.
This blocks the calling thread until the thread whose join() method is called terminates -- either normally or through an unhandled exception or until the optional timeout occurs.
When the timeout argument is present and not None, it should be a floating-point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened -- if the thread is still alive, the join() call timed out.
When the timeout argument is not present or None, the operation will block until the thread terminates.
A thread can be join()ed many times.
join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.
- property name¶
A string used for identification purposes only.
It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.
- run()¶
Method representing the thread's activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
- setDaemon(daemonic)¶
Set whether this thread is a daemon.
This method is deprecated, use the .daemon property instead.
- setName(name)¶
Set the name string for this thread.
This method is deprecated, use the name attribute instead.
- start()¶
Start the thread's activity.
It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control.
This method will raise a RuntimeError if called more than once on the same thread object.
- eventlet.green.threading.ThreadError¶
RuntimeError
的别名
- class eventlet.green.threading.Timer(interval, function, args=None, kwargs=None)¶
基类:
Thread
Call a function after a specified number of seconds:
t = Timer(30.0, f, args=None, kwargs=None) t.start() t.cancel() # stop the timer's action if it's still waiting
- cancel()¶
Stop the timer if it hasn't finished yet.
- run()¶
Method representing the thread's activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
- eventlet.green.threading.active_count()¶
Return the number of Thread objects currently alive.
The returned count is equal to the length of the list returned by enumerate().
- eventlet.green.threading.current_thread()¶
- eventlet.green.threading.enumerate()¶
Return a list of all Thread objects currently alive.
The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started.
- eventlet.green.threading.excepthook(args, /)¶
Handle uncaught Thread.run() exception.
- eventlet.green.threading.get_ident(gr=None)¶
- eventlet.green.threading.getprofile()¶
Get the profiler function as set by threading.setprofile().
- eventlet.green.threading.gettrace()¶
Get the trace function as set by threading.settrace().
- class eventlet.green.threading.local(*args, **kw)¶
基类:
_localbase
- eventlet.green.threading.main_thread()¶
Return the main thread object.
In normal conditions, the main thread is the thread from which the Python interpreter was started.
- eventlet.green.threading.setprofile(func)¶
Set a profile function for all threads started from the threading module.
The func will be passed to sys.setprofile() for each thread, before its run() method is called.
- eventlet.green.threading.setprofile_all_threads(func)¶
Set a profile function for all threads started from the threading module and all Python threads that are currently executing.
The func will be passed to sys.setprofile() for each thread, before its run() method is called.
- eventlet.green.threading.settrace(func)¶
Set a trace function for all threads started from the threading module.
The func will be passed to sys.settrace() for each thread, before its run() method is called.
- eventlet.green.threading.settrace_all_threads(func)¶
Set a trace function for all threads started from the threading module and all Python threads that are currently executing.
The func will be passed to sys.settrace() for each thread, before its run() method is called.
- eventlet.green.threading.stack_size(size=None)¶
eventlet.green.time module¶
eventlet.green.urllib2 module¶
eventlet.green.zmq module¶
The zmq
module wraps the Socket
and Context
found in pyzmq
to be non blocking.
- class eventlet.green.zmq.Context(io_threads: int = 1)¶
- class eventlet.green.zmq.Context(io_threads: Context)
- class eventlet.green.zmq.Context(*, shadow: Context | int)
基类:
Context
Subclass of
zmq.Context
- class eventlet.green.zmq.Socket(context, socket_type)¶
基类:
Socket
Green version of :class:
zmq.core.socket.Socket
.- The following three methods are always overridden:
send
recv
getsockopt
To ensure that the
zmq.NOBLOCK
flag is set and that sending or receiving is deferred to the hub (using :func:eventlet.hubs.trampoline
) if azmq.EAGAIN
(retry) error is raised.- For some socket types, the following methods are also overridden:
send_multipart
recv_multipart
- close(linger=None)¶
Close the socket.
If linger is specified, LINGER sockopt will be set prior to closing.
Note: closing a zmq Socket may not close the underlying sockets if there are undelivered messages. Only after all messages are delivered or discarded by reaching the socket's LINGER timeout (default: forever) will the underlying sockets be closed.
This can be called to close the socket by hand. If this is not called, the socket will automatically be closed when it is garbage collected, in which case you may see a ResourceWarning about the unclosed socket.
- getsockopt(option)¶
Get the value of a socket option.
See the 0MQ API documentation for details on specific options.
Parameters¶
- optionint
The option to get. Available values will depend on your version of libzmq. Examples include:
zmq.IDENTITY, HWM, LINGER, FD, EVENTS
Returns¶
- optvalint or bytes
The value of the option as a bytestring or int.
- recv(flags=0, copy=True, track=False)¶
Receive a message.
With flags=NOBLOCK, this raises
ZMQError
if no messages have arrived; otherwise, this waits until a message arrives. SeePoller
for more general non-blocking I/O.Parameters¶
- flagsint
0 or NOBLOCK.
- copybool
Should the message be received in a copying or non-copying manner? If False a Frame object is returned, if True a string copy of message is returned.
- trackbool
Should the message be tracked for notification that ZMQ has finished with it? (ignored if copy=True)
Returns¶
- msgbytes or Frame
The received message frame. If copy is False, then it will be a Frame, otherwise it will be bytes.
Raises¶
- ZMQError
for any of the reasons zmq_msg_recv might fail (including if NOBLOCK is set and no new messages have arrived).
- recv_json(flags=0, **kwargs)¶
Receive a Python object as a message using json to serialize.
Keyword arguments are passed on to json.loads
Parameters¶
- flagsint
Any valid flags for
Socket.recv()
.
Returns¶
- objPython object
The Python object that arrives as a message.
Raises¶
- ZMQError
for any of the reasons
recv()
might fail
- recv_multipart(flags=0, copy=True, track=False)¶
Receive a multipart message as a list of bytes or Frame objects
Parameters¶
- flagsint, optional
Any valid flags for
Socket.recv()
.- copybool, optional
Should the message frame(s) be received in a copying or non-copying manner? If False a Frame object is returned for each part, if True a copy of the bytes is made for each frame.
- trackbool, optional
Should the message frame(s) be tracked for notification that ZMQ has finished with it? (ignored if copy=True)
Returns¶
- msg_partslist
A list of frames in the multipart message; either Frames or bytes, depending on copy.
Raises¶
- ZMQError
for any of the reasons
recv()
might fail
- recv_pyobj(flags=0)¶
Receive a Python object as a message using pickle to serialize.
Parameters¶
- flagsint
Any valid flags for
Socket.recv()
.
Returns¶
- objPython object
The Python object that arrives as a message.
Raises¶
- ZMQError
for any of the reasons
recv()
might fail
- recv_string(flags=0, encoding='utf-8')¶
Receive a unicode string, as sent by send_string.
Parameters¶
- flagsint
Any valid flags for
Socket.recv()
.- encodingstr
The encoding to be used
Returns¶
- sstr
The Python unicode string that arrives as encoded bytes.
Raises¶
- ZMQError
for any of the reasons
Socket.recv()
might fail
- send(msg, flags=0, copy=True, track=False)¶
Send a single zmq message frame on this socket.
This queues the message to be sent by the IO thread at a later time.
With flags=NOBLOCK, this raises
ZMQError
if the queue is full; otherwise, this waits until space is available. SeePoller
for more general non-blocking I/O.Parameters¶
- databytes, Frame, memoryview
The content of the message. This can be any object that provides the Python buffer API (i.e. memoryview(data) can be called).
- flagsint
0, NOBLOCK, SNDMORE, or NOBLOCK|SNDMORE.
- copybool
Should the message be sent in a copying or non-copying manner.
- trackbool
Should the message be tracked for notification that ZMQ has finished with it? (ignored if copy=True)
- routing_idint
For use with SERVER sockets
- groupstr
For use with RADIO sockets
Returns¶
- Noneif copy or not track
None if message was sent, raises an exception otherwise.
- MessageTrackerif track and not copy
a MessageTracker object, whose done property will be False until the send is completed.
Raises¶
- TypeError
If a unicode object is passed
- ValueError
If track=True, but an untracked Frame is passed.
- ZMQError
If the send does not succeed for any reason (including if NOBLOCK is set and the outgoing queue is full).
在 17.0 版本发生变更: DRAFT support for routing_id and group arguments.
- send_json(obj, flags=0, **kwargs)¶
Send a Python object as a message using json to serialize.
Keyword arguments are passed on to json.dumps
Parameters¶
- objPython object
The Python object to send
- flagsint
Any valid flags for
Socket.send()
- send_multipart(msg_parts, flags=0, copy=True, track=False)¶
Send a sequence of buffers as a multipart message.
The zmq.SNDMORE flag is added to all msg parts before the last.
Parameters¶
- msg_partsiterable
A sequence of objects to send as a multipart message. Each element can be any sendable object (Frame, bytes, buffer-providers)
- flagsint, optional
Any valid flags for
Socket.send()
. SNDMORE is added automatically for frames before the last.- copybool, optional
Should the frame(s) be sent in a copying or non-copying manner. If copy=False, frames smaller than self.copy_threshold bytes will be copied anyway.
- trackbool, optional
Should the frame(s) be tracked for notification that ZMQ has finished with it (ignored if copy=True).
Returns¶
None : if copy or not track MessageTracker : if track and not copy
a MessageTracker object, whose done property will be False until the last send is completed.
- send_pyobj(obj, flags=0, protocol=2)¶
Send a Python object as a message using pickle to serialize.
Parameters¶
- objPython object
The Python object to send.
- flagsint
Any valid flags for
Socket.send()
.- protocolint
The pickle protocol number to use. The default is pickle.DEFAULT_PROTOCOL where defined, and pickle.HIGHEST_PROTOCOL elsewhere.
- send_string(u, flags=0, copy=True, encoding='utf-8')¶
Send a Python unicode string as a message with an encoding.
0MQ communicates with raw bytes, so you must encode/decode text (str) around 0MQ.
Parameters¶
- ustr
The unicode string to send.
- flagsint, optional
Any valid flags for
Socket.send()
.- encodingstr
The encoding to be used