doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
reversed(seq) Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).
python.library.functions#reversed
rlcompleter — Completion function for GNU readline Source code: Lib/rlcompleter.py The rlcompleter module defines a completion function suitable for the readline module by completing valid Python identifiers and keywords. When this module is imported on a Unix platform with the readline module available, an instance of the Completer class is automatically created and its complete() method is set as the readline completer. Example: >>> import rlcompleter >>> import readline >>> readline.parse_and_bind("tab: complete") >>> readline. <TAB PRESSED> readline.__doc__ readline.get_line_buffer( readline.read_init_file( readline.__file__ readline.insert_text( readline.set_completer( readline.__name__ readline.parse_and_bind( >>> readline. The rlcompleter module is designed for use with Python’s interactive mode. Unless Python is run with the -S option, the module is automatically imported and configured (see Readline configuration). On platforms without readline, the Completer class defined by this module can still be used for custom purposes. Completer Objects Completer objects have the following method: Completer.complete(text, state) Return the stateth completion for text. If called for text that doesn’t include a period character ('.'), it will complete from names currently defined in __main__, builtins and keywords (as defined by the keyword module). If called for a dotted name, it will try to evaluate anything without obvious side-effects (functions will not be evaluated, but it can generate calls to __getattr__()) up to the last part, and find matches for the rest via the dir() function. Any exception raised during the evaluation of the expression is caught, silenced and None is returned.
python.library.rlcompleter
Completer.complete(text, state) Return the stateth completion for text. If called for text that doesn’t include a period character ('.'), it will complete from names currently defined in __main__, builtins and keywords (as defined by the keyword module). If called for a dotted name, it will try to evaluate anything without obvious side-effects (functions will not be evaluated, but it can generate calls to __getattr__()) up to the last part, and find matches for the rest via the dir() function. Any exception raised during the evaluation of the expression is caught, silenced and None is returned.
python.library.rlcompleter#rlcompleter.Completer.complete
round(number[, ndigits]) Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as number. For a general Python object number, round delegates to number.__round__. Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
python.library.functions#round
runpy — Locating and executing Python modules Source code: Lib/runpy.py The runpy module is used to locate and run Python modules without importing them first. Its main use is to implement the -m command line switch that allows scripts to be located using the Python module namespace rather than the filesystem. Note that this is not a sandbox module - all code is executed in the current process, and any side effects (such as cached imports of other modules) will remain in place after the functions have returned. Furthermore, any functions and classes defined by the executed code are not guaranteed to work correctly after a runpy function has returned. If that limitation is not acceptable for a given use case, importlib is likely to be a more suitable choice than this module. The runpy module provides two functions: runpy.run_module(mod_name, init_globals=None, run_name=None, alter_sys=False) Execute the code of the specified module and return the resulting module globals dictionary. The module’s code is first located using the standard import mechanism (refer to PEP 302 for details) and then executed in a fresh module namespace. The mod_name argument should be an absolute module name. If the module name refers to a package rather than a normal module, then that package is imported and the __main__ submodule within that package is then executed and the resulting module globals dictionary returned. The optional dictionary argument init_globals may be used to pre-populate the module’s globals dictionary before the code is executed. The supplied dictionary will not be modified. If any of the special global variables below are defined in the supplied dictionary, those definitions are overridden by run_module(). The special global variables __name__, __spec__, __file__, __cached__, __loader__ and __package__ are set in the globals dictionary before the module code is executed (Note that this is a minimal set of variables - other variables may be set implicitly as an interpreter implementation detail). __name__ is set to run_name if this optional argument is not None, to mod_name + '.__main__' if the named module is a package and to the mod_name argument otherwise. __spec__ will be set appropriately for the actually imported module (that is, __spec__.name will always be mod_name or mod_name + '.__main__, never run_name). __file__, __cached__, __loader__ and __package__ are set as normal based on the module spec. If the argument alter_sys is supplied and evaluates to True, then sys.argv[0] is updated with the value of __file__ and sys.modules[__name__] is updated with a temporary module object for the module being executed. Both sys.argv[0] and sys.modules[__name__] are restored to their original values before the function returns. Note that this manipulation of sys is not thread-safe. Other threads may see the partially initialised module, as well as the altered list of arguments. It is recommended that the sys module be left alone when invoking this function from threaded code. See also The -m option offering equivalent functionality from the command line. Changed in version 3.1: Added ability to execute packages by looking for a __main__ submodule. Changed in version 3.2: Added __cached__ global variable (see PEP 3147). Changed in version 3.4: Updated to take advantage of the module spec feature added by PEP 451. This allows __cached__ to be set correctly for modules run this way, as well as ensuring the real module name is always accessible as __spec__.name. runpy.run_path(file_path, init_globals=None, run_name=None) Execute the code at the named filesystem location and return the resulting module globals dictionary. As with a script name supplied to the CPython command line, the supplied path may refer to a Python source file, a compiled bytecode file or a valid sys.path entry containing a __main__ module (e.g. a zipfile containing a top-level __main__.py file). For a simple script, the specified code is simply executed in a fresh module namespace. For a valid sys.path entry (typically a zipfile or directory), the entry is first added to the beginning of sys.path. The function then looks for and executes a __main__ module using the updated path. Note that there is no special protection against invoking an existing __main__ entry located elsewhere on sys.path if there is no such module at the specified location. The optional dictionary argument init_globals may be used to pre-populate the module’s globals dictionary before the code is executed. The supplied dictionary will not be modified. If any of the special global variables below are defined in the supplied dictionary, those definitions are overridden by run_path(). The special global variables __name__, __spec__, __file__, __cached__, __loader__ and __package__ are set in the globals dictionary before the module code is executed (Note that this is a minimal set of variables - other variables may be set implicitly as an interpreter implementation detail). __name__ is set to run_name if this optional argument is not None and to '<run_path>' otherwise. If the supplied path directly references a script file (whether as source or as precompiled byte code), then __file__ will be set to the supplied path, and __spec__, __cached__, __loader__ and __package__ will all be set to None. If the supplied path is a reference to a valid sys.path entry, then __spec__ will be set appropriately for the imported __main__ module (that is, __spec__.name will always be __main__). __file__, __cached__, __loader__ and __package__ will be set as normal based on the module spec. A number of alterations are also made to the sys module. Firstly, sys.path may be altered as described above. sys.argv[0] is updated with the value of file_path and sys.modules[__name__] is updated with a temporary module object for the module being executed. All modifications to items in sys are reverted before the function returns. Note that, unlike run_module(), the alterations made to sys are not optional in this function as these adjustments are essential to allowing the execution of sys.path entries. As the thread-safety limitations still apply, use of this function in threaded code should be either serialised with the import lock or delegated to a separate process. See also Interface options for equivalent functionality on the command line (python path/to/script). New in version 3.2. Changed in version 3.4: Updated to take advantage of the module spec feature added by PEP 451. This allows __cached__ to be set correctly in the case where __main__ is imported from a valid sys.path entry rather than being executed directly. See also PEP 338 – Executing modules as scripts PEP written and implemented by Nick Coghlan. PEP 366 – Main module explicit relative imports PEP written and implemented by Nick Coghlan. PEP 451 – A ModuleSpec Type for the Import System PEP written and implemented by Eric Snow Command line and environment - CPython command line details The importlib.import_module() function
python.library.runpy
runpy.run_module(mod_name, init_globals=None, run_name=None, alter_sys=False) Execute the code of the specified module and return the resulting module globals dictionary. The module’s code is first located using the standard import mechanism (refer to PEP 302 for details) and then executed in a fresh module namespace. The mod_name argument should be an absolute module name. If the module name refers to a package rather than a normal module, then that package is imported and the __main__ submodule within that package is then executed and the resulting module globals dictionary returned. The optional dictionary argument init_globals may be used to pre-populate the module’s globals dictionary before the code is executed. The supplied dictionary will not be modified. If any of the special global variables below are defined in the supplied dictionary, those definitions are overridden by run_module(). The special global variables __name__, __spec__, __file__, __cached__, __loader__ and __package__ are set in the globals dictionary before the module code is executed (Note that this is a minimal set of variables - other variables may be set implicitly as an interpreter implementation detail). __name__ is set to run_name if this optional argument is not None, to mod_name + '.__main__' if the named module is a package and to the mod_name argument otherwise. __spec__ will be set appropriately for the actually imported module (that is, __spec__.name will always be mod_name or mod_name + '.__main__, never run_name). __file__, __cached__, __loader__ and __package__ are set as normal based on the module spec. If the argument alter_sys is supplied and evaluates to True, then sys.argv[0] is updated with the value of __file__ and sys.modules[__name__] is updated with a temporary module object for the module being executed. Both sys.argv[0] and sys.modules[__name__] are restored to their original values before the function returns. Note that this manipulation of sys is not thread-safe. Other threads may see the partially initialised module, as well as the altered list of arguments. It is recommended that the sys module be left alone when invoking this function from threaded code. See also The -m option offering equivalent functionality from the command line. Changed in version 3.1: Added ability to execute packages by looking for a __main__ submodule. Changed in version 3.2: Added __cached__ global variable (see PEP 3147). Changed in version 3.4: Updated to take advantage of the module spec feature added by PEP 451. This allows __cached__ to be set correctly for modules run this way, as well as ensuring the real module name is always accessible as __spec__.name.
python.library.runpy#runpy.run_module
runpy.run_path(file_path, init_globals=None, run_name=None) Execute the code at the named filesystem location and return the resulting module globals dictionary. As with a script name supplied to the CPython command line, the supplied path may refer to a Python source file, a compiled bytecode file or a valid sys.path entry containing a __main__ module (e.g. a zipfile containing a top-level __main__.py file). For a simple script, the specified code is simply executed in a fresh module namespace. For a valid sys.path entry (typically a zipfile or directory), the entry is first added to the beginning of sys.path. The function then looks for and executes a __main__ module using the updated path. Note that there is no special protection against invoking an existing __main__ entry located elsewhere on sys.path if there is no such module at the specified location. The optional dictionary argument init_globals may be used to pre-populate the module’s globals dictionary before the code is executed. The supplied dictionary will not be modified. If any of the special global variables below are defined in the supplied dictionary, those definitions are overridden by run_path(). The special global variables __name__, __spec__, __file__, __cached__, __loader__ and __package__ are set in the globals dictionary before the module code is executed (Note that this is a minimal set of variables - other variables may be set implicitly as an interpreter implementation detail). __name__ is set to run_name if this optional argument is not None and to '<run_path>' otherwise. If the supplied path directly references a script file (whether as source or as precompiled byte code), then __file__ will be set to the supplied path, and __spec__, __cached__, __loader__ and __package__ will all be set to None. If the supplied path is a reference to a valid sys.path entry, then __spec__ will be set appropriately for the imported __main__ module (that is, __spec__.name will always be __main__). __file__, __cached__, __loader__ and __package__ will be set as normal based on the module spec. A number of alterations are also made to the sys module. Firstly, sys.path may be altered as described above. sys.argv[0] is updated with the value of file_path and sys.modules[__name__] is updated with a temporary module object for the module being executed. All modifications to items in sys are reverted before the function returns. Note that, unlike run_module(), the alterations made to sys are not optional in this function as these adjustments are essential to allowing the execution of sys.path entries. As the thread-safety limitations still apply, use of this function in threaded code should be either serialised with the import lock or delegated to a separate process. See also Interface options for equivalent functionality on the command line (python path/to/script). New in version 3.2. Changed in version 3.4: Updated to take advantage of the module spec feature added by PEP 451. This allows __cached__ to be set correctly in the case where __main__ is imported from a valid sys.path entry rather than being executed directly.
python.library.runpy#runpy.run_path
exception RuntimeError Raised when an error is detected that doesn’t fall in any of the other categories. The associated value is a string indicating what precisely went wrong.
python.library.exceptions#RuntimeError
exception RuntimeWarning Base class for warnings about dubious runtime behavior.
python.library.exceptions#RuntimeWarning
sched — Event scheduler Source code: Lib/sched.py The sched module defines a class which implements a general purpose event scheduler: class sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep) The scheduler class defines a generic interface to scheduling events. It needs two functions to actually deal with the “outside world” — timefunc should be callable without arguments, and return a number (the “time”, in any units whatsoever). The delayfunc function should be callable with one argument, compatible with the output of timefunc, and should delay that many time units. delayfunc will also be called with the argument 0 after each event is run to allow other threads an opportunity to run in multi-threaded applications. Changed in version 3.3: timefunc and delayfunc parameters are optional. Changed in version 3.3: scheduler class can be safely used in multi-threaded environments. Example: >>> import sched, time >>> s = sched.scheduler(time.time, time.sleep) >>> def print_time(a='default'): ... print("From print_time", time.time(), a) ... >>> def print_some_times(): ... print(time.time()) ... s.enter(10, 1, print_time) ... s.enter(5, 2, print_time, argument=('positional',)) ... s.enter(5, 1, print_time, kwargs={'a': 'keyword'}) ... s.run() ... print(time.time()) ... >>> print_some_times() 930343690.257 From print_time 930343695.274 positional From print_time 930343695.275 keyword From print_time 930343700.273 default 930343700.276 Scheduler Objects scheduler instances have the following methods and attributes: scheduler.enterabs(time, priority, action, argument=(), kwargs={}) Schedule a new event. The time argument should be a numeric type compatible with the return value of the timefunc function passed to the constructor. Events scheduled for the same time will be executed in the order of their priority. A lower number represents a higher priority. Executing the event means executing action(*argument, **kwargs). argument is a sequence holding the positional arguments for action. kwargs is a dictionary holding the keyword arguments for action. Return value is an event which may be used for later cancellation of the event (see cancel()). Changed in version 3.3: argument parameter is optional. Changed in version 3.3: kwargs parameter was added. scheduler.enter(delay, priority, action, argument=(), kwargs={}) Schedule an event for delay more time units. Other than the relative time, the other arguments, the effect and the return value are the same as those for enterabs(). Changed in version 3.3: argument parameter is optional. Changed in version 3.3: kwargs parameter was added. scheduler.cancel(event) Remove the event from the queue. If event is not an event currently in the queue, this method will raise a ValueError. scheduler.empty() Return True if the event queue is empty. scheduler.run(blocking=True) Run all scheduled events. This method will wait (using the delayfunc() function passed to the constructor) for the next event, then execute it and so on until there are no more scheduled events. If blocking is false executes the scheduled events due to expire soonest (if any) and then return the deadline of the next scheduled call in the scheduler (if any). Either action or delayfunc can raise an exception. In either case, the scheduler will maintain a consistent state and propagate the exception. If an exception is raised by action, the event will not be attempted in future calls to run(). If a sequence of events takes longer to run than the time available before the next event, the scheduler will simply fall behind. No events will be dropped; the calling code is responsible for canceling events which are no longer pertinent. Changed in version 3.3: blocking parameter was added. scheduler.queue Read-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as a named tuple with the following fields: time, priority, action, argument, kwargs.
python.library.sched
class sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep) The scheduler class defines a generic interface to scheduling events. It needs two functions to actually deal with the “outside world” — timefunc should be callable without arguments, and return a number (the “time”, in any units whatsoever). The delayfunc function should be callable with one argument, compatible with the output of timefunc, and should delay that many time units. delayfunc will also be called with the argument 0 after each event is run to allow other threads an opportunity to run in multi-threaded applications. Changed in version 3.3: timefunc and delayfunc parameters are optional. Changed in version 3.3: scheduler class can be safely used in multi-threaded environments.
python.library.sched#sched.scheduler
scheduler.cancel(event) Remove the event from the queue. If event is not an event currently in the queue, this method will raise a ValueError.
python.library.sched#sched.scheduler.cancel
scheduler.empty() Return True if the event queue is empty.
python.library.sched#sched.scheduler.empty
scheduler.enter(delay, priority, action, argument=(), kwargs={}) Schedule an event for delay more time units. Other than the relative time, the other arguments, the effect and the return value are the same as those for enterabs(). Changed in version 3.3: argument parameter is optional. Changed in version 3.3: kwargs parameter was added.
python.library.sched#sched.scheduler.enter
scheduler.enterabs(time, priority, action, argument=(), kwargs={}) Schedule a new event. The time argument should be a numeric type compatible with the return value of the timefunc function passed to the constructor. Events scheduled for the same time will be executed in the order of their priority. A lower number represents a higher priority. Executing the event means executing action(*argument, **kwargs). argument is a sequence holding the positional arguments for action. kwargs is a dictionary holding the keyword arguments for action. Return value is an event which may be used for later cancellation of the event (see cancel()). Changed in version 3.3: argument parameter is optional. Changed in version 3.3: kwargs parameter was added.
python.library.sched#sched.scheduler.enterabs
scheduler.queue Read-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as a named tuple with the following fields: time, priority, action, argument, kwargs.
python.library.sched#sched.scheduler.queue
scheduler.run(blocking=True) Run all scheduled events. This method will wait (using the delayfunc() function passed to the constructor) for the next event, then execute it and so on until there are no more scheduled events. If blocking is false executes the scheduled events due to expire soonest (if any) and then return the deadline of the next scheduled call in the scheduler (if any). Either action or delayfunc can raise an exception. In either case, the scheduler will maintain a consistent state and propagate the exception. If an exception is raised by action, the event will not be attempted in future calls to run(). If a sequence of events takes longer to run than the time available before the next event, the scheduler will simply fall behind. No events will be dropped; the calling code is responsible for canceling events which are no longer pertinent. Changed in version 3.3: blocking parameter was added.
python.library.sched#sched.scheduler.run
secrets — Generate secure random numbers for managing secrets New in version 3.6. Source code: Lib/secrets.py The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets. In particular, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography. See also PEP 506 Random numbers The secrets module provides access to the most secure source of randomness that your operating system provides. class secrets.SystemRandom A class for generating random numbers using the highest-quality sources provided by the operating system. See random.SystemRandom for additional details. secrets.choice(sequence) Return a randomly-chosen element from a non-empty sequence. secrets.randbelow(n) Return a random int in the range [0, n). secrets.randbits(k) Return an int with k random bits. Generating tokens The secrets module provides functions for generating secure tokens, suitable for applications such as password resets, hard-to-guess URLs, and similar. secrets.token_bytes([nbytes=None]) Return a random byte string containing nbytes number of bytes. If nbytes is None or not supplied, a reasonable default is used. >>> token_bytes(16) b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b' secrets.token_hex([nbytes=None]) Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits. If nbytes is None or not supplied, a reasonable default is used. >>> token_hex(16) 'f9bf78b9a18ce6d46a0cd2b0b86df9da' secrets.token_urlsafe([nbytes=None]) Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is None or not supplied, a reasonable default is used. >>> token_urlsafe(16) 'Drmhze6EPcv0fN_81Bj-nA' How many bytes should tokens use? To be secure against brute-force attacks, tokens need to have sufficient randomness. Unfortunately, what is considered sufficient will necessarily increase as computers get more powerful and able to make more guesses in a shorter period. As of 2015, it is believed that 32 bytes (256 bits) of randomness is sufficient for the typical use-case expected for the secrets module. For those who want to manage their own token length, you can explicitly specify how much randomness is used for tokens by giving an int argument to the various token_* functions. That argument is taken as the number of bytes of randomness to use. Otherwise, if no argument is provided, or if the argument is None, the token_* functions will use a reasonable default instead. Note That default is subject to change at any time, including during maintenance releases. Other functions secrets.compare_digest(a, b) Return True if strings a and b are equal, otherwise False, in such a way as to reduce the risk of timing attacks. See hmac.compare_digest() for additional details. Recipes and best practices This section shows recipes and best practices for using secrets to manage a basic level of security. Generate an eight-character alphanumeric password: import string import secrets alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(8)) Note Applications should not store passwords in a recoverable format, whether plain text or encrypted. They should be salted and hashed using a cryptographically-strong one-way (irreversible) hash function. Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits: import string import secrets alphabet = string.ascii_letters + string.digits while True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): break Generate an XKCD-style passphrase: import secrets # On standard Linux systems, use a convenient dictionary file. # Other platforms may need to provide their own word-list. with open('/usr/share/dict/words') as f: words = [word.strip() for word in f] password = ' '.join(secrets.choice(words) for i in range(4)) Generate a hard-to-guess temporary URL containing a security token suitable for password recovery applications: import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()
python.library.secrets
secrets.choice(sequence) Return a randomly-chosen element from a non-empty sequence.
python.library.secrets#secrets.choice
secrets.compare_digest(a, b) Return True if strings a and b are equal, otherwise False, in such a way as to reduce the risk of timing attacks. See hmac.compare_digest() for additional details.
python.library.secrets#secrets.compare_digest
secrets.randbelow(n) Return a random int in the range [0, n).
python.library.secrets#secrets.randbelow
secrets.randbits(k) Return an int with k random bits.
python.library.secrets#secrets.randbits
class secrets.SystemRandom A class for generating random numbers using the highest-quality sources provided by the operating system. See random.SystemRandom for additional details.
python.library.secrets#secrets.SystemRandom
secrets.token_bytes([nbytes=None]) Return a random byte string containing nbytes number of bytes. If nbytes is None or not supplied, a reasonable default is used. >>> token_bytes(16) b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'
python.library.secrets#secrets.token_bytes
secrets.token_hex([nbytes=None]) Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits. If nbytes is None or not supplied, a reasonable default is used. >>> token_hex(16) 'f9bf78b9a18ce6d46a0cd2b0b86df9da'
python.library.secrets#secrets.token_hex
secrets.token_urlsafe([nbytes=None]) Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is None or not supplied, a reasonable default is used. >>> token_urlsafe(16) 'Drmhze6EPcv0fN_81Bj-nA'
python.library.secrets#secrets.token_urlsafe
select — Waiting for I/O completion This module provides access to the select() and poll() functions available in most operating systems, devpoll() available on Solaris and derivatives, epoll() available on Linux 2.5+ and kqueue() available on most BSD. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read. Note The selectors module allows high-level and efficient I/O multiplexing, built upon the select module primitives. Users are encouraged to use the selectors module instead, unless they want precise control over the OS-level primitives used. The module defines the following: exception select.error A deprecated alias of OSError. Changed in version 3.3: Following PEP 3151, this class was made an alias of OSError. select.devpoll() (Only supported on Solaris and derivatives.) Returns a /dev/poll polling object; see section /dev/poll Polling Objects below for the methods supported by devpoll objects. devpoll() objects are linked to the number of file descriptors allowed at the time of instantiation. If your program reduces this value, devpoll() will fail. If your program increases this value, devpoll() may return an incomplete list of active file descriptors. The new file descriptor is non-inheritable. New in version 3.3. Changed in version 3.4: The new file descriptor is now non-inheritable. select.epoll(sizehint=-1, flags=0) (Only supported on Linux 2.5.44 and newer.) Return an edge polling object, which can be used as Edge or Level Triggered interface for I/O events. sizehint informs epoll about the expected number of events to be registered. It must be positive, or -1 to use the default. It is only used on older systems where epoll_create1() is not available; otherwise it has no effect (though its value is still checked). flags is deprecated and completely ignored. However, when supplied, its value must be 0 or select.EPOLL_CLOEXEC, otherwise OSError is raised. See the Edge and Level Trigger Polling (epoll) Objects section below for the methods supported by epolling objects. epoll objects support the context management protocol: when used in a with statement, the new file descriptor is automatically closed at the end of the block. The new file descriptor is non-inheritable. Changed in version 3.3: Added the flags parameter. Changed in version 3.4: Support for the with statement was added. The new file descriptor is now non-inheritable. Deprecated since version 3.4: The flags parameter. select.EPOLL_CLOEXEC is used by default now. Use os.set_inheritable() to make the file descriptor inheritable. select.poll() (Not supported by all operating systems.) Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events; see section Polling Objects below for the methods supported by polling objects. select.kqueue() (Only supported on BSD.) Returns a kernel queue object; see section Kqueue Objects below for the methods supported by kqueue objects. The new file descriptor is non-inheritable. Changed in version 3.4: The new file descriptor is now non-inheritable. select.kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0) (Only supported on BSD.) Returns a kernel event object; see section Kevent Objects below for the methods supported by kevent objects. select.select(rlist, wlist, xlist[, timeout]) This is a straightforward interface to the Unix select() system call. The first three arguments are iterables of ‘waitable objects’: either integers representing file descriptors or objects with a parameterless method named fileno() returning such an integer: rlist: wait until ready for reading wlist: wait until ready for writing xlist: wait for an “exceptional condition” (see the manual page for what your system considers such a condition) Empty iterables are allowed, but acceptance of three empty iterables is platform-dependent. (It is known to work on Unix but not on Windows.) The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks. The return value is a triple of lists of objects that are ready: subsets of the first three arguments. When the time-out is reached without a file descriptor becoming ready, three empty lists are returned. Among the acceptable object types in the iterables are Python file objects (e.g. sys.stdin, or objects returned by open() or os.popen()), socket objects returned by socket.socket(). You may also define a wrapper class yourself, as long as it has an appropriate fileno() method (that really returns a file descriptor, not just a random integer). Note File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock. Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError. select.PIPE_BUF The minimum number of bytes which can be written without blocking to a pipe when the pipe has been reported as ready for writing by select(), poll() or another interface in this module. This doesn’t apply to other kind of file-like objects such as sockets. This value is guaranteed by POSIX to be at least 512. Availability: Unix New in version 3.2. /dev/poll Polling Objects Solaris and derivatives have /dev/poll. While select() is O(highest file descriptor) and poll() is O(number of file descriptors), /dev/poll is O(active file descriptors). /dev/poll behaviour is very close to the standard poll() object. devpoll.close() Close the file descriptor of the polling object. New in version 3.4. devpoll.closed True if the polling object is closed. New in version 3.4. devpoll.fileno() Return the file descriptor number of the polling object. New in version 3.4. devpoll.register(fd[, eventmask]) Register a file descriptor with the polling object. Future calls to the poll() method will then check whether the file descriptor has any pending I/O events. fd can be either an integer, or an object with a fileno() method that returns an integer. File objects implement fileno(), so they can also be used as the argument. eventmask is an optional bitmask describing the type of events you want to check for. The constants are the same that with poll() object. The default value is a combination of the constants POLLIN, POLLPRI, and POLLOUT. Warning Registering a file descriptor that’s already registered is not an error, but the result is undefined. The appropriate action is to unregister or modify it first. This is an important difference compared with poll(). devpoll.modify(fd[, eventmask]) This method does an unregister() followed by a register(). It is (a bit) more efficient that doing the same explicitly. devpoll.unregister(fd) Remove a file descriptor being tracked by a polling object. Just like the register() method, fd can be an integer or an object with a fileno() method that returns an integer. Attempting to remove a file descriptor that was never registered is safely ignored. devpoll.poll([timeout]) Polls the set of registered file descriptors, and returns a possibly-empty list containing (fd, event) 2-tuples for the descriptors that have events or errors to report. fd is the file descriptor, and event is a bitmask with bits set for the reported events for that descriptor — POLLIN for waiting input, POLLOUT to indicate that the descriptor can be written to, and so forth. An empty list indicates that the call timed out and no file descriptors had any events to report. If timeout is given, it specifies the length of time in milliseconds which the system will wait for events before returning. If timeout is omitted, -1, or None, the call will block until there is an event for this poll object. Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError. Edge and Level Trigger Polling (epoll) Objects https://linux.die.net/man/4/epoll eventmask Constant Meaning EPOLLIN Available for read EPOLLOUT Available for write EPOLLPRI Urgent data for read EPOLLERR Error condition happened on the assoc. fd EPOLLHUP Hang up happened on the assoc. fd EPOLLET Set Edge Trigger behavior, the default is Level Trigger behavior EPOLLONESHOT Set one-shot behavior. After one event is pulled out, the fd is internally disabled EPOLLEXCLUSIVE Wake only one epoll object when the associated fd has an event. The default (if this flag is not set) is to wake all epoll objects polling on a fd. EPOLLRDHUP Stream socket peer closed connection or shut down writing half of connection. EPOLLRDNORM Equivalent to EPOLLIN EPOLLRDBAND Priority data band can be read. EPOLLWRNORM Equivalent to EPOLLOUT EPOLLWRBAND Priority data may be written. EPOLLMSG Ignored. New in version 3.6: EPOLLEXCLUSIVE was added. It’s only supported by Linux Kernel 4.5 or later. epoll.close() Close the control file descriptor of the epoll object. epoll.closed True if the epoll object is closed. epoll.fileno() Return the file descriptor number of the control fd. epoll.fromfd(fd) Create an epoll object from a given file descriptor. epoll.register(fd[, eventmask]) Register a fd descriptor with the epoll object. epoll.modify(fd, eventmask) Modify a registered file descriptor. epoll.unregister(fd) Remove a registered file descriptor from the epoll object. Changed in version 3.9: The method no longer ignores the EBADF error. epoll.poll(timeout=None, maxevents=-1) Wait for events. timeout in seconds (float) Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError. Polling Objects The poll() system call, supported on most Unix systems, provides better scalability for network servers that service many, many clients at the same time. poll() scales better because the system call only requires listing the file descriptors of interest, while select() builds a bitmap, turns on bits for the fds of interest, and then afterward the whole bitmap has to be linearly scanned again. select() is O(highest file descriptor), while poll() is O(number of file descriptors). poll.register(fd[, eventmask]) Register a file descriptor with the polling object. Future calls to the poll() method will then check whether the file descriptor has any pending I/O events. fd can be either an integer, or an object with a fileno() method that returns an integer. File objects implement fileno(), so they can also be used as the argument. eventmask is an optional bitmask describing the type of events you want to check for, and can be a combination of the constants POLLIN, POLLPRI, and POLLOUT, described in the table below. If not specified, the default value used will check for all 3 types of events. Constant Meaning POLLIN There is data to read POLLPRI There is urgent data to read POLLOUT Ready for output: writing will not block POLLERR Error condition of some sort POLLHUP Hung up POLLRDHUP Stream socket peer closed connection, or shut down writing half of connection POLLNVAL Invalid request: descriptor not open Registering a file descriptor that’s already registered is not an error, and has the same effect as registering the descriptor exactly once. poll.modify(fd, eventmask) Modifies an already registered fd. This has the same effect as register(fd, eventmask). Attempting to modify a file descriptor that was never registered causes an OSError exception with errno ENOENT to be raised. poll.unregister(fd) Remove a file descriptor being tracked by a polling object. Just like the register() method, fd can be an integer or an object with a fileno() method that returns an integer. Attempting to remove a file descriptor that was never registered causes a KeyError exception to be raised. poll.poll([timeout]) Polls the set of registered file descriptors, and returns a possibly-empty list containing (fd, event) 2-tuples for the descriptors that have events or errors to report. fd is the file descriptor, and event is a bitmask with bits set for the reported events for that descriptor — POLLIN for waiting input, POLLOUT to indicate that the descriptor can be written to, and so forth. An empty list indicates that the call timed out and no file descriptors had any events to report. If timeout is given, it specifies the length of time in milliseconds which the system will wait for events before returning. If timeout is omitted, negative, or None, the call will block until there is an event for this poll object. Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError. Kqueue Objects kqueue.close() Close the control file descriptor of the kqueue object. kqueue.closed True if the kqueue object is closed. kqueue.fileno() Return the file descriptor number of the control fd. kqueue.fromfd(fd) Create a kqueue object from a given file descriptor. kqueue.control(changelist, max_events[, timeout]) → eventlist Low level interface to kevent changelist must be an iterable of kevent objects or None max_events must be 0 or a positive integer timeout in seconds (floats possible); the default is None, to wait forever Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError. Kevent Objects https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 kevent.ident Value used to identify the event. The interpretation depends on the filter but it’s usually the file descriptor. In the constructor ident can either be an int or an object with a fileno() method. kevent stores the integer internally. kevent.filter Name of the kernel filter. Constant Meaning KQ_FILTER_READ Takes a descriptor and returns whenever there is data available to read KQ_FILTER_WRITE Takes a descriptor and returns whenever there is data available to write KQ_FILTER_AIO AIO requests KQ_FILTER_VNODE Returns when one or more of the requested events watched in fflag occurs KQ_FILTER_PROC Watch for events on a process id KQ_FILTER_NETDEV Watch for events on a network device [not available on Mac OS X] KQ_FILTER_SIGNAL Returns whenever the watched signal is delivered to the process KQ_FILTER_TIMER Establishes an arbitrary timer kevent.flags Filter action. Constant Meaning KQ_EV_ADD Adds or modifies an event KQ_EV_DELETE Removes an event from the queue KQ_EV_ENABLE Permitscontrol() to returns the event KQ_EV_DISABLE Disablesevent KQ_EV_ONESHOT Removes event after first occurrence KQ_EV_CLEAR Reset the state after an event is retrieved KQ_EV_SYSFLAGS internal event KQ_EV_FLAG1 internal event KQ_EV_EOF Filter specific EOF condition KQ_EV_ERROR See return values kevent.fflags Filter specific flags. KQ_FILTER_READ and KQ_FILTER_WRITE filter flags: Constant Meaning KQ_NOTE_LOWAT low water mark of a socket buffer KQ_FILTER_VNODE filter flags: Constant Meaning KQ_NOTE_DELETE unlink() was called KQ_NOTE_WRITE a write occurred KQ_NOTE_EXTEND the file was extended KQ_NOTE_ATTRIB an attribute was changed KQ_NOTE_LINK the link count has changed KQ_NOTE_RENAME the file was renamed KQ_NOTE_REVOKE access to the file was revoked KQ_FILTER_PROC filter flags: Constant Meaning KQ_NOTE_EXIT the process has exited KQ_NOTE_FORK the process has called fork() KQ_NOTE_EXEC the process has executed a new process KQ_NOTE_PCTRLMASK internal filter flag KQ_NOTE_PDATAMASK internal filter flag KQ_NOTE_TRACK follow a process across fork() KQ_NOTE_CHILD returned on the child process for NOTE_TRACK KQ_NOTE_TRACKERR unable to attach to a child KQ_FILTER_NETDEV filter flags (not available on Mac OS X): Constant Meaning KQ_NOTE_LINKUP link is up KQ_NOTE_LINKDOWN link is down KQ_NOTE_LINKINV link state is invalid kevent.data Filter specific data. kevent.udata User defined value.
python.library.select
select.devpoll() (Only supported on Solaris and derivatives.) Returns a /dev/poll polling object; see section /dev/poll Polling Objects below for the methods supported by devpoll objects. devpoll() objects are linked to the number of file descriptors allowed at the time of instantiation. If your program reduces this value, devpoll() will fail. If your program increases this value, devpoll() may return an incomplete list of active file descriptors. The new file descriptor is non-inheritable. New in version 3.3. Changed in version 3.4: The new file descriptor is now non-inheritable.
python.library.select#select.devpoll
devpoll.close() Close the file descriptor of the polling object. New in version 3.4.
python.library.select#select.devpoll.close
devpoll.closed True if the polling object is closed. New in version 3.4.
python.library.select#select.devpoll.closed
devpoll.fileno() Return the file descriptor number of the polling object. New in version 3.4.
python.library.select#select.devpoll.fileno
devpoll.modify(fd[, eventmask]) This method does an unregister() followed by a register(). It is (a bit) more efficient that doing the same explicitly.
python.library.select#select.devpoll.modify
devpoll.poll([timeout]) Polls the set of registered file descriptors, and returns a possibly-empty list containing (fd, event) 2-tuples for the descriptors that have events or errors to report. fd is the file descriptor, and event is a bitmask with bits set for the reported events for that descriptor — POLLIN for waiting input, POLLOUT to indicate that the descriptor can be written to, and so forth. An empty list indicates that the call timed out and no file descriptors had any events to report. If timeout is given, it specifies the length of time in milliseconds which the system will wait for events before returning. If timeout is omitted, -1, or None, the call will block until there is an event for this poll object. Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError.
python.library.select#select.devpoll.poll
devpoll.register(fd[, eventmask]) Register a file descriptor with the polling object. Future calls to the poll() method will then check whether the file descriptor has any pending I/O events. fd can be either an integer, or an object with a fileno() method that returns an integer. File objects implement fileno(), so they can also be used as the argument. eventmask is an optional bitmask describing the type of events you want to check for. The constants are the same that with poll() object. The default value is a combination of the constants POLLIN, POLLPRI, and POLLOUT. Warning Registering a file descriptor that’s already registered is not an error, but the result is undefined. The appropriate action is to unregister or modify it first. This is an important difference compared with poll().
python.library.select#select.devpoll.register
devpoll.unregister(fd) Remove a file descriptor being tracked by a polling object. Just like the register() method, fd can be an integer or an object with a fileno() method that returns an integer. Attempting to remove a file descriptor that was never registered is safely ignored.
python.library.select#select.devpoll.unregister
select.epoll(sizehint=-1, flags=0) (Only supported on Linux 2.5.44 and newer.) Return an edge polling object, which can be used as Edge or Level Triggered interface for I/O events. sizehint informs epoll about the expected number of events to be registered. It must be positive, or -1 to use the default. It is only used on older systems where epoll_create1() is not available; otherwise it has no effect (though its value is still checked). flags is deprecated and completely ignored. However, when supplied, its value must be 0 or select.EPOLL_CLOEXEC, otherwise OSError is raised. See the Edge and Level Trigger Polling (epoll) Objects section below for the methods supported by epolling objects. epoll objects support the context management protocol: when used in a with statement, the new file descriptor is automatically closed at the end of the block. The new file descriptor is non-inheritable. Changed in version 3.3: Added the flags parameter. Changed in version 3.4: Support for the with statement was added. The new file descriptor is now non-inheritable. Deprecated since version 3.4: The flags parameter. select.EPOLL_CLOEXEC is used by default now. Use os.set_inheritable() to make the file descriptor inheritable.
python.library.select#select.epoll
epoll.close() Close the control file descriptor of the epoll object.
python.library.select#select.epoll.close
epoll.closed True if the epoll object is closed.
python.library.select#select.epoll.closed
epoll.fileno() Return the file descriptor number of the control fd.
python.library.select#select.epoll.fileno
epoll.fromfd(fd) Create an epoll object from a given file descriptor.
python.library.select#select.epoll.fromfd
epoll.modify(fd, eventmask) Modify a registered file descriptor.
python.library.select#select.epoll.modify
epoll.poll(timeout=None, maxevents=-1) Wait for events. timeout in seconds (float) Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError.
python.library.select#select.epoll.poll
epoll.register(fd[, eventmask]) Register a fd descriptor with the epoll object.
python.library.select#select.epoll.register
epoll.unregister(fd) Remove a registered file descriptor from the epoll object. Changed in version 3.9: The method no longer ignores the EBADF error.
python.library.select#select.epoll.unregister
exception select.error A deprecated alias of OSError. Changed in version 3.3: Following PEP 3151, this class was made an alias of OSError.
python.library.select#select.error
select.kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0) (Only supported on BSD.) Returns a kernel event object; see section Kevent Objects below for the methods supported by kevent objects.
python.library.select#select.kevent
kevent.data Filter specific data.
python.library.select#select.kevent.data
kevent.fflags Filter specific flags. KQ_FILTER_READ and KQ_FILTER_WRITE filter flags: Constant Meaning KQ_NOTE_LOWAT low water mark of a socket buffer KQ_FILTER_VNODE filter flags: Constant Meaning KQ_NOTE_DELETE unlink() was called KQ_NOTE_WRITE a write occurred KQ_NOTE_EXTEND the file was extended KQ_NOTE_ATTRIB an attribute was changed KQ_NOTE_LINK the link count has changed KQ_NOTE_RENAME the file was renamed KQ_NOTE_REVOKE access to the file was revoked KQ_FILTER_PROC filter flags: Constant Meaning KQ_NOTE_EXIT the process has exited KQ_NOTE_FORK the process has called fork() KQ_NOTE_EXEC the process has executed a new process KQ_NOTE_PCTRLMASK internal filter flag KQ_NOTE_PDATAMASK internal filter flag KQ_NOTE_TRACK follow a process across fork() KQ_NOTE_CHILD returned on the child process for NOTE_TRACK KQ_NOTE_TRACKERR unable to attach to a child KQ_FILTER_NETDEV filter flags (not available on Mac OS X): Constant Meaning KQ_NOTE_LINKUP link is up KQ_NOTE_LINKDOWN link is down KQ_NOTE_LINKINV link state is invalid
python.library.select#select.kevent.fflags
kevent.filter Name of the kernel filter. Constant Meaning KQ_FILTER_READ Takes a descriptor and returns whenever there is data available to read KQ_FILTER_WRITE Takes a descriptor and returns whenever there is data available to write KQ_FILTER_AIO AIO requests KQ_FILTER_VNODE Returns when one or more of the requested events watched in fflag occurs KQ_FILTER_PROC Watch for events on a process id KQ_FILTER_NETDEV Watch for events on a network device [not available on Mac OS X] KQ_FILTER_SIGNAL Returns whenever the watched signal is delivered to the process KQ_FILTER_TIMER Establishes an arbitrary timer
python.library.select#select.kevent.filter
kevent.flags Filter action. Constant Meaning KQ_EV_ADD Adds or modifies an event KQ_EV_DELETE Removes an event from the queue KQ_EV_ENABLE Permitscontrol() to returns the event KQ_EV_DISABLE Disablesevent KQ_EV_ONESHOT Removes event after first occurrence KQ_EV_CLEAR Reset the state after an event is retrieved KQ_EV_SYSFLAGS internal event KQ_EV_FLAG1 internal event KQ_EV_EOF Filter specific EOF condition KQ_EV_ERROR See return values
python.library.select#select.kevent.flags
kevent.ident Value used to identify the event. The interpretation depends on the filter but it’s usually the file descriptor. In the constructor ident can either be an int or an object with a fileno() method. kevent stores the integer internally.
python.library.select#select.kevent.ident
kevent.udata User defined value.
python.library.select#select.kevent.udata
select.kqueue() (Only supported on BSD.) Returns a kernel queue object; see section Kqueue Objects below for the methods supported by kqueue objects. The new file descriptor is non-inheritable. Changed in version 3.4: The new file descriptor is now non-inheritable.
python.library.select#select.kqueue
kqueue.close() Close the control file descriptor of the kqueue object.
python.library.select#select.kqueue.close
kqueue.closed True if the kqueue object is closed.
python.library.select#select.kqueue.closed
kqueue.control(changelist, max_events[, timeout]) → eventlist Low level interface to kevent changelist must be an iterable of kevent objects or None max_events must be 0 or a positive integer timeout in seconds (floats possible); the default is None, to wait forever Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError.
python.library.select#select.kqueue.control
kqueue.fileno() Return the file descriptor number of the control fd.
python.library.select#select.kqueue.fileno
kqueue.fromfd(fd) Create a kqueue object from a given file descriptor.
python.library.select#select.kqueue.fromfd
select.PIPE_BUF The minimum number of bytes which can be written without blocking to a pipe when the pipe has been reported as ready for writing by select(), poll() or another interface in this module. This doesn’t apply to other kind of file-like objects such as sockets. This value is guaranteed by POSIX to be at least 512. Availability: Unix New in version 3.2.
python.library.select#select.PIPE_BUF
select.poll() (Not supported by all operating systems.) Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events; see section Polling Objects below for the methods supported by polling objects.
python.library.select#select.poll
poll.modify(fd, eventmask) Modifies an already registered fd. This has the same effect as register(fd, eventmask). Attempting to modify a file descriptor that was never registered causes an OSError exception with errno ENOENT to be raised.
python.library.select#select.poll.modify
poll.poll([timeout]) Polls the set of registered file descriptors, and returns a possibly-empty list containing (fd, event) 2-tuples for the descriptors that have events or errors to report. fd is the file descriptor, and event is a bitmask with bits set for the reported events for that descriptor — POLLIN for waiting input, POLLOUT to indicate that the descriptor can be written to, and so forth. An empty list indicates that the call timed out and no file descriptors had any events to report. If timeout is given, it specifies the length of time in milliseconds which the system will wait for events before returning. If timeout is omitted, negative, or None, the call will block until there is an event for this poll object. Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError.
python.library.select#select.poll.poll
poll.register(fd[, eventmask]) Register a file descriptor with the polling object. Future calls to the poll() method will then check whether the file descriptor has any pending I/O events. fd can be either an integer, or an object with a fileno() method that returns an integer. File objects implement fileno(), so they can also be used as the argument. eventmask is an optional bitmask describing the type of events you want to check for, and can be a combination of the constants POLLIN, POLLPRI, and POLLOUT, described in the table below. If not specified, the default value used will check for all 3 types of events. Constant Meaning POLLIN There is data to read POLLPRI There is urgent data to read POLLOUT Ready for output: writing will not block POLLERR Error condition of some sort POLLHUP Hung up POLLRDHUP Stream socket peer closed connection, or shut down writing half of connection POLLNVAL Invalid request: descriptor not open Registering a file descriptor that’s already registered is not an error, and has the same effect as registering the descriptor exactly once.
python.library.select#select.poll.register
poll.unregister(fd) Remove a file descriptor being tracked by a polling object. Just like the register() method, fd can be an integer or an object with a fileno() method that returns an integer. Attempting to remove a file descriptor that was never registered causes a KeyError exception to be raised.
python.library.select#select.poll.unregister
select.select(rlist, wlist, xlist[, timeout]) This is a straightforward interface to the Unix select() system call. The first three arguments are iterables of ‘waitable objects’: either integers representing file descriptors or objects with a parameterless method named fileno() returning such an integer: rlist: wait until ready for reading wlist: wait until ready for writing xlist: wait for an “exceptional condition” (see the manual page for what your system considers such a condition) Empty iterables are allowed, but acceptance of three empty iterables is platform-dependent. (It is known to work on Unix but not on Windows.) The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks. The return value is a triple of lists of objects that are ready: subsets of the first three arguments. When the time-out is reached without a file descriptor becoming ready, three empty lists are returned. Among the acceptable object types in the iterables are Python file objects (e.g. sys.stdin, or objects returned by open() or os.popen()), socket objects returned by socket.socket(). You may also define a wrapper class yourself, as long as it has an appropriate fileno() method (that really returns a file descriptor, not just a random integer). Note File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock. Changed in version 3.5: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError.
python.library.select#select.select
selectors — High-level I/O multiplexing New in version 3.4. Source code: Lib/selectors.py Introduction This module allows high-level and efficient I/O multiplexing, built upon the select module primitives. Users are encouraged to use this module instead, unless they want precise control over the OS-level primitives used. It defines a BaseSelector abstract base class, along with several concrete implementations (KqueueSelector, EpollSelector…), that can be used to wait for I/O readiness notification on multiple file objects. In the following, “file object” refers to any object with a fileno() method, or a raw file descriptor. See file object. DefaultSelector is an alias to the most efficient implementation available on the current platform: this should be the default choice for most users. Note The type of file objects supported depends on the platform: on Windows, sockets are supported, but not pipes, whereas on Unix, both are supported (some other types may be supported as well, such as fifos or special file devices). See also select Low-level I/O multiplexing module. Classes Classes hierarchy: BaseSelector +-- SelectSelector +-- PollSelector +-- EpollSelector +-- DevpollSelector +-- KqueueSelector In the following, events is a bitwise mask indicating which I/O events should be waited for on a given file object. It can be a combination of the modules constants below: Constant Meaning EVENT_READ Available for read EVENT_WRITE Available for write class selectors.SelectorKey A SelectorKey is a namedtuple used to associate a file object to its underlying file descriptor, selected event mask and attached data. It is returned by several BaseSelector methods. fileobj File object registered. fd Underlying file descriptor. events Events that must be waited for on this file object. data Optional opaque data associated to this file object: for example, this could be used to store a per-client session ID. class selectors.BaseSelector A BaseSelector is used to wait for I/O event readiness on multiple file objects. It supports file stream registration, unregistration, and a method to wait for I/O events on those streams, with an optional timeout. It’s an abstract base class, so cannot be instantiated. Use DefaultSelector instead, or one of SelectSelector, KqueueSelector etc. if you want to specifically use an implementation, and your platform supports it. BaseSelector and its concrete implementations support the context manager protocol. abstractmethod register(fileobj, events, data=None) Register a file object for selection, monitoring it for I/O events. fileobj is the file object to monitor. It may either be an integer file descriptor or an object with a fileno() method. events is a bitwise mask of events to monitor. data is an opaque object. This returns a new SelectorKey instance, or raises a ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is already registered. abstractmethod unregister(fileobj) Unregister a file object from selection, removing it from monitoring. A file object shall be unregistered prior to being closed. fileobj must be a file object previously registered. This returns the associated SelectorKey instance, or raises a KeyError if fileobj is not registered. It will raise ValueError if fileobj is invalid (e.g. it has no fileno() method or its fileno() method has an invalid return value). modify(fileobj, events, data=None) Change a registered file object’s monitored events or attached data. This is equivalent to BaseSelector.unregister(fileobj)() followed by BaseSelector.register(fileobj, events, data)(), except that it can be implemented more efficiently. This returns a new SelectorKey instance, or raises a ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is not registered. abstractmethod select(timeout=None) Wait until some registered file objects become ready, or the timeout expires. If timeout > 0, this specifies the maximum wait time, in seconds. If timeout <= 0, the call won’t block, and will report the currently ready file objects. If timeout is None, the call will block until a monitored file object becomes ready. This returns a list of (key, events) tuples, one for each ready file object. key is the SelectorKey instance corresponding to a ready file object. events is a bitmask of events ready on this file object. Note This method can return before any file object becomes ready or the timeout has elapsed if the current process receives a signal: in this case, an empty list will be returned. Changed in version 3.5: The selector is now retried with a recomputed timeout when interrupted by a signal if the signal handler did not raise an exception (see PEP 475 for the rationale), instead of returning an empty list of events before the timeout. close() Close the selector. This must be called to make sure that any underlying resource is freed. The selector shall not be used once it has been closed. get_key(fileobj) Return the key associated with a registered file object. This returns the SelectorKey instance associated to this file object, or raises KeyError if the file object is not registered. abstractmethod get_map() Return a mapping of file objects to selector keys. This returns a Mapping instance mapping registered file objects to their associated SelectorKey instance. class selectors.DefaultSelector The default selector class, using the most efficient implementation available on the current platform. This should be the default choice for most users. class selectors.SelectSelector select.select()-based selector. class selectors.PollSelector select.poll()-based selector. class selectors.EpollSelector select.epoll()-based selector. fileno() This returns the file descriptor used by the underlying select.epoll() object. class selectors.DevpollSelector select.devpoll()-based selector. fileno() This returns the file descriptor used by the underlying select.devpoll() object. New in version 3.5. class selectors.KqueueSelector select.kqueue()-based selector. fileno() This returns the file descriptor used by the underlying select.kqueue() object. Examples Here is a simple echo server implementation: import selectors import socket sel = selectors.DefaultSelector() def accept(sock, mask): conn, addr = sock.accept() # Should be ready print('accepted', conn, 'from', addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read) def read(conn, mask): data = conn.recv(1000) # Should be ready if data: print('echoing', repr(data), 'to', conn) conn.send(data) # Hope it won't block else: print('closing', conn) sel.unregister(conn) conn.close() sock = socket.socket() sock.bind(('localhost', 1234)) sock.listen(100) sock.setblocking(False) sel.register(sock, selectors.EVENT_READ, accept) while True: events = sel.select() for key, mask in events: callback = key.data callback(key.fileobj, mask)
python.library.selectors
class selectors.BaseSelector A BaseSelector is used to wait for I/O event readiness on multiple file objects. It supports file stream registration, unregistration, and a method to wait for I/O events on those streams, with an optional timeout. It’s an abstract base class, so cannot be instantiated. Use DefaultSelector instead, or one of SelectSelector, KqueueSelector etc. if you want to specifically use an implementation, and your platform supports it. BaseSelector and its concrete implementations support the context manager protocol. abstractmethod register(fileobj, events, data=None) Register a file object for selection, monitoring it for I/O events. fileobj is the file object to monitor. It may either be an integer file descriptor or an object with a fileno() method. events is a bitwise mask of events to monitor. data is an opaque object. This returns a new SelectorKey instance, or raises a ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is already registered. abstractmethod unregister(fileobj) Unregister a file object from selection, removing it from monitoring. A file object shall be unregistered prior to being closed. fileobj must be a file object previously registered. This returns the associated SelectorKey instance, or raises a KeyError if fileobj is not registered. It will raise ValueError if fileobj is invalid (e.g. it has no fileno() method or its fileno() method has an invalid return value). modify(fileobj, events, data=None) Change a registered file object’s monitored events or attached data. This is equivalent to BaseSelector.unregister(fileobj)() followed by BaseSelector.register(fileobj, events, data)(), except that it can be implemented more efficiently. This returns a new SelectorKey instance, or raises a ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is not registered. abstractmethod select(timeout=None) Wait until some registered file objects become ready, or the timeout expires. If timeout > 0, this specifies the maximum wait time, in seconds. If timeout <= 0, the call won’t block, and will report the currently ready file objects. If timeout is None, the call will block until a monitored file object becomes ready. This returns a list of (key, events) tuples, one for each ready file object. key is the SelectorKey instance corresponding to a ready file object. events is a bitmask of events ready on this file object. Note This method can return before any file object becomes ready or the timeout has elapsed if the current process receives a signal: in this case, an empty list will be returned. Changed in version 3.5: The selector is now retried with a recomputed timeout when interrupted by a signal if the signal handler did not raise an exception (see PEP 475 for the rationale), instead of returning an empty list of events before the timeout. close() Close the selector. This must be called to make sure that any underlying resource is freed. The selector shall not be used once it has been closed. get_key(fileobj) Return the key associated with a registered file object. This returns the SelectorKey instance associated to this file object, or raises KeyError if the file object is not registered. abstractmethod get_map() Return a mapping of file objects to selector keys. This returns a Mapping instance mapping registered file objects to their associated SelectorKey instance.
python.library.selectors#selectors.BaseSelector
close() Close the selector. This must be called to make sure that any underlying resource is freed. The selector shall not be used once it has been closed.
python.library.selectors#selectors.BaseSelector.close
get_key(fileobj) Return the key associated with a registered file object. This returns the SelectorKey instance associated to this file object, or raises KeyError if the file object is not registered.
python.library.selectors#selectors.BaseSelector.get_key
abstractmethod get_map() Return a mapping of file objects to selector keys. This returns a Mapping instance mapping registered file objects to their associated SelectorKey instance.
python.library.selectors#selectors.BaseSelector.get_map
modify(fileobj, events, data=None) Change a registered file object’s monitored events or attached data. This is equivalent to BaseSelector.unregister(fileobj)() followed by BaseSelector.register(fileobj, events, data)(), except that it can be implemented more efficiently. This returns a new SelectorKey instance, or raises a ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is not registered.
python.library.selectors#selectors.BaseSelector.modify
abstractmethod register(fileobj, events, data=None) Register a file object for selection, monitoring it for I/O events. fileobj is the file object to monitor. It may either be an integer file descriptor or an object with a fileno() method. events is a bitwise mask of events to monitor. data is an opaque object. This returns a new SelectorKey instance, or raises a ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is already registered.
python.library.selectors#selectors.BaseSelector.register
abstractmethod select(timeout=None) Wait until some registered file objects become ready, or the timeout expires. If timeout > 0, this specifies the maximum wait time, in seconds. If timeout <= 0, the call won’t block, and will report the currently ready file objects. If timeout is None, the call will block until a monitored file object becomes ready. This returns a list of (key, events) tuples, one for each ready file object. key is the SelectorKey instance corresponding to a ready file object. events is a bitmask of events ready on this file object. Note This method can return before any file object becomes ready or the timeout has elapsed if the current process receives a signal: in this case, an empty list will be returned. Changed in version 3.5: The selector is now retried with a recomputed timeout when interrupted by a signal if the signal handler did not raise an exception (see PEP 475 for the rationale), instead of returning an empty list of events before the timeout.
python.library.selectors#selectors.BaseSelector.select
abstractmethod unregister(fileobj) Unregister a file object from selection, removing it from monitoring. A file object shall be unregistered prior to being closed. fileobj must be a file object previously registered. This returns the associated SelectorKey instance, or raises a KeyError if fileobj is not registered. It will raise ValueError if fileobj is invalid (e.g. it has no fileno() method or its fileno() method has an invalid return value).
python.library.selectors#selectors.BaseSelector.unregister
class selectors.DefaultSelector The default selector class, using the most efficient implementation available on the current platform. This should be the default choice for most users.
python.library.selectors#selectors.DefaultSelector
class selectors.DevpollSelector select.devpoll()-based selector. fileno() This returns the file descriptor used by the underlying select.devpoll() object. New in version 3.5.
python.library.selectors#selectors.DevpollSelector
fileno() This returns the file descriptor used by the underlying select.devpoll() object.
python.library.selectors#selectors.DevpollSelector.fileno
class selectors.EpollSelector select.epoll()-based selector. fileno() This returns the file descriptor used by the underlying select.epoll() object.
python.library.selectors#selectors.EpollSelector
fileno() This returns the file descriptor used by the underlying select.epoll() object.
python.library.selectors#selectors.EpollSelector.fileno
class selectors.KqueueSelector select.kqueue()-based selector. fileno() This returns the file descriptor used by the underlying select.kqueue() object.
python.library.selectors#selectors.KqueueSelector
fileno() This returns the file descriptor used by the underlying select.kqueue() object.
python.library.selectors#selectors.KqueueSelector.fileno
class selectors.PollSelector select.poll()-based selector.
python.library.selectors#selectors.PollSelector
class selectors.SelectorKey A SelectorKey is a namedtuple used to associate a file object to its underlying file descriptor, selected event mask and attached data. It is returned by several BaseSelector methods. fileobj File object registered. fd Underlying file descriptor. events Events that must be waited for on this file object. data Optional opaque data associated to this file object: for example, this could be used to store a per-client session ID.
python.library.selectors#selectors.SelectorKey
data Optional opaque data associated to this file object: for example, this could be used to store a per-client session ID.
python.library.selectors#selectors.SelectorKey.data
events Events that must be waited for on this file object.
python.library.selectors#selectors.SelectorKey.events
fd Underlying file descriptor.
python.library.selectors#selectors.SelectorKey.fd
fileobj File object registered.
python.library.selectors#selectors.SelectorKey.fileobj
class selectors.SelectSelector select.select()-based selector.
python.library.selectors#selectors.SelectSelector
class set([iterable]) Return a new set object, optionally with elements taken from iterable. set is a built-in class. See set and Set Types — set, frozenset for documentation about this class. For other containers see the built-in frozenset, list, tuple, and dict classes, as well as the collections module.
python.library.functions#set
class set([iterable]) class frozenset([iterable]) Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned. Sets can be created by several means: Use a comma-separated list of elements within braces: {'jack', 'sjoerd'} Use a set comprehension: {c for c in 'abracadabra' if c not in 'abc'} Use the type constructor: set(), set('foobar'), set(['a', 'b', 'foo']) Instances of set and frozenset provide the following operations: len(s) Return the number of elements in set s (cardinality of s). x in s Test x for membership in s. x not in s Test x for non-membership in s. isdisjoint(other) Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set. issubset(other) set <= other Test whether every element in the set is in other. set < other Test whether the set is a proper subset of other, that is, set <= other and set != other. issuperset(other) set >= other Test whether every element in other is in the set. set > other Test whether the set is a proper superset of other, that is, set >= other and set != other. union(*others) set | other | ... Return a new set with elements from the set and all others. intersection(*others) set & other & ... Return a new set with elements common to the set and all others. difference(*others) set - other - ... Return a new set with elements in the set that are not in the others. symmetric_difference(other) set ^ other Return a new set with elements in either the set or other but not both. copy() Return a shallow copy of the set. Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs'). Both set and frozenset support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal). Instances of set are compared to instances of frozenset based on their members. For example, set('abc') == frozenset('abc') returns True and so does set('abc') in set([frozenset('abc')]). The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return False: a<b, a==b, or a>b. Since sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets. Set elements, like dictionary keys, must be hashable. Binary operations that mix set instances with frozenset return the type of the first operand. For example: frozenset('ab') | set('bc') returns an instance of frozenset. The following table lists operations available for set that do not apply to immutable instances of frozenset: update(*others) set |= other | ... Update the set, adding elements from all others. intersection_update(*others) set &= other & ... Update the set, keeping only elements found in it and all others. difference_update(*others) set -= other | ... Update the set, removing elements found in others. symmetric_difference_update(other) set ^= other Update the set, keeping only elements found in either set, but not in both. add(elem) Add element elem to the set. remove(elem) Remove element elem from the set. Raises KeyError if elem is not contained in the set. discard(elem) Remove element elem from the set if it is present. pop() Remove and return an arbitrary element from the set. Raises KeyError if the set is empty. clear() Remove all elements from the set. Note, the non-operator versions of the update(), intersection_update(), difference_update(), and symmetric_difference_update() methods will accept any iterable as an argument. Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem.
python.library.stdtypes#set
setattr(object, name, value) This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.
python.library.functions#setattr
shelve — Python object persistence Source code: Lib/shelve.py A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings. shelve.open(filename, flag='c', protocol=None, writeback=False) Open a persistent dictionary. The filename specified is the base filename for the underlying database. As a side-effect, an extension may be added to the filename and more than one file may be created. By default, the underlying database file is opened for reading and writing. The optional flag parameter has the same interpretation as the flag parameter of dbm.open(). By default, version 3 pickles are used to serialize values. The version of the pickle protocol can be specified with the protocol parameter. Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated). Note Do not rely on the shelf being closed automatically; always call close() explicitly when you don’t need it any more, or use shelve.open() as a context manager: with shelve.open('spam') as db: db['eggs'] = 'eggs' Warning Because the shelve module is backed by pickle, it is insecure to load a shelf from an untrusted source. Like with pickle, loading a shelf can execute arbitrary code. Shelf objects support all methods supported by dictionaries. This eases the transition from dictionary based scripts to those requiring persistent storage. Two additional methods are supported: Shelf.sync() Write back all entries in the cache if the shelf was opened with writeback set to True. Also empty the cache and synchronize the persistent dictionary on disk, if feasible. This is called automatically when the shelf is closed with close(). Shelf.close() Synchronize and close the persistent dict object. Operations on a closed shelf will fail with a ValueError. See also Persistent dictionary recipe with widely supported storage formats and having the speed of native dictionaries. Restrictions The choice of which database package will be used (such as dbm.ndbm or dbm.gnu) depends on which interface is available. Therefore it is not safe to open the database directly using dbm. The database is also (unfortunately) subject to the limitations of dbm, if it is used — this means that (the pickled representation of) the objects stored in the database should be fairly small, and in rare cases key collisions may cause the database to refuse updates. The shelve module does not support concurrent read/write access to shelved objects. (Multiple simultaneous read accesses are safe.) When a program has a shelf open for writing, no other program should have it open for reading or writing. Unix file locking can be used to solve this, but this differs across Unix versions and requires knowledge about the database implementation used. class shelve.Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8') A subclass of collections.abc.MutableMapping which stores pickled values in the dict object. By default, version 3 pickles are used to serialize values. The version of the pickle protocol can be specified with the protocol parameter. See the pickle documentation for a discussion of the pickle protocols. If the writeback parameter is True, the object will hold a cache of all entries accessed and write them back to the dict at sync and close times. This allows natural operations on mutable entries, but can consume much more memory and make sync and close take a long time. The keyencoding parameter is the encoding used to encode keys before they are used with the underlying dict. A Shelf object can also be used as a context manager, in which case it will be automatically closed when the with block ends. Changed in version 3.2: Added the keyencoding parameter; previously, keys were always encoded in UTF-8. Changed in version 3.4: Added context manager support. class shelve.BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8') A subclass of Shelf which exposes first(), next(), previous(), last() and set_location() which are available in the third-party bsddb module from pybsddb but not in other database modules. The dict object passed to the constructor must support those methods. This is generally accomplished by calling one of bsddb.hashopen(), bsddb.btopen() or bsddb.rnopen(). The optional protocol, writeback, and keyencoding parameters have the same interpretation as for the Shelf class. class shelve.DbfilenameShelf(filename, flag='c', protocol=None, writeback=False) A subclass of Shelf which accepts a filename instead of a dict-like object. The underlying file will be opened using dbm.open(). By default, the file will be created and opened for both read and write. The optional flag parameter has the same interpretation as for the open() function. The optional protocol and writeback parameters have the same interpretation as for the Shelf class. Example To summarize the interface (key is a string, data is an arbitrary object): import shelve d = shelve.open(filename) # open -- file may get suffix added by low-level # library d[key] = data # store data at key (overwrites old data if # using an existing key) data = d[key] # retrieve a COPY of data at key (raise KeyError # if no such key) del d[key] # delete data stored at key (raises KeyError # if no such key) flag = key in d # true if the key exists klist = list(d.keys()) # a list of all existing keys (slow!) # as d was opened WITHOUT writeback=True, beware: d['xx'] = [0, 1, 2] # this works as expected, but... d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]! # having opened d without writeback=True, you need to code carefully: temp = d['xx'] # extracts the copy temp.append(5) # mutates the copy d['xx'] = temp # stores the copy right back, to persist it # or, d=shelve.open(filename,writeback=True) would let you just code # d['xx'].append(5) and have it work as expected, BUT it would also # consume more memory and make the d.close() operation slower. d.close() # close it See also Module dbm Generic interface to dbm-style databases. Module pickle Object serialization used by shelve.
python.library.shelve
class shelve.BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8') A subclass of Shelf which exposes first(), next(), previous(), last() and set_location() which are available in the third-party bsddb module from pybsddb but not in other database modules. The dict object passed to the constructor must support those methods. This is generally accomplished by calling one of bsddb.hashopen(), bsddb.btopen() or bsddb.rnopen(). The optional protocol, writeback, and keyencoding parameters have the same interpretation as for the Shelf class.
python.library.shelve#shelve.BsdDbShelf
class shelve.DbfilenameShelf(filename, flag='c', protocol=None, writeback=False) A subclass of Shelf which accepts a filename instead of a dict-like object. The underlying file will be opened using dbm.open(). By default, the file will be created and opened for both read and write. The optional flag parameter has the same interpretation as for the open() function. The optional protocol and writeback parameters have the same interpretation as for the Shelf class.
python.library.shelve#shelve.DbfilenameShelf
shelve.open(filename, flag='c', protocol=None, writeback=False) Open a persistent dictionary. The filename specified is the base filename for the underlying database. As a side-effect, an extension may be added to the filename and more than one file may be created. By default, the underlying database file is opened for reading and writing. The optional flag parameter has the same interpretation as the flag parameter of dbm.open(). By default, version 3 pickles are used to serialize values. The version of the pickle protocol can be specified with the protocol parameter. Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated). Note Do not rely on the shelf being closed automatically; always call close() explicitly when you don’t need it any more, or use shelve.open() as a context manager: with shelve.open('spam') as db: db['eggs'] = 'eggs'
python.library.shelve#shelve.open
class shelve.Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8') A subclass of collections.abc.MutableMapping which stores pickled values in the dict object. By default, version 3 pickles are used to serialize values. The version of the pickle protocol can be specified with the protocol parameter. See the pickle documentation for a discussion of the pickle protocols. If the writeback parameter is True, the object will hold a cache of all entries accessed and write them back to the dict at sync and close times. This allows natural operations on mutable entries, but can consume much more memory and make sync and close take a long time. The keyencoding parameter is the encoding used to encode keys before they are used with the underlying dict. A Shelf object can also be used as a context manager, in which case it will be automatically closed when the with block ends. Changed in version 3.2: Added the keyencoding parameter; previously, keys were always encoded in UTF-8. Changed in version 3.4: Added context manager support.
python.library.shelve#shelve.Shelf
Shelf.close() Synchronize and close the persistent dict object. Operations on a closed shelf will fail with a ValueError.
python.library.shelve#shelve.Shelf.close
Shelf.sync() Write back all entries in the cache if the shelf was opened with writeback set to True. Also empty the cache and synchronize the persistent dictionary on disk, if feasible. This is called automatically when the shelf is closed with close().
python.library.shelve#shelve.Shelf.sync
shlex — Simple lexical analysis Source code: Lib/shlex.py The shlex class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell. This will often be useful for writing minilanguages, (for example, in run control files for Python applications) or for parsing quoted strings. The shlex module defines the following functions: shlex.split(s, comments=False, posix=True) Split the string s using shell-like syntax. If comments is False (the default), the parsing of comments in the given string will be disabled (setting the commenters attribute of the shlex instance to the empty string). This function operates in POSIX mode by default, but uses non-POSIX mode if the posix argument is false. Note Since the split() function instantiates a shlex instance, passing None for s will read the string to split from standard input. Deprecated since version 3.9: Passing None for s will raise an exception in future Python versions. shlex.join(split_command) Concatenate the tokens of the list split_command and return a string. This function is the inverse of split(). >>> from shlex import join >>> print(join(['echo', '-n', 'Multiple words'])) echo -n 'Multiple words' The returned value is shell-escaped to protect against injection vulnerabilities (see quote()). New in version 3.8. shlex.quote(s) Return a shell-escaped version of the string s. The returned value is a string that can safely be used as one token in a shell command line, for cases where you cannot use a list. This idiom would be unsafe: >>> filename = 'somefile; rm -rf ~' >>> command = 'ls -l {}'.format(filename) >>> print(command) # executed by a shell: boom! ls -l somefile; rm -rf ~ quote() lets you plug the security hole: >>> from shlex import quote >>> command = 'ls -l {}'.format(quote(filename)) >>> print(command) ls -l 'somefile; rm -rf ~' >>> remote_command = 'ssh home {}'.format(quote(command)) >>> print(remote_command) ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"'' The quoting is compatible with UNIX shells and with split(): >>> from shlex import split >>> remote_command = split(remote_command) >>> remote_command ['ssh', 'home', "ls -l 'somefile; rm -rf ~'"] >>> command = split(remote_command[-1]) >>> command ['ls', '-l', 'somefile; rm -rf ~'] New in version 3.3. The shlex module defines the following class: class shlex.shlex(instream=None, infile=None, posix=False, punctuation_chars=False) A shlex instance or subclass instance is a lexical analyzer object. The initialization argument, if present, specifies where to read characters from. It must be a file-/stream-like object with read() and readline() methods, or a string. If no argument is given, input will be taken from sys.stdin. The second optional argument is a filename string, which sets the initial value of the infile attribute. If the instream argument is omitted or equal to sys.stdin, this second argument defaults to “stdin”. The posix argument defines the operational mode: when posix is not true (default), the shlex instance will operate in compatibility mode. When operating in POSIX mode, shlex will try to be as close as possible to the POSIX shell parsing rules. The punctuation_chars argument provides a way to make the behaviour even closer to how real shells parse. This can take a number of values: the default value, False, preserves the behaviour seen under Python 3.5 and earlier. If set to True, then parsing of the characters ();<>|& is changed: any run of these characters (considered punctuation characters) is returned as a single token. If set to a non-empty string of characters, those characters will be used as the punctuation characters. Any characters in the wordchars attribute that appear in punctuation_chars will be removed from wordchars. See Improved Compatibility with Shells for more information. punctuation_chars can be set only upon shlex instance creation and can’t be modified later. Changed in version 3.6: The punctuation_chars parameter was added. See also Module configparser Parser for configuration files similar to the Windows .ini files. shlex Objects A shlex instance has the following methods: shlex.get_token() Return a token. If tokens have been stacked using push_token(), pop a token off the stack. Otherwise, read one from the input stream. If reading encounters an immediate end-of-file, eof is returned (the empty string ('') in non-POSIX mode, and None in POSIX mode). shlex.push_token(str) Push the argument onto the token stack. shlex.read_token() Read a raw token. Ignore the pushback stack, and do not interpret source requests. (This is not ordinarily a useful entry point, and is documented here only for the sake of completeness.) shlex.sourcehook(filename) When shlex detects a source request (see source below) this method is given the following token as argument, and expected to return a tuple consisting of a filename and an open file-like object. Normally, this method first strips any quotes off the argument. If the result is an absolute pathname, or there was no previous source request in effect, or the previous source was a stream (such as sys.stdin), the result is left alone. Otherwise, if the result is a relative pathname, the directory part of the name of the file immediately before it on the source inclusion stack is prepended (this behavior is like the way the C preprocessor handles #include "file.h"). The result of the manipulations is treated as a filename, and returned as the first component of the tuple, with open() called on it to yield the second component. (Note: this is the reverse of the order of arguments in instance initialization!) This hook is exposed so that you can use it to implement directory search paths, addition of file extensions, and other namespace hacks. There is no corresponding ‘close’ hook, but a shlex instance will call the close() method of the sourced input stream when it returns EOF. For more explicit control of source stacking, use the push_source() and pop_source() methods. shlex.push_source(newstream, newfile=None) Push an input source stream onto the input stack. If the filename argument is specified it will later be available for use in error messages. This is the same method used internally by the sourcehook() method. shlex.pop_source() Pop the last-pushed input source from the input stack. This is the same method used internally when the lexer reaches EOF on a stacked input stream. shlex.error_leader(infile=None, lineno=None) This method generates an error message leader in the format of a Unix C compiler error label; the format is '"%s", line %d: ', where the %s is replaced with the name of the current source file and the %d with the current input line number (the optional arguments can be used to override these). This convenience is provided to encourage shlex users to generate error messages in the standard, parseable format understood by Emacs and other Unix tools. Instances of shlex subclasses have some public instance variables which either control lexical analysis or can be used for debugging: shlex.commenters The string of characters that are recognized as comment beginners. All characters from the comment beginner to end of line are ignored. Includes just '#' by default. shlex.wordchars The string of characters that will accumulate into multi-character tokens. By default, includes all ASCII alphanumerics and underscore. In POSIX mode, the accented characters in the Latin-1 set are also included. If punctuation_chars is not empty, the characters ~-./*?=, which can appear in filename specifications and command line parameters, will also be included in this attribute, and any characters which appear in punctuation_chars will be removed from wordchars if they are present there. If whitespace_split is set to True, this will have no effect. shlex.whitespace Characters that will be considered whitespace and skipped. Whitespace bounds tokens. By default, includes space, tab, linefeed and carriage-return. shlex.escape Characters that will be considered as escape. This will be only used in POSIX mode, and includes just '\' by default. shlex.quotes Characters that will be considered string quotes. The token accumulates until the same quote is encountered again (thus, different quote types protect each other as in the shell.) By default, includes ASCII single and double quotes. shlex.escapedquotes Characters in quotes that will interpret escape characters defined in escape. This is only used in POSIX mode, and includes just '"' by default. shlex.whitespace_split If True, tokens will only be split in whitespaces. This is useful, for example, for parsing command lines with shlex, getting tokens in a similar way to shell arguments. When used in combination with punctuation_chars, tokens will be split on whitespace in addition to those characters. Changed in version 3.8: The punctuation_chars attribute was made compatible with the whitespace_split attribute. shlex.infile The name of the current input file, as initially set at class instantiation time or stacked by later source requests. It may be useful to examine this when constructing error messages. shlex.instream The input stream from which this shlex instance is reading characters. shlex.source This attribute is None by default. If you assign a string to it, that string will be recognized as a lexical-level inclusion request similar to the source keyword in various shells. That is, the immediately following token will be opened as a filename and input will be taken from that stream until EOF, at which point the close() method of that stream will be called and the input source will again become the original input stream. Source requests may be stacked any number of levels deep. shlex.debug If this attribute is numeric and 1 or more, a shlex instance will print verbose progress output on its behavior. If you need to use this, you can read the module source code to learn the details. shlex.lineno Source line number (count of newlines seen so far plus one). shlex.token The token buffer. It may be useful to examine this when catching exceptions. shlex.eof Token used to determine end of file. This will be set to the empty string (''), in non-POSIX mode, and to None in POSIX mode. shlex.punctuation_chars A read-only property. Characters that will be considered punctuation. Runs of punctuation characters will be returned as a single token. However, note that no semantic validity checking will be performed: for example, ‘>>>’ could be returned as a token, even though it may not be recognised as such by shells. New in version 3.6. Parsing Rules When operating in non-POSIX mode, shlex will try to obey to the following rules. Quote characters are not recognized within words (Do"Not"Separate is parsed as the single word Do"Not"Separate); Escape characters are not recognized; Enclosing characters in quotes preserve the literal value of all characters within the quotes; Closing quotes separate words ("Do"Separate is parsed as "Do" and Separate); If whitespace_split is False, any character not declared to be a word character, whitespace, or a quote will be returned as a single-character token. If it is True, shlex will only split words in whitespaces; EOF is signaled with an empty string (''); It’s not possible to parse empty strings, even if quoted. When operating in POSIX mode, shlex will try to obey to the following parsing rules. Quotes are stripped out, and do not separate words ("Do"Not"Separate" is parsed as the single word DoNotSeparate); Non-quoted escape characters (e.g. '\') preserve the literal value of the next character that follows; Enclosing characters in quotes which are not part of escapedquotes (e.g. "'") preserve the literal value of all characters within the quotes; Enclosing characters in quotes which are part of escapedquotes (e.g. '"') preserves the literal value of all characters within the quotes, with the exception of the characters mentioned in escape. The escape characters retain its special meaning only when followed by the quote in use, or the escape character itself. Otherwise the escape character will be considered a normal character. EOF is signaled with a None value; Quoted empty strings ('') are allowed. Improved Compatibility with Shells New in version 3.6. The shlex class provides compatibility with the parsing performed by common Unix shells like bash, dash, and sh. To take advantage of this compatibility, specify the punctuation_chars argument in the constructor. This defaults to False, which preserves pre-3.6 behaviour. However, if it is set to True, then parsing of the characters ();<>|& is changed: any run of these characters is returned as a single token. While this is short of a full parser for shells (which would be out of scope for the standard library, given the multiplicity of shells out there), it does allow you to perform processing of command lines more easily than you could otherwise. To illustrate, you can see the difference in the following snippet: >>> import shlex >>> text = "a && b; c && d || e; f >'abc'; (def \"ghi\")" >>> s = shlex.shlex(text, posix=True) >>> s.whitespace_split = True >>> list(s) ['a', '&&', 'b;', 'c', '&&', 'd', '||', 'e;', 'f', '>abc;', '(def', 'ghi)'] >>> s = shlex.shlex(text, posix=True, punctuation_chars=True) >>> s.whitespace_split = True >>> list(s) ['a', '&&', 'b', ';', 'c', '&&', 'd', '||', 'e', ';', 'f', '>', 'abc', ';', '(', 'def', 'ghi', ')'] Of course, tokens will be returned which are not valid for shells, and you’ll need to implement your own error checks on the returned tokens. Instead of passing True as the value for the punctuation_chars parameter, you can pass a string with specific characters, which will be used to determine which characters constitute punctuation. For example: >>> import shlex >>> s = shlex.shlex("a && b || c", punctuation_chars="|") >>> list(s) ['a', '&', '&', 'b', '||', 'c'] Note When punctuation_chars is specified, the wordchars attribute is augmented with the characters ~-./*?=. That is because these characters can appear in file names (including wildcards) and command-line arguments (e.g. --color=auto). Hence: >>> import shlex >>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?', ... punctuation_chars=True) >>> list(s) ['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?'] However, to match the shell as closely as possible, it is recommended to always use posix and whitespace_split when using punctuation_chars, which will negate wordchars entirely. For best effect, punctuation_chars should be set in conjunction with posix=True. (Note that posix=False is the default for shlex.)
python.library.shlex
shlex.join(split_command) Concatenate the tokens of the list split_command and return a string. This function is the inverse of split(). >>> from shlex import join >>> print(join(['echo', '-n', 'Multiple words'])) echo -n 'Multiple words' The returned value is shell-escaped to protect against injection vulnerabilities (see quote()). New in version 3.8.
python.library.shlex#shlex.join