doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
plistlib.loads(data, *, fmt=None, dict_type=dict) Load a plist from a bytes object. See load() for an explanation of the keyword arguments. New in version 3.4.
python.library.plistlib#plistlib.loads
class plistlib.UID(data) Wraps an int. This is used when reading or writing NSKeyedArchiver encoded data, which contains UID (see PList manual). It has one attribute, data, which can be used to retrieve the int value of the UID. data must be in the range 0 <= data < 2**64. New in version 3.8.
python.library.plistlib#plistlib.UID
Policies An event loop policy is a global per-process object that controls the management of the event loop. Each event loop has a default policy, which can be changed and customized using the policy API. A policy defines the notion of context and manages a separate event loop per context. The default policy defines context to be the current thread. By using a custom event loop policy, the behavior of get_event_loop(), set_event_loop(), and new_event_loop() functions can be customized. Policy objects should implement the APIs defined in the AbstractEventLoopPolicy abstract base class. Getting and Setting the Policy The following functions can be used to get and set the policy for the current process: asyncio.get_event_loop_policy() Return the current process-wide policy. asyncio.set_event_loop_policy(policy) Set the current process-wide policy to policy. If policy is set to None, the default policy is restored. Policy Objects The abstract event loop policy base class is defined as follows: class asyncio.AbstractEventLoopPolicy An abstract base class for asyncio policies. get_event_loop() Get the event loop for the current context. Return an event loop object implementing the AbstractEventLoop interface. This method should never return None. Changed in version 3.6. set_event_loop(loop) Set the event loop for the current context to loop. new_event_loop() Create and return a new event loop object. This method should never return None. get_child_watcher() Get a child process watcher object. Return a watcher object implementing the AbstractChildWatcher interface. This function is Unix specific. set_child_watcher(watcher) Set the current child process watcher to watcher. This function is Unix specific. asyncio ships with the following built-in policies: class asyncio.DefaultEventLoopPolicy The default asyncio policy. Uses SelectorEventLoop on Unix and ProactorEventLoop on Windows. There is no need to install the default policy manually. asyncio is configured to use the default policy automatically. Changed in version 3.8: On Windows, ProactorEventLoop is now used by default. class asyncio.WindowsSelectorEventLoopPolicy An alternative event loop policy that uses the SelectorEventLoop event loop implementation. Availability: Windows. class asyncio.WindowsProactorEventLoopPolicy An alternative event loop policy that uses the ProactorEventLoop event loop implementation. Availability: Windows. Process Watchers A process watcher allows customization of how an event loop monitors child processes on Unix. Specifically, the event loop needs to know when a child process has exited. In asyncio, child processes are created with create_subprocess_exec() and loop.subprocess_exec() functions. asyncio defines the AbstractChildWatcher abstract base class, which child watchers should implement, and has four different implementations: ThreadedChildWatcher (configured to be used by default), MultiLoopChildWatcher, SafeChildWatcher, and FastChildWatcher. See also the Subprocess and Threads section. The following two functions can be used to customize the child process watcher implementation used by the asyncio event loop: asyncio.get_child_watcher() Return the current child watcher for the current policy. asyncio.set_child_watcher(watcher) Set the current child watcher to watcher for the current policy. watcher must implement methods defined in the AbstractChildWatcher base class. Note Third-party event loops implementations might not support custom child watchers. For such event loops, using set_child_watcher() might be prohibited or have no effect. class asyncio.AbstractChildWatcher add_child_handler(pid, callback, *args) Register a new child handler. Arrange for callback(pid, returncode, *args) to be called when a process with PID equal to pid terminates. Specifying another callback for the same process replaces the previous handler. The callback callable must be thread-safe. remove_child_handler(pid) Removes the handler for process with PID equal to pid. The function returns True if the handler was successfully removed, False if there was nothing to remove. attach_loop(loop) Attach the watcher to an event loop. If the watcher was previously attached to an event loop, then it is first detached before attaching to the new loop. Note: loop may be None. is_active() Return True if the watcher is ready to use. Spawning a subprocess with inactive current child watcher raises RuntimeError. New in version 3.8. close() Close the watcher. This method has to be called to ensure that underlying resources are cleaned-up. class asyncio.ThreadedChildWatcher This implementation starts a new waiting thread for every subprocess spawn. It works reliably even when the asyncio event loop is run in a non-main OS thread. There is no noticeable overhead when handling a big number of children (O(1) each time a child terminates), but starting a thread per process requires extra memory. This watcher is used by default. New in version 3.8. class asyncio.MultiLoopChildWatcher This implementation registers a SIGCHLD signal handler on instantiation. That can break third-party code that installs a custom handler for SIGCHLD signal. The watcher avoids disrupting other code spawning processes by polling every process explicitly on a SIGCHLD signal. There is no limitation for running subprocesses from different threads once the watcher is installed. The solution is safe but it has a significant overhead when handling a big number of processes (O(n) each time a SIGCHLD is received). New in version 3.8. class asyncio.SafeChildWatcher This implementation uses active event loop from the main thread to handle SIGCHLD signal. If the main thread has no running event loop another thread cannot spawn a subprocess (RuntimeError is raised). The watcher avoids disrupting other code spawning processes by polling every process explicitly on a SIGCHLD signal. This solution is as safe as MultiLoopChildWatcher and has the same O(N) complexity but requires a running event loop in the main thread to work. class asyncio.FastChildWatcher This implementation reaps every terminated processes by calling os.waitpid(-1) directly, possibly breaking other code spawning processes and waiting for their termination. There is no noticeable overhead when handling a big number of children (O(1) each time a child terminates). This solution requires a running event loop in the main thread to work, as SafeChildWatcher. class asyncio.PidfdChildWatcher This implementation polls process file descriptors (pidfds) to await child process termination. In some respects, PidfdChildWatcher is a “Goldilocks” child watcher implementation. It doesn’t require signals or threads, doesn’t interfere with any processes launched outside the event loop, and scales linearly with the number of subprocesses launched by the event loop. The main disadvantage is that pidfds are specific to Linux, and only work on recent (5.3+) kernels. New in version 3.9. Custom Policies To implement a new event loop policy, it is recommended to subclass DefaultEventLoopPolicy and override the methods for which custom behavior is wanted, e.g.: class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy): def get_event_loop(self): """Get the event loop. This may be None or an instance of EventLoop. """ loop = super().get_event_loop() # Do something with loop ... return loop asyncio.set_event_loop_policy(MyEventLoopPolicy())
python.library.asyncio-policy
poplib — POP3 protocol client Source code: Lib/poplib.py This module defines a class, POP3, which encapsulates a connection to a POP3 server and implements the protocol as defined in RFC 1939. The POP3 class supports both the minimal and optional command sets from RFC 1939. The POP3 class also supports the STLS command introduced in RFC 2595 to enable encrypted communication on an already established connection. Additionally, this module provides a class POP3_SSL, which provides support for connecting to POP3 servers that use SSL as an underlying protocol layer. Note that POP3, though widely supported, is obsolescent. The implementation quality of POP3 servers varies widely, and too many are quite poor. If your mailserver supports IMAP, you would be better off using the imaplib.IMAP4 class, as IMAP servers tend to be better implemented. The poplib module provides two classes: class poplib.POP3(host, port=POP3_PORT[, timeout]) This class implements the actual POP3 protocol. The connection is created when the instance is initialized. If port is omitted, the standard POP3 port (110) is used. The optional timeout parameter specifies a timeout in seconds for the connection attempt (if not specified, the global default timeout setting will be used). Raises an auditing event poplib.connect with arguments self, host, port. All commands will raise an auditing event poplib.putline with arguments self and line, where line is the bytes about to be sent to the remote host. Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket. class poplib.POP3_SSL(host, port=POP3_SSL_PORT, keyfile=None, certfile=None, timeout=None, context=None) This is a subclass of POP3 that connects to the server over an SSL encrypted socket. If port is not specified, 995, the standard POP3-over-SSL port is used. timeout works as in the POP3 constructor. context is an optional ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read Security considerations for best practices. keyfile and certfile are a legacy alternative to context - they can point to PEM-formatted private key and certificate chain files, respectively, for the SSL connection. Raises an auditing event poplib.connect with arguments self, host, port. All commands will raise an auditing event poplib.putline with arguments self and line, where line is the bytes about to be sent to the remote host. Changed in version 3.2: context parameter added. Changed in version 3.4: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI). Deprecated since version 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you. Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket. One exception is defined as an attribute of the poplib module: exception poplib.error_proto Exception raised on any errors from this module (errors from socket module are not caught). The reason for the exception is passed to the constructor as a string. See also Module imaplib The standard Python IMAP module. Frequently Asked Questions About Fetchmail The FAQ for the fetchmail POP/IMAP client collects information on POP3 server variations and RFC noncompliance that may be useful if you need to write an application based on the POP protocol. POP3 Objects All POP3 commands are represented by methods of the same name, in lower-case; most return the response text sent by the server. An POP3 instance has the following methods: POP3.set_debuglevel(level) Set the instance’s debugging level. This controls the amount of debugging output printed. The default, 0, produces no debugging output. A value of 1 produces a moderate amount of debugging output, generally a single line per request. A value of 2 or higher produces the maximum amount of debugging output, logging each line sent and received on the control connection. POP3.getwelcome() Returns the greeting string sent by the POP3 server. POP3.capa() Query the server’s capabilities as specified in RFC 2449. Returns a dictionary in the form {'name': ['param'...]}. New in version 3.4. POP3.user(username) Send user command, response should indicate that a password is required. POP3.pass_(password) Send password, response includes message count and mailbox size. Note: the mailbox on the server is locked until quit() is called. POP3.apop(user, secret) Use the more secure APOP authentication to log into the POP3 server. POP3.rpop(user) Use RPOP authentication (similar to UNIX r-commands) to log into POP3 server. POP3.stat() Get mailbox status. The result is a tuple of 2 integers: (message count, mailbox size). POP3.list([which]) Request message list, result is in the form (response, ['mesg_num octets', ...], octets). If which is set, it is the message to list. POP3.retr(which) Retrieve whole message number which, and set its seen flag. Result is in form (response, ['line', ...], octets). POP3.dele(which) Flag message number which for deletion. On most servers deletions are not actually performed until QUIT (the major exception is Eudora QPOP, which deliberately violates the RFCs by doing pending deletes on any disconnect). POP3.rset() Remove any deletion marks for the mailbox. POP3.noop() Do nothing. Might be used as a keep-alive. POP3.quit() Signoff: commit changes, unlock mailbox, drop connection. POP3.top(which, howmuch) Retrieves the message header plus howmuch lines of the message after the header of message number which. Result is in form (response, ['line', ...], octets). The POP3 TOP command this method uses, unlike the RETR command, doesn’t set the message’s seen flag; unfortunately, TOP is poorly specified in the RFCs and is frequently broken in off-brand servers. Test this method by hand against the POP3 servers you will use before trusting it. POP3.uidl(which=None) Return message digest (unique id) list. If which is specified, result contains the unique id for that message in the form 'response mesgnum uid, otherwise result is list (response, ['mesgnum uid', ...], octets). POP3.utf8() Try to switch to UTF-8 mode. Returns the server response if successful, raises error_proto if not. Specified in RFC 6856. New in version 3.5. POP3.stls(context=None) Start a TLS session on the active connection as specified in RFC 2595. This is only allowed before user authentication context parameter is a ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read Security considerations for best practices. This method supports hostname checking via ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI). New in version 3.4. Instances of POP3_SSL have no additional methods. The interface of this subclass is identical to its parent. POP3 Example Here is a minimal example (without error checking) that opens a mailbox and retrieves and prints all messages: import getpass, poplib M = poplib.POP3('localhost') M.user(getpass.getuser()) M.pass_(getpass.getpass()) numMessages = len(M.list()[1]) for i in range(numMessages): for j in M.retr(i+1)[1]: print(j) At the end of the module, there is a test section that contains a more extensive example of usage.
python.library.poplib
exception poplib.error_proto Exception raised on any errors from this module (errors from socket module are not caught). The reason for the exception is passed to the constructor as a string.
python.library.poplib#poplib.error_proto
class poplib.POP3(host, port=POP3_PORT[, timeout]) This class implements the actual POP3 protocol. The connection is created when the instance is initialized. If port is omitted, the standard POP3 port (110) is used. The optional timeout parameter specifies a timeout in seconds for the connection attempt (if not specified, the global default timeout setting will be used). Raises an auditing event poplib.connect with arguments self, host, port. All commands will raise an auditing event poplib.putline with arguments self and line, where line is the bytes about to be sent to the remote host. Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket.
python.library.poplib#poplib.POP3
POP3.apop(user, secret) Use the more secure APOP authentication to log into the POP3 server.
python.library.poplib#poplib.POP3.apop
POP3.capa() Query the server’s capabilities as specified in RFC 2449. Returns a dictionary in the form {'name': ['param'...]}. New in version 3.4.
python.library.poplib#poplib.POP3.capa
POP3.dele(which) Flag message number which for deletion. On most servers deletions are not actually performed until QUIT (the major exception is Eudora QPOP, which deliberately violates the RFCs by doing pending deletes on any disconnect).
python.library.poplib#poplib.POP3.dele
POP3.getwelcome() Returns the greeting string sent by the POP3 server.
python.library.poplib#poplib.POP3.getwelcome
POP3.list([which]) Request message list, result is in the form (response, ['mesg_num octets', ...], octets). If which is set, it is the message to list.
python.library.poplib#poplib.POP3.list
POP3.noop() Do nothing. Might be used as a keep-alive.
python.library.poplib#poplib.POP3.noop
POP3.pass_(password) Send password, response includes message count and mailbox size. Note: the mailbox on the server is locked until quit() is called.
python.library.poplib#poplib.POP3.pass_
POP3.quit() Signoff: commit changes, unlock mailbox, drop connection.
python.library.poplib#poplib.POP3.quit
POP3.retr(which) Retrieve whole message number which, and set its seen flag. Result is in form (response, ['line', ...], octets).
python.library.poplib#poplib.POP3.retr
POP3.rpop(user) Use RPOP authentication (similar to UNIX r-commands) to log into POP3 server.
python.library.poplib#poplib.POP3.rpop
POP3.rset() Remove any deletion marks for the mailbox.
python.library.poplib#poplib.POP3.rset
POP3.set_debuglevel(level) Set the instance’s debugging level. This controls the amount of debugging output printed. The default, 0, produces no debugging output. A value of 1 produces a moderate amount of debugging output, generally a single line per request. A value of 2 or higher produces the maximum amount of debugging output, logging each line sent and received on the control connection.
python.library.poplib#poplib.POP3.set_debuglevel
POP3.stat() Get mailbox status. The result is a tuple of 2 integers: (message count, mailbox size).
python.library.poplib#poplib.POP3.stat
POP3.stls(context=None) Start a TLS session on the active connection as specified in RFC 2595. This is only allowed before user authentication context parameter is a ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read Security considerations for best practices. This method supports hostname checking via ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI). New in version 3.4.
python.library.poplib#poplib.POP3.stls
POP3.top(which, howmuch) Retrieves the message header plus howmuch lines of the message after the header of message number which. Result is in form (response, ['line', ...], octets). The POP3 TOP command this method uses, unlike the RETR command, doesn’t set the message’s seen flag; unfortunately, TOP is poorly specified in the RFCs and is frequently broken in off-brand servers. Test this method by hand against the POP3 servers you will use before trusting it.
python.library.poplib#poplib.POP3.top
POP3.uidl(which=None) Return message digest (unique id) list. If which is specified, result contains the unique id for that message in the form 'response mesgnum uid, otherwise result is list (response, ['mesgnum uid', ...], octets).
python.library.poplib#poplib.POP3.uidl
POP3.user(username) Send user command, response should indicate that a password is required.
python.library.poplib#poplib.POP3.user
POP3.utf8() Try to switch to UTF-8 mode. Returns the server response if successful, raises error_proto if not. Specified in RFC 6856. New in version 3.5.
python.library.poplib#poplib.POP3.utf8
class poplib.POP3_SSL(host, port=POP3_SSL_PORT, keyfile=None, certfile=None, timeout=None, context=None) This is a subclass of POP3 that connects to the server over an SSL encrypted socket. If port is not specified, 995, the standard POP3-over-SSL port is used. timeout works as in the POP3 constructor. context is an optional ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read Security considerations for best practices. keyfile and certfile are a legacy alternative to context - they can point to PEM-formatted private key and certificate chain files, respectively, for the SSL connection. Raises an auditing event poplib.connect with arguments self, host, port. All commands will raise an auditing event poplib.putline with arguments self and line, where line is the bytes about to be sent to the remote host. Changed in version 3.2: context parameter added. Changed in version 3.4: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI). Deprecated since version 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you. Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket.
python.library.poplib#poplib.POP3_SSL
posix — The most common POSIX system calls This module provides access to operating system functionality that is standardized by the C Standard and the POSIX standard (a thinly disguised Unix interface). Do not import this module directly. Instead, import the module os, which provides a portable version of this interface. On Unix, the os module provides a superset of the posix interface. On non-Unix operating systems the posix module is not available, but a subset is always available through the os interface. Once os is imported, there is no performance penalty in using it instead of posix. In addition, os provides some additional functionality, such as automatically calling putenv() when an entry in os.environ is changed. Errors are reported as exceptions; the usual exceptions are given for type errors, while errors reported by the system calls raise OSError. Large File Support Several operating systems (including AIX, HP-UX, Irix and Solaris) provide support for files that are larger than 2 GiB from a C programming model where int and long are 32-bit values. This is typically accomplished by defining the relevant size and offset types as 64-bit values. Such files are sometimes referred to as large files. Large file support is enabled in Python when the size of an off_t is larger than a long and the long long is at least as large as an off_t. It may be necessary to configure and compile Python with certain compiler flags to enable this mode. For example, it is enabled by default with recent versions of Irix, but with Solaris 2.6 and 2.7 you need to do something like: CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \ ./configure On large-file-capable Linux systems, this might work: CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" \ ./configure Notable Module Contents In addition to many functions described in the os module documentation, posix defines the following data item: posix.environ A dictionary representing the string environment at the time the interpreter was started. Keys and values are bytes on Unix and str on Windows. For example, environ[b'HOME'] (environ['HOME'] on Windows) is the pathname of your home directory, equivalent to getenv("HOME") in C. Modifying this dictionary does not affect the string environment passed on by execv(), popen() or system(); if you need to change the environment, pass environ to execve() or add variable assignments and export statements to the command string for system() or popen(). Changed in version 3.2: On Unix, keys and values are bytes. Note The os module provides an alternate implementation of environ which updates the environment on modification. Note also that updating os.environ will render this dictionary obsolete. Use of the os module version of this is recommended over direct access to the posix module.
python.library.posix
posix.environ A dictionary representing the string environment at the time the interpreter was started. Keys and values are bytes on Unix and str on Windows. For example, environ[b'HOME'] (environ['HOME'] on Windows) is the pathname of your home directory, equivalent to getenv("HOME") in C. Modifying this dictionary does not affect the string environment passed on by execv(), popen() or system(); if you need to change the environment, pass environ to execve() or add variable assignments and export statements to the command string for system() or popen(). Changed in version 3.2: On Unix, keys and values are bytes. Note The os module provides an alternate implementation of environ which updates the environment on modification. Note also that updating os.environ will render this dictionary obsolete. Use of the os module version of this is recommended over direct access to the posix module.
python.library.posix#posix.environ
pow(base, exp[, mod]) Return base to the power exp; if mod is present, return base to the power exp, modulo mod (computed more efficiently than pow(base, exp) % mod). The two-argument form pow(base, exp) is equivalent to using the power operator: base**exp. The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. For int operands base and exp, if mod is present, mod must also be of integer type and mod must be nonzero. If mod is present and exp is negative, base must be relatively prime to mod. In that case, pow(inv_base, -exp, mod) is returned, where inv_base is an inverse to base modulo mod. Here’s an example of computing an inverse for 38 modulo 97: >>> pow(38, -1, mod=97) 23 >>> 23 * 38 % 97 == 1 True Changed in version 3.8: For int operands, the three-argument form of pow now allows the second argument to be negative, permitting computation of modular inverses. Changed in version 3.8: Allow keyword arguments. Formerly, only positional arguments were supported.
python.library.functions#pow
pprint — Data pretty printer Source code: Lib/pprint.py The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets or classes are included, as well as many other objects which are not representable as Python literals. The formatted representation keeps objects on a single line if it can, and breaks them onto multiple lines if they don’t fit within the allowed width. Construct PrettyPrinter objects explicitly if you need to adjust the width constraint. Dictionaries are sorted by key before the display is computed. Changed in version 3.9: Added support for pretty-printing types.SimpleNamespace. The pprint module defines one class: class pprint.PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True) Construct a PrettyPrinter instance. This constructor understands several keyword parameters. An output stream may be set using the stream keyword; the only method used on the stream object is the file protocol’s write() method. If not specified, the PrettyPrinter adopts sys.stdout. The amount of indentation added for each recursive level is specified by indent; the default is one. Other values can cause output to look a little odd, but can make nesting easier to spot. The number of levels which may be printed is controlled by depth; if the data structure being printed is too deep, the next contained level is replaced by .... By default, there is no constraint on the depth of the objects being formatted. The desired output width is constrained using the width parameter; the default is 80 characters. If a structure cannot be formatted within the constrained width, a best effort will be made. If compact is false (the default) each item of a long sequence will be formatted on a separate line. If compact is true, as many items as will fit within the width will be formatted on each output line. If sort_dicts is true (the default), dictionaries will be formatted with their keys sorted, otherwise they will display in insertion order. Changed in version 3.4: Added the compact parameter. Changed in version 3.8: Added the sort_dicts parameter. >>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff[:]) >>> pp = pprint.PrettyPrinter(indent=4) >>> pp.pprint(stuff) [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> pp = pprint.PrettyPrinter(width=41, compact=True) >>> pp.pprint(stuff) [['spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ... ('parrot', ('fresh fruit',)))))))) >>> pp = pprint.PrettyPrinter(depth=6) >>> pp.pprint(tup) ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...))))))) The pprint module also provides several shortcut functions: pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True) Return the formatted representation of object as a string. indent, width, depth, compact and sort_dicts will be passed to the PrettyPrinter constructor as formatting parameters. Changed in version 3.4: Added the compact parameter. Changed in version 3.8: Added the sort_dicts parameter. pprint.pp(object, *args, sort_dicts=False, **kwargs) Prints the formatted representation of object followed by a newline. If sort_dicts is false (the default), dictionaries will be displayed with their keys in insertion order, otherwise the dict keys will be sorted. args and kwargs will be passed to pprint() as formatting parameters. New in version 3.8. pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True) Prints the formatted representation of object on stream, followed by a newline. If stream is None, sys.stdout is used. This may be used in the interactive interpreter instead of the print() function for inspecting values (you can even reassign print = pprint.pprint for use within a scope). indent, width, depth, compact and sort_dicts will be passed to the PrettyPrinter constructor as formatting parameters. Changed in version 3.4: Added the compact parameter. Changed in version 3.8: Added the sort_dicts parameter. >>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff) >>> pprint.pprint(stuff) [<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni'] pprint.isreadable(object) Determine if the formatted representation of object is “readable”, or can be used to reconstruct the value using eval(). This always returns False for recursive objects. >>> pprint.isreadable(stuff) False pprint.isrecursive(object) Determine if object requires a recursive representation. One more support function is also defined: pprint.saferepr(object) Return a string representation of object, protected against recursive data structures. If the representation of object exposes a recursive entry, the recursive reference will be represented as <Recursion on typename with id=number>. The representation is not otherwise formatted. >>> pprint.saferepr(stuff) "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']" PrettyPrinter Objects PrettyPrinter instances have the following methods: PrettyPrinter.pformat(object) Return the formatted representation of object. This takes into account the options passed to the PrettyPrinter constructor. PrettyPrinter.pprint(object) Print the formatted representation of object on the configured stream, followed by a newline. The following methods provide the implementations for the corresponding functions of the same names. Using these methods on an instance is slightly more efficient since new PrettyPrinter objects don’t need to be created. PrettyPrinter.isreadable(object) Determine if the formatted representation of the object is “readable,” or can be used to reconstruct the value using eval(). Note that this returns False for recursive objects. If the depth parameter of the PrettyPrinter is set and the object is deeper than allowed, this returns False. PrettyPrinter.isrecursive(object) Determine if the object requires a recursive representation. This method is provided as a hook to allow subclasses to modify the way objects are converted to strings. The default implementation uses the internals of the saferepr() implementation. PrettyPrinter.format(object, context, maxlevels, level) Returns three values: the formatted version of object as a string, a flag indicating whether the result is readable, and a flag indicating whether recursion was detected. The first argument is the object to be presented. The second is a dictionary which contains the id() of objects that are part of the current presentation context (direct and indirect containers for object that are affecting the presentation) as the keys; if an object needs to be presented which is already represented in context, the third return value should be True. Recursive calls to the format() method should add additional entries for containers to this dictionary. The third argument, maxlevels, gives the requested limit to recursion; this will be 0 if there is no requested limit. This argument should be passed unmodified to recursive calls. The fourth argument, level, gives the current level; recursive calls should be passed a value less than that of the current call. Example To demonstrate several uses of the pprint() function and its parameters, let’s fetch information about a project from PyPI: >>> import json >>> import pprint >>> from urllib.request import urlopen >>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp: ... project_info = json.load(resp)['info'] In its basic form, pprint() shows the whole object: >>> pprint.pprint(project_info) {'author': 'The Python Packaging Authority', 'author_email': 'pypa-dev@googlegroups.com', 'bugtrack_url': None, 'classifiers': ['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Build Tools'], 'description': 'A sample Python project\n' '=======================\n' '\n' 'This is the description file for the project.\n' '\n' 'The file should use UTF-8 encoding and be written using ' 'ReStructured Text. It\n' 'will be used to generate the project webpage on PyPI, and ' 'should be written for\n' 'that purpose.\n' '\n' 'Typical contents for this file would include an overview of ' 'the project, basic\n' 'usage examples, etc. Generally, including the project ' 'changelog in here is not\n' 'a good idea, although a simple "What\'s New" section for the ' 'most recent version\n' 'may be appropriate.', 'description_content_type': None, 'docs_url': None, 'download_url': 'UNKNOWN', 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1}, 'home_page': 'https://github.com/pypa/sampleproject', 'keywords': 'sample setuptools development', 'license': 'MIT', 'maintainer': None, 'maintainer_email': None, 'name': 'sampleproject', 'package_url': 'https://pypi.org/project/sampleproject/', 'platform': 'UNKNOWN', 'project_url': 'https://pypi.org/project/sampleproject/', 'project_urls': {'Download': 'UNKNOWN', 'Homepage': 'https://github.com/pypa/sampleproject'}, 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/', 'requires_dist': None, 'requires_python': None, 'summary': 'A sample Python project', 'version': '1.2.0'} The result can be limited to a certain depth (ellipsis is used for deeper contents): >>> pprint.pprint(project_info, depth=1) {'author': 'The Python Packaging Authority', 'author_email': 'pypa-dev@googlegroups.com', 'bugtrack_url': None, 'classifiers': [...], 'description': 'A sample Python project\n' '=======================\n' '\n' 'This is the description file for the project.\n' '\n' 'The file should use UTF-8 encoding and be written using ' 'ReStructured Text. It\n' 'will be used to generate the project webpage on PyPI, and ' 'should be written for\n' 'that purpose.\n' '\n' 'Typical contents for this file would include an overview of ' 'the project, basic\n' 'usage examples, etc. Generally, including the project ' 'changelog in here is not\n' 'a good idea, although a simple "What\'s New" section for the ' 'most recent version\n' 'may be appropriate.', 'description_content_type': None, 'docs_url': None, 'download_url': 'UNKNOWN', 'downloads': {...}, 'home_page': 'https://github.com/pypa/sampleproject', 'keywords': 'sample setuptools development', 'license': 'MIT', 'maintainer': None, 'maintainer_email': None, 'name': 'sampleproject', 'package_url': 'https://pypi.org/project/sampleproject/', 'platform': 'UNKNOWN', 'project_url': 'https://pypi.org/project/sampleproject/', 'project_urls': {...}, 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/', 'requires_dist': None, 'requires_python': None, 'summary': 'A sample Python project', 'version': '1.2.0'} Additionally, maximum character width can be suggested. If a long object cannot be split, the specified width will be exceeded: >>> pprint.pprint(project_info, depth=1, width=60) {'author': 'The Python Packaging Authority', 'author_email': 'pypa-dev@googlegroups.com', 'bugtrack_url': None, 'classifiers': [...], 'description': 'A sample Python project\n' '=======================\n' '\n' 'This is the description file for the ' 'project.\n' '\n' 'The file should use UTF-8 encoding and be ' 'written using ReStructured Text. It\n' 'will be used to generate the project ' 'webpage on PyPI, and should be written ' 'for\n' 'that purpose.\n' '\n' 'Typical contents for this file would ' 'include an overview of the project, ' 'basic\n' 'usage examples, etc. Generally, including ' 'the project changelog in here is not\n' 'a good idea, although a simple "What\'s ' 'New" section for the most recent version\n' 'may be appropriate.', 'description_content_type': None, 'docs_url': None, 'download_url': 'UNKNOWN', 'downloads': {...}, 'home_page': 'https://github.com/pypa/sampleproject', 'keywords': 'sample setuptools development', 'license': 'MIT', 'maintainer': None, 'maintainer_email': None, 'name': 'sampleproject', 'package_url': 'https://pypi.org/project/sampleproject/', 'platform': 'UNKNOWN', 'project_url': 'https://pypi.org/project/sampleproject/', 'project_urls': {...}, 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/', 'requires_dist': None, 'requires_python': None, 'summary': 'A sample Python project', 'version': '1.2.0'}
python.library.pprint
pprint.isreadable(object) Determine if the formatted representation of object is “readable”, or can be used to reconstruct the value using eval(). This always returns False for recursive objects. >>> pprint.isreadable(stuff) False
python.library.pprint#pprint.isreadable
pprint.isrecursive(object) Determine if object requires a recursive representation.
python.library.pprint#pprint.isrecursive
pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True) Return the formatted representation of object as a string. indent, width, depth, compact and sort_dicts will be passed to the PrettyPrinter constructor as formatting parameters. Changed in version 3.4: Added the compact parameter. Changed in version 3.8: Added the sort_dicts parameter.
python.library.pprint#pprint.pformat
pprint.pp(object, *args, sort_dicts=False, **kwargs) Prints the formatted representation of object followed by a newline. If sort_dicts is false (the default), dictionaries will be displayed with their keys in insertion order, otherwise the dict keys will be sorted. args and kwargs will be passed to pprint() as formatting parameters. New in version 3.8.
python.library.pprint#pprint.pp
pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True) Prints the formatted representation of object on stream, followed by a newline. If stream is None, sys.stdout is used. This may be used in the interactive interpreter instead of the print() function for inspecting values (you can even reassign print = pprint.pprint for use within a scope). indent, width, depth, compact and sort_dicts will be passed to the PrettyPrinter constructor as formatting parameters. Changed in version 3.4: Added the compact parameter. Changed in version 3.8: Added the sort_dicts parameter. >>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff) >>> pprint.pprint(stuff) [<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']
python.library.pprint#pprint.pprint
class pprint.PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True) Construct a PrettyPrinter instance. This constructor understands several keyword parameters. An output stream may be set using the stream keyword; the only method used on the stream object is the file protocol’s write() method. If not specified, the PrettyPrinter adopts sys.stdout. The amount of indentation added for each recursive level is specified by indent; the default is one. Other values can cause output to look a little odd, but can make nesting easier to spot. The number of levels which may be printed is controlled by depth; if the data structure being printed is too deep, the next contained level is replaced by .... By default, there is no constraint on the depth of the objects being formatted. The desired output width is constrained using the width parameter; the default is 80 characters. If a structure cannot be formatted within the constrained width, a best effort will be made. If compact is false (the default) each item of a long sequence will be formatted on a separate line. If compact is true, as many items as will fit within the width will be formatted on each output line. If sort_dicts is true (the default), dictionaries will be formatted with their keys sorted, otherwise they will display in insertion order. Changed in version 3.4: Added the compact parameter. Changed in version 3.8: Added the sort_dicts parameter. >>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff[:]) >>> pp = pprint.PrettyPrinter(indent=4) >>> pp.pprint(stuff) [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> pp = pprint.PrettyPrinter(width=41, compact=True) >>> pp.pprint(stuff) [['spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ... ('parrot', ('fresh fruit',)))))))) >>> pp = pprint.PrettyPrinter(depth=6) >>> pp.pprint(tup) ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
python.library.pprint#pprint.PrettyPrinter
PrettyPrinter.format(object, context, maxlevels, level) Returns three values: the formatted version of object as a string, a flag indicating whether the result is readable, and a flag indicating whether recursion was detected. The first argument is the object to be presented. The second is a dictionary which contains the id() of objects that are part of the current presentation context (direct and indirect containers for object that are affecting the presentation) as the keys; if an object needs to be presented which is already represented in context, the third return value should be True. Recursive calls to the format() method should add additional entries for containers to this dictionary. The third argument, maxlevels, gives the requested limit to recursion; this will be 0 if there is no requested limit. This argument should be passed unmodified to recursive calls. The fourth argument, level, gives the current level; recursive calls should be passed a value less than that of the current call.
python.library.pprint#pprint.PrettyPrinter.format
PrettyPrinter.isreadable(object) Determine if the formatted representation of the object is “readable,” or can be used to reconstruct the value using eval(). Note that this returns False for recursive objects. If the depth parameter of the PrettyPrinter is set and the object is deeper than allowed, this returns False.
python.library.pprint#pprint.PrettyPrinter.isreadable
PrettyPrinter.isrecursive(object) Determine if the object requires a recursive representation.
python.library.pprint#pprint.PrettyPrinter.isrecursive
PrettyPrinter.pformat(object) Return the formatted representation of object. This takes into account the options passed to the PrettyPrinter constructor.
python.library.pprint#pprint.PrettyPrinter.pformat
PrettyPrinter.pprint(object) Print the formatted representation of object on the configured stream, followed by a newline.
python.library.pprint#pprint.PrettyPrinter.pprint
pprint.saferepr(object) Return a string representation of object, protected against recursive data structures. If the representation of object exposes a recursive entry, the recursive reference will be represented as <Recursion on typename with id=number>. The representation is not otherwise formatted. >>> pprint.saferepr(stuff) "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
python.library.pprint#pprint.saferepr
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments. All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end. The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead. Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed. Changed in version 3.3: Added the flush keyword argument.
python.library.functions#print
exception ProcessLookupError Raised when a given process doesn’t exist. Corresponds to errno ESRCH.
python.library.exceptions#ProcessLookupError
class profile.Profile(timer=None, timeunit=0.0, subcalls=True, builtins=True) This class is normally only used if more precise control over profiling is needed than what the cProfile.run() function provides. A custom timer can be supplied for measuring how long code takes to run via the timer argument. This must be a function that returns a single number representing the current time. If the number is an integer, the timeunit specifies a multiplier that specifies the duration of each unit of time. For example, if the timer returns times measured in thousands of seconds, the time unit would be .001. Directly using the Profile class allows formatting profile results without writing the profile data to a file: import cProfile, pstats, io from pstats import SortKey pr = cProfile.Profile() pr.enable() # ... do something ... pr.disable() s = io.StringIO() sortby = SortKey.CUMULATIVE ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() print(s.getvalue()) The Profile class can also be used as a context manager (supported only in cProfile module. see Context Manager Types): import cProfile with cProfile.Profile() as pr: # ... do something ... pr.print_stats() Changed in version 3.8: Added context manager support. enable() Start collecting profiling data. Only in cProfile. disable() Stop collecting profiling data. Only in cProfile. create_stats() Stop collecting profiling data and record the results internally as the current profile. print_stats(sort=-1) Create a Stats object based on the current profile and print the results to stdout. dump_stats(filename) Write the results of the current profile to filename. run(cmd) Profile the cmd via exec(). runctx(cmd, globals, locals) Profile the cmd via exec() with the specified global and local environment. runcall(func, /, *args, **kwargs) Profile func(*args, **kwargs)
python.library.profile#profile.Profile
create_stats() Stop collecting profiling data and record the results internally as the current profile.
python.library.profile#profile.Profile.create_stats
disable() Stop collecting profiling data. Only in cProfile.
python.library.profile#profile.Profile.disable
dump_stats(filename) Write the results of the current profile to filename.
python.library.profile#profile.Profile.dump_stats
enable() Start collecting profiling data. Only in cProfile.
python.library.profile#profile.Profile.enable
print_stats(sort=-1) Create a Stats object based on the current profile and print the results to stdout.
python.library.profile#profile.Profile.print_stats
run(cmd) Profile the cmd via exec().
python.library.profile#profile.Profile.run
runcall(func, /, *args, **kwargs) Profile func(*args, **kwargs)
python.library.profile#profile.Profile.runcall
runctx(cmd, globals, locals) Profile the cmd via exec() with the specified global and local environment.
python.library.profile#profile.Profile.runctx
profile.run(command, filename=None, sort=-1) This function takes a single argument that can be passed to the exec() function, and an optional file name. In all cases this routine executes: exec(command, __main__.__dict__, __main__.__dict__) and gathers profiling statistics from the execution. If no file name is present, then this function automatically creates a Stats instance and prints a simple profiling report. If the sort value is specified, it is passed to this Stats instance to control how the results are sorted.
python.library.profile#profile.run
profile.runctx(command, globals, locals, filename=None, sort=-1) This function is similar to run(), with added arguments to supply the globals and locals dictionaries for the command string. This routine executes: exec(command, globals, locals) and gathers profiling statistics as in the run() function above.
python.library.profile#profile.runctx
class property(fget=None, fset=None, fdel=None, doc=None) Return a property attribute. fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute. A typical use is to define a managed attribute x: class C: def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") If c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter and del c.x the deleter. If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget’s docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator: class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage The @property decorator turns the voltage() method into a “getter” for a read-only attribute with the same name, and it sets the docstring for voltage to “Get the current voltage.” A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example: class C: def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (x in this case.) The returned property object also has the attributes fget, fset, and fdel corresponding to the constructor arguments. Changed in version 3.5: The docstrings of property objects are now writeable.
python.library.functions#property
class pstats.Stats(*filenames or profile, stream=sys.stdout) This class constructor creates an instance of a “statistics object” from a filename (or list of filenames) or from a Profile instance. Output will be printed to the stream specified by stream. The file selected by the above constructor must have been created by the corresponding version of profile or cProfile. To be specific, there is no file compatibility guaranteed with future versions of this profiler, and there is no compatibility with files produced by other profilers, or the same profiler run on a different operating system. If several files are provided, all the statistics for identical functions will be coalesced, so that an overall view of several processes can be considered in a single report. If additional files need to be combined with data in an existing Stats object, the add() method can be used. Instead of reading the profile data from a file, a cProfile.Profile or profile.Profile object can be used as the profile data source. Stats objects have the following methods: strip_dirs() This method for the Stats class removes all leading path information from file names. It is very useful in reducing the size of the printout to fit within (close to) 80 columns. This method modifies the object, and the stripped information is lost. After performing a strip operation, the object is considered to have its entries in a “random” order, as it was just after object initialization and loading. If strip_dirs() causes two function names to be indistinguishable (they are on the same line of the same filename, and have the same function name), then the statistics for these two entries are accumulated into a single entry. add(*filenames) This method of the Stats class accumulates additional profiling information into the current profiling object. Its arguments should refer to filenames created by the corresponding version of profile.run() or cProfile.run(). Statistics for identically named (re: file, line, name) functions are automatically accumulated into single function statistics. dump_stats(filename) Save the data loaded into the Stats object to a file named filename. The file is created if it does not exist, and is overwritten if it already exists. This is equivalent to the method of the same name on the profile.Profile and cProfile.Profile classes. sort_stats(*keys) This method modifies the Stats object by sorting it according to the supplied criteria. The argument can be either a string or a SortKey enum identifying the basis of a sort (example: 'time', 'name', SortKey.TIME or SortKey.NAME). The SortKey enums argument have advantage over the string argument in that it is more robust and less error prone. When more than one key is provided, then additional keys are used as secondary criteria when there is equality in all keys selected before them. For example, sort_stats(SortKey.NAME, SortKey.FILE) will sort all the entries according to their function name, and resolve all ties (identical function names) by sorting by file name. For the string argument, abbreviations can be used for any key names, as long as the abbreviation is unambiguous. The following are the valid string and SortKey: Valid String Arg Valid enum Arg Meaning 'calls' SortKey.CALLS call count 'cumulative' SortKey.CUMULATIVE cumulative time 'cumtime' N/A cumulative time 'file' N/A file name 'filename' SortKey.FILENAME file name 'module' N/A file name 'ncalls' N/A call count 'pcalls' SortKey.PCALLS primitive call count 'line' SortKey.LINE line number 'name' SortKey.NAME function name 'nfl' SortKey.NFL name/file/line 'stdname' SortKey.STDNAME standard name 'time' SortKey.TIME internal time 'tottime' N/A internal time Note that all sorts on statistics are in descending order (placing most time consuming items first), where as name, file, and line number searches are in ascending order (alphabetical). The subtle distinction between SortKey.NFL and SortKey.STDNAME is that the standard name is a sort of the name as printed, which means that the embedded line numbers get compared in an odd way. For example, lines 3, 20, and 40 would (if the file names were the same) appear in the string order 20, 3 and 40. In contrast, SortKey.NFL does a numeric compare of the line numbers. In fact, sort_stats(SortKey.NFL) is the same as sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE). For backward-compatibility reasons, the numeric arguments -1, 0, 1, and 2 are permitted. They are interpreted as 'stdname', 'calls', 'time', and 'cumulative' respectively. If this old style format (numeric) is used, only one sort key (the numeric key) will be used, and additional arguments will be silently ignored. New in version 3.7: Added the SortKey enum. reverse_order() This method for the Stats class reverses the ordering of the basic list within the object. Note that by default ascending vs descending order is properly selected based on the sort key of choice. print_stats(*restrictions) This method for the Stats class prints out a report as described in the profile.run() definition. The order of the printing is based on the last sort_stats() operation done on the object (subject to caveats in add() and strip_dirs()). The arguments provided (if any) can be used to limit the list down to the significant entries. Initially, the list is taken to be the complete set of profiled functions. Each restriction is either an integer (to select a count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to select a percentage of lines), or a string that will interpreted as a regular expression (to pattern match the standard name that is printed). If several restrictions are provided, then they are applied sequentially. For example: print_stats(.1, 'foo:') would first limit the printing to first 10% of list, and then only print functions that were part of filename .*foo:. In contrast, the command: print_stats('foo:', .1) would limit the list to all functions having file names .*foo:, and then proceed to only print the first 10% of them. print_callers(*restrictions) This method for the Stats class prints a list of all functions that called each function in the profiled database. The ordering is identical to that provided by print_stats(), and the definition of the restricting argument is also identical. Each caller is reported on its own line. The format differs slightly depending on the profiler that produced the stats: With profile, a number is shown in parentheses after each caller to show how many times this specific call was made. For convenience, a second non-parenthesized number repeats the cumulative time spent in the function at the right. With cProfile, each caller is preceded by three numbers: the number of times this specific call was made, and the total and cumulative times spent in the current function while it was invoked by this specific caller. print_callees(*restrictions) This method for the Stats class prints a list of all function that were called by the indicated function. Aside from this reversal of direction of calls (re: called vs was called by), the arguments and ordering are identical to the print_callers() method. get_stats_profile() This method returns an instance of StatsProfile, which contains a mapping of function names to instances of FunctionProfile. Each FunctionProfile instance holds information related to the function’s profile such as how long the function took to run, how many times it was called, etc… New in version 3.9: Added the following dataclasses: StatsProfile, FunctionProfile. Added the following function: get_stats_profile.
python.library.profile#pstats.Stats
add(*filenames) This method of the Stats class accumulates additional profiling information into the current profiling object. Its arguments should refer to filenames created by the corresponding version of profile.run() or cProfile.run(). Statistics for identically named (re: file, line, name) functions are automatically accumulated into single function statistics.
python.library.profile#pstats.Stats.add
dump_stats(filename) Save the data loaded into the Stats object to a file named filename. The file is created if it does not exist, and is overwritten if it already exists. This is equivalent to the method of the same name on the profile.Profile and cProfile.Profile classes.
python.library.profile#pstats.Stats.dump_stats
get_stats_profile() This method returns an instance of StatsProfile, which contains a mapping of function names to instances of FunctionProfile. Each FunctionProfile instance holds information related to the function’s profile such as how long the function took to run, how many times it was called, etc… New in version 3.9: Added the following dataclasses: StatsProfile, FunctionProfile. Added the following function: get_stats_profile.
python.library.profile#pstats.Stats.get_stats_profile
print_callees(*restrictions) This method for the Stats class prints a list of all function that were called by the indicated function. Aside from this reversal of direction of calls (re: called vs was called by), the arguments and ordering are identical to the print_callers() method.
python.library.profile#pstats.Stats.print_callees
print_callers(*restrictions) This method for the Stats class prints a list of all functions that called each function in the profiled database. The ordering is identical to that provided by print_stats(), and the definition of the restricting argument is also identical. Each caller is reported on its own line. The format differs slightly depending on the profiler that produced the stats: With profile, a number is shown in parentheses after each caller to show how many times this specific call was made. For convenience, a second non-parenthesized number repeats the cumulative time spent in the function at the right. With cProfile, each caller is preceded by three numbers: the number of times this specific call was made, and the total and cumulative times spent in the current function while it was invoked by this specific caller.
python.library.profile#pstats.Stats.print_callers
print_stats(*restrictions) This method for the Stats class prints out a report as described in the profile.run() definition. The order of the printing is based on the last sort_stats() operation done on the object (subject to caveats in add() and strip_dirs()). The arguments provided (if any) can be used to limit the list down to the significant entries. Initially, the list is taken to be the complete set of profiled functions. Each restriction is either an integer (to select a count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to select a percentage of lines), or a string that will interpreted as a regular expression (to pattern match the standard name that is printed). If several restrictions are provided, then they are applied sequentially. For example: print_stats(.1, 'foo:') would first limit the printing to first 10% of list, and then only print functions that were part of filename .*foo:. In contrast, the command: print_stats('foo:', .1) would limit the list to all functions having file names .*foo:, and then proceed to only print the first 10% of them.
python.library.profile#pstats.Stats.print_stats
reverse_order() This method for the Stats class reverses the ordering of the basic list within the object. Note that by default ascending vs descending order is properly selected based on the sort key of choice.
python.library.profile#pstats.Stats.reverse_order
sort_stats(*keys) This method modifies the Stats object by sorting it according to the supplied criteria. The argument can be either a string or a SortKey enum identifying the basis of a sort (example: 'time', 'name', SortKey.TIME or SortKey.NAME). The SortKey enums argument have advantage over the string argument in that it is more robust and less error prone. When more than one key is provided, then additional keys are used as secondary criteria when there is equality in all keys selected before them. For example, sort_stats(SortKey.NAME, SortKey.FILE) will sort all the entries according to their function name, and resolve all ties (identical function names) by sorting by file name. For the string argument, abbreviations can be used for any key names, as long as the abbreviation is unambiguous. The following are the valid string and SortKey: Valid String Arg Valid enum Arg Meaning 'calls' SortKey.CALLS call count 'cumulative' SortKey.CUMULATIVE cumulative time 'cumtime' N/A cumulative time 'file' N/A file name 'filename' SortKey.FILENAME file name 'module' N/A file name 'ncalls' N/A call count 'pcalls' SortKey.PCALLS primitive call count 'line' SortKey.LINE line number 'name' SortKey.NAME function name 'nfl' SortKey.NFL name/file/line 'stdname' SortKey.STDNAME standard name 'time' SortKey.TIME internal time 'tottime' N/A internal time Note that all sorts on statistics are in descending order (placing most time consuming items first), where as name, file, and line number searches are in ascending order (alphabetical). The subtle distinction between SortKey.NFL and SortKey.STDNAME is that the standard name is a sort of the name as printed, which means that the embedded line numbers get compared in an odd way. For example, lines 3, 20, and 40 would (if the file names were the same) appear in the string order 20, 3 and 40. In contrast, SortKey.NFL does a numeric compare of the line numbers. In fact, sort_stats(SortKey.NFL) is the same as sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE). For backward-compatibility reasons, the numeric arguments -1, 0, 1, and 2 are permitted. They are interpreted as 'stdname', 'calls', 'time', and 'cumulative' respectively. If this old style format (numeric) is used, only one sort key (the numeric key) will be used, and additional arguments will be silently ignored. New in version 3.7: Added the SortKey enum.
python.library.profile#pstats.Stats.sort_stats
strip_dirs() This method for the Stats class removes all leading path information from file names. It is very useful in reducing the size of the printout to fit within (close to) 80 columns. This method modifies the object, and the stripped information is lost. After performing a strip operation, the object is considered to have its entries in a “random” order, as it was just after object initialization and loading. If strip_dirs() causes two function names to be indistinguishable (they are on the same line of the same filename, and have the same function name), then the statistics for these two entries are accumulated into a single entry.
python.library.profile#pstats.Stats.strip_dirs
pty — Pseudo-terminal utilities Source code: Lib/pty.py The pty module defines operations for handling the pseudo-terminal concept: starting another process and being able to write to and read from its controlling terminal programmatically. Because pseudo-terminal handling is highly platform dependent, there is code to do it only for Linux. (The Linux code is supposed to work on other platforms, but hasn’t been tested yet.) The pty module defines the following functions: pty.fork() Fork. Connect the child’s controlling terminal to a pseudo-terminal. Return value is (pid, fd). Note that the child gets pid 0, and the fd is invalid. The parent’s return value is the pid of the child, and fd is a file descriptor connected to the child’s controlling terminal (and also to the child’s standard input and output). pty.openpty() Open a new pseudo-terminal pair, using os.openpty() if possible, or emulation code for generic Unix systems. Return a pair of file descriptors (master, slave), for the master and the slave end, respectively. pty.spawn(argv[, master_read[, stdin_read]]) Spawn a process, and connect its controlling terminal with the current process’s standard io. This is often used to baffle programs which insist on reading from the controlling terminal. It is expected that the process spawned behind the pty will eventually terminate, and when it does spawn will return. The functions master_read and stdin_read are passed a file descriptor which they should read from, and they should always return a byte string. In order to force spawn to return before the child process exits an OSError should be thrown. The default implementation for both functions will read and return up to 1024 bytes each time the function is called. The master_read callback is passed the pseudoterminal’s master file descriptor to read output from the child process, and stdin_read is passed file descriptor 0, to read from the parent process’s standard input. Returning an empty byte string from either callback is interpreted as an end-of-file (EOF) condition, and that callback will not be called after that. If stdin_read signals EOF the controlling terminal can no longer communicate with the parent process OR the child process. Unless the child process will quit without any input, spawn will then loop forever. If master_read signals EOF the same behavior results (on linux at least). If both callbacks signal EOF then spawn will probably never return, unless select throws an error on your platform when passed three empty lists. This is a bug, documented in issue 26228. Return the exit status value from os.waitpid() on the child process. waitstatus_to_exitcode() can be used to convert the exit status into an exit code. Raises an auditing event pty.spawn with argument argv. Changed in version 3.4: spawn() now returns the status value from os.waitpid() on the child process. Example The following program acts like the Unix command script(1), using a pseudo-terminal to record all input and output of a terminal session in a “typescript”. import argparse import os import pty import sys import time parser = argparse.ArgumentParser() parser.add_argument('-a', dest='append', action='store_true') parser.add_argument('-p', dest='use_python', action='store_true') parser.add_argument('filename', nargs='?', default='typescript') options = parser.parse_args() shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh') filename = options.filename mode = 'ab' if options.append else 'wb' with open(filename, mode) as script: def read(fd): data = os.read(fd, 1024) script.write(data) return data print('Script started, file is', filename) script.write(('Script started on %s\n' % time.asctime()).encode()) pty.spawn(shell, read) script.write(('Script done on %s\n' % time.asctime()).encode()) print('Script done, file is', filename)
python.library.pty
pty.fork() Fork. Connect the child’s controlling terminal to a pseudo-terminal. Return value is (pid, fd). Note that the child gets pid 0, and the fd is invalid. The parent’s return value is the pid of the child, and fd is a file descriptor connected to the child’s controlling terminal (and also to the child’s standard input and output).
python.library.pty#pty.fork
pty.openpty() Open a new pseudo-terminal pair, using os.openpty() if possible, or emulation code for generic Unix systems. Return a pair of file descriptors (master, slave), for the master and the slave end, respectively.
python.library.pty#pty.openpty
pty.spawn(argv[, master_read[, stdin_read]]) Spawn a process, and connect its controlling terminal with the current process’s standard io. This is often used to baffle programs which insist on reading from the controlling terminal. It is expected that the process spawned behind the pty will eventually terminate, and when it does spawn will return. The functions master_read and stdin_read are passed a file descriptor which they should read from, and they should always return a byte string. In order to force spawn to return before the child process exits an OSError should be thrown. The default implementation for both functions will read and return up to 1024 bytes each time the function is called. The master_read callback is passed the pseudoterminal’s master file descriptor to read output from the child process, and stdin_read is passed file descriptor 0, to read from the parent process’s standard input. Returning an empty byte string from either callback is interpreted as an end-of-file (EOF) condition, and that callback will not be called after that. If stdin_read signals EOF the controlling terminal can no longer communicate with the parent process OR the child process. Unless the child process will quit without any input, spawn will then loop forever. If master_read signals EOF the same behavior results (on linux at least). If both callbacks signal EOF then spawn will probably never return, unless select throws an error on your platform when passed three empty lists. This is a bug, documented in issue 26228. Return the exit status value from os.waitpid() on the child process. waitstatus_to_exitcode() can be used to convert the exit status into an exit code. Raises an auditing event pty.spawn with argument argv. Changed in version 3.4: spawn() now returns the status value from os.waitpid() on the child process.
python.library.pty#pty.spawn
pwd — The password database This module provides access to the Unix user account and password database. It is available on all Unix versions. Password database entries are reported as a tuple-like object, whose attributes correspond to the members of the passwd structure (Attribute field below, see <pwd.h>): Index Attribute Meaning 0 pw_name Login name 1 pw_passwd Optional encrypted password 2 pw_uid Numerical user ID 3 pw_gid Numerical group ID 4 pw_gecos User name or comment field 5 pw_dir User home directory 6 pw_shell User command interpreter The uid and gid items are integers, all others are strings. KeyError is raised if the entry asked for cannot be found. Note In traditional Unix the field pw_passwd usually contains a password encrypted with a DES derived algorithm (see module crypt). However most modern unices use a so-called shadow password system. On those unices the pw_passwd field only contains an asterisk ('*') or the letter 'x' where the encrypted password is stored in a file /etc/shadow which is not world readable. Whether the pw_passwd field contains anything useful is system-dependent. If available, the spwd module should be used where access to the encrypted password is required. It defines the following items: pwd.getpwuid(uid) Return the password database entry for the given numeric user ID. pwd.getpwnam(name) Return the password database entry for the given user name. pwd.getpwall() Return a list of all available password database entries, in arbitrary order. See also Module grp An interface to the group database, similar to this. Module spwd An interface to the shadow password database, similar to this.
python.library.pwd
pwd.getpwall() Return a list of all available password database entries, in arbitrary order.
python.library.pwd#pwd.getpwall
pwd.getpwnam(name) Return the password database entry for the given user name.
python.library.pwd#pwd.getpwnam
pwd.getpwuid(uid) Return the password database entry for the given numeric user ID.
python.library.pwd#pwd.getpwuid
pyclbr — Python module browser support Source code: Lib/pyclbr.py The pyclbr module provides limited information about the functions, classes, and methods defined in a Python-coded module. The information is sufficient to implement a module browser. The information is extracted from the Python source code rather than by importing the module, so this module is safe to use with untrusted code. This restriction makes it impossible to use this module with modules not implemented in Python, including all standard and optional extension modules. pyclbr.readmodule(module, path=None) Return a dictionary mapping module-level class names to class descriptors. If possible, descriptors for imported base classes are included. Parameter module is a string with the name of the module to read; it may be the name of a module within a package. If given, path is a sequence of directory paths prepended to sys.path, which is used to locate the module source code. This function is the original interface and is only kept for back compatibility. It returns a filtered version of the following. pyclbr.readmodule_ex(module, path=None) Return a dictionary-based tree containing a function or class descriptors for each function and class defined in the module with a def or class statement. The returned dictionary maps module-level function and class names to their descriptors. Nested objects are entered into the children dictionary of their parent. As with readmodule, module names the module to be read and path is prepended to sys.path. If the module being read is a package, the returned dictionary has a key '__path__' whose value is a list containing the package search path. New in version 3.7: Descriptors for nested definitions. They are accessed through the new children attribute. Each has a new parent attribute. The descriptors returned by these functions are instances of Function and Class classes. Users are not expected to create instances of these classes. Function Objects Class Function instances describe functions defined by def statements. They have the following attributes: Function.file Name of the file in which the function is defined. Function.module The name of the module defining the function described. Function.name The name of the function. Function.lineno The line number in the file where the definition starts. Function.parent For top-level functions, None. For nested functions, the parent. New in version 3.7. Function.children A dictionary mapping names to descriptors for nested functions and classes. New in version 3.7. Class Objects Class Class instances describe classes defined by class statements. They have the same attributes as Functions and two more. Class.file Name of the file in which the class is defined. Class.module The name of the module defining the class described. Class.name The name of the class. Class.lineno The line number in the file where the definition starts. Class.parent For top-level classes, None. For nested classes, the parent. New in version 3.7. Class.children A dictionary mapping names to descriptors for nested functions and classes. New in version 3.7. Class.super A list of Class objects which describe the immediate base classes of the class being described. Classes which are named as superclasses but which are not discoverable by readmodule_ex() are listed as a string with the class name instead of as Class objects. Class.methods A dictionary mapping method names to line numbers. This can be derived from the newer children dictionary, but remains for back-compatibility.
python.library.pyclbr
Class.children A dictionary mapping names to descriptors for nested functions and classes. New in version 3.7.
python.library.pyclbr#pyclbr.Class.children
Class.file Name of the file in which the class is defined.
python.library.pyclbr#pyclbr.Class.file
Class.lineno The line number in the file where the definition starts.
python.library.pyclbr#pyclbr.Class.lineno
Class.methods A dictionary mapping method names to line numbers. This can be derived from the newer children dictionary, but remains for back-compatibility.
python.library.pyclbr#pyclbr.Class.methods
Class.module The name of the module defining the class described.
python.library.pyclbr#pyclbr.Class.module
Class.name The name of the class.
python.library.pyclbr#pyclbr.Class.name
Class.parent For top-level classes, None. For nested classes, the parent. New in version 3.7.
python.library.pyclbr#pyclbr.Class.parent
Class.super A list of Class objects which describe the immediate base classes of the class being described. Classes which are named as superclasses but which are not discoverable by readmodule_ex() are listed as a string with the class name instead of as Class objects.
python.library.pyclbr#pyclbr.Class.super
Function.children A dictionary mapping names to descriptors for nested functions and classes. New in version 3.7.
python.library.pyclbr#pyclbr.Function.children
Function.file Name of the file in which the function is defined.
python.library.pyclbr#pyclbr.Function.file
Function.lineno The line number in the file where the definition starts.
python.library.pyclbr#pyclbr.Function.lineno
Function.module The name of the module defining the function described.
python.library.pyclbr#pyclbr.Function.module
Function.name The name of the function.
python.library.pyclbr#pyclbr.Function.name
Function.parent For top-level functions, None. For nested functions, the parent. New in version 3.7.
python.library.pyclbr#pyclbr.Function.parent
pyclbr.readmodule(module, path=None) Return a dictionary mapping module-level class names to class descriptors. If possible, descriptors for imported base classes are included. Parameter module is a string with the name of the module to read; it may be the name of a module within a package. If given, path is a sequence of directory paths prepended to sys.path, which is used to locate the module source code. This function is the original interface and is only kept for back compatibility. It returns a filtered version of the following.
python.library.pyclbr#pyclbr.readmodule
pyclbr.readmodule_ex(module, path=None) Return a dictionary-based tree containing a function or class descriptors for each function and class defined in the module with a def or class statement. The returned dictionary maps module-level function and class names to their descriptors. Nested objects are entered into the children dictionary of their parent. As with readmodule, module names the module to be read and path is prepended to sys.path. If the module being read is a package, the returned dictionary has a key '__path__' whose value is a list containing the package search path.
python.library.pyclbr#pyclbr.readmodule_ex
pydoc — Documentation generator and online help system Source code: Lib/pydoc.py The pydoc module automatically generates documentation from Python modules. The documentation can be presented as pages of text on the console, served to a Web browser, or saved to HTML files. For modules, classes, functions and methods, the displayed documentation is derived from the docstring (i.e. the __doc__ attribute) of the object, and recursively of its documentable members. If there is no docstring, pydoc tries to obtain a description from the block of comment lines just above the definition of the class, function or method in the source file, or at the top of the module (see inspect.getcomments()). The built-in function help() invokes the online help system in the interactive interpreter, which uses pydoc to generate its documentation as text on the console. The same text documentation can also be viewed from outside the Python interpreter by running pydoc as a script at the operating system’s command prompt. For example, running pydoc sys at a shell prompt will display documentation on the sys module, in a style similar to the manual pages shown by the Unix man command. The argument to pydoc can be the name of a function, module, or package, or a dotted reference to a class, method, or function within a module or module in a package. If the argument to pydoc looks like a path (that is, it contains the path separator for your operating system, such as a slash in Unix), and refers to an existing Python source file, then documentation is produced for that file. Note In order to find objects and their documentation, pydoc imports the module(s) to be documented. Therefore, any code on module level will be executed on that occasion. Use an if __name__ == '__main__': guard to only execute code when a file is invoked as a script and not just imported. When printing output to the console, pydoc attempts to paginate the output for easier reading. If the PAGER environment variable is set, pydoc will use its value as a pagination program. Specifying a -w flag before the argument will cause HTML documentation to be written out to a file in the current directory, instead of displaying text on the console. Specifying a -k flag before the argument will search the synopsis lines of all available modules for the keyword given as the argument, again in a manner similar to the Unix man command. The synopsis line of a module is the first line of its documentation string. You can also use pydoc to start an HTTP server on the local machine that will serve documentation to visiting Web browsers. pydoc -p 1234 will start a HTTP server on port 1234, allowing you to browse the documentation at http://localhost:1234/ in your preferred Web browser. Specifying 0 as the port number will select an arbitrary unused port. pydoc -n <hostname> will start the server listening at the given hostname. By default the hostname is ‘localhost’ but if you want the server to be reached from other machines, you may want to change the host name that the server responds to. During development this is especially useful if you want to run pydoc from within a container. pydoc -b will start the server and additionally open a web browser to a module index page. Each served page has a navigation bar at the top where you can Get help on an individual item, Search all modules with a keyword in their synopsis line, and go to the Module index, Topics and Keywords pages. When pydoc generates documentation, it uses the current environment and path to locate modules. Thus, invoking pydoc spam documents precisely the version of the module you would get if you started the Python interpreter and typed import spam. Module docs for core modules are assumed to reside in https://docs.python.org/X.Y/library/ where X and Y are the major and minor version numbers of the Python interpreter. This can be overridden by setting the PYTHONDOCS environment variable to a different URL or to a local directory containing the Library Reference Manual pages. Changed in version 3.2: Added the -b option. Changed in version 3.3: The -g command line option was removed. Changed in version 3.4: pydoc now uses inspect.signature() rather than inspect.getfullargspec() to extract signature information from callables. Changed in version 3.7: Added the -n option.
python.library.pydoc
py_compile — Compile Python source files Source code: Lib/py_compile.py The py_compile module provides a function to generate a byte-code file from a source file, and another function used when the module source file is invoked as a script. Though not often needed, this function can be useful when installing modules for shared use, especially if some of the users may not have permission to write the byte-code cache files in the directory containing the source code. exception py_compile.PyCompileError Exception raised when an error occurs while attempting to compile the file. py_compile.compile(file, cfile=None, dfile=None, doraise=False, optimize=-1, invalidation_mode=PycInvalidationMode.TIMESTAMP, quiet=0) Compile a source file to byte-code and write out the byte-code cache file. The source code is loaded from the file named file. The byte-code is written to cfile, which defaults to the PEP 3147/PEP 488 path, ending in .pyc. For example, if file is /foo/bar/baz.py cfile will default to /foo/bar/__pycache__/baz.cpython-32.pyc for Python 3.2. If dfile is specified, it is used as the name of the source file in error messages instead of file. If doraise is true, a PyCompileError is raised when an error is encountered while compiling file. If doraise is false (the default), an error string is written to sys.stderr, but no exception is raised. This function returns the path to byte-compiled file, i.e. whatever cfile value was used. The doraise and quiet arguments determine how errors are handled while compiling file. If quiet is 0 or 1, and doraise is false, the default behaviour is enabled: an error string is written to sys.stderr, and the function returns None instead of a path. If doraise is true, a PyCompileError is raised instead. However if quiet is 2, no message is written, and doraise has no effect. If the path that cfile becomes (either explicitly specified or computed) is a symlink or non-regular file, FileExistsError will be raised. This is to act as a warning that import will turn those paths into regular files if it is allowed to write byte-compiled files to those paths. This is a side-effect of import using file renaming to place the final byte-compiled file into place to prevent concurrent file writing issues. optimize controls the optimization level and is passed to the built-in compile() function. The default of -1 selects the optimization level of the current interpreter. invalidation_mode should be a member of the PycInvalidationMode enum and controls how the generated bytecode cache is invalidated at runtime. The default is PycInvalidationMode.CHECKED_HASH if the SOURCE_DATE_EPOCH environment variable is set, otherwise the default is PycInvalidationMode.TIMESTAMP. Changed in version 3.2: Changed default value of cfile to be PEP 3147-compliant. Previous default was file + 'c' ('o' if optimization was enabled). Also added the optimize parameter. Changed in version 3.4: Changed code to use importlib for the byte-code cache file writing. This means file creation/writing semantics now match what importlib does, e.g. permissions, write-and-move semantics, etc. Also added the caveat that FileExistsError is raised if cfile is a symlink or non-regular file. Changed in version 3.7: The invalidation_mode parameter was added as specified in PEP 552. If the SOURCE_DATE_EPOCH environment variable is set, invalidation_mode will be forced to PycInvalidationMode.CHECKED_HASH. Changed in version 3.7.2: The SOURCE_DATE_EPOCH environment variable no longer overrides the value of the invalidation_mode argument, and determines its default value instead. Changed in version 3.8: The quiet parameter was added. class py_compile.PycInvalidationMode A enumeration of possible methods the interpreter can use to determine whether a bytecode file is up to date with a source file. The .pyc file indicates the desired invalidation mode in its header. See Cached bytecode invalidation for more information on how Python invalidates .pyc files at runtime. New in version 3.7. TIMESTAMP The .pyc file includes the timestamp and size of the source file, which Python will compare against the metadata of the source file at runtime to determine if the .pyc file needs to be regenerated. CHECKED_HASH The .pyc file includes a hash of the source file content, which Python will compare against the source at runtime to determine if the .pyc file needs to be regenerated. UNCHECKED_HASH Like CHECKED_HASH, the .pyc file includes a hash of the source file content. However, Python will at runtime assume the .pyc file is up to date and not validate the .pyc against the source file at all. This option is useful when the .pycs are kept up to date by some system external to Python like a build system. py_compile.main(args=None) Compile several source files. The files named in args (or on the command line, if args is None) are compiled and the resulting byte-code is cached in the normal manner. This function does not search a directory structure to locate source files; it only compiles files named explicitly. If '-' is the only parameter in args, the list of files is taken from standard input. Changed in version 3.2: Added support for '-'. When this module is run as a script, the main() is used to compile all the files named on the command line. The exit status is nonzero if one of the files could not be compiled. See also Module compileall Utilities to compile all Python source files in a directory tree.
python.library.py_compile
py_compile.compile(file, cfile=None, dfile=None, doraise=False, optimize=-1, invalidation_mode=PycInvalidationMode.TIMESTAMP, quiet=0) Compile a source file to byte-code and write out the byte-code cache file. The source code is loaded from the file named file. The byte-code is written to cfile, which defaults to the PEP 3147/PEP 488 path, ending in .pyc. For example, if file is /foo/bar/baz.py cfile will default to /foo/bar/__pycache__/baz.cpython-32.pyc for Python 3.2. If dfile is specified, it is used as the name of the source file in error messages instead of file. If doraise is true, a PyCompileError is raised when an error is encountered while compiling file. If doraise is false (the default), an error string is written to sys.stderr, but no exception is raised. This function returns the path to byte-compiled file, i.e. whatever cfile value was used. The doraise and quiet arguments determine how errors are handled while compiling file. If quiet is 0 or 1, and doraise is false, the default behaviour is enabled: an error string is written to sys.stderr, and the function returns None instead of a path. If doraise is true, a PyCompileError is raised instead. However if quiet is 2, no message is written, and doraise has no effect. If the path that cfile becomes (either explicitly specified or computed) is a symlink or non-regular file, FileExistsError will be raised. This is to act as a warning that import will turn those paths into regular files if it is allowed to write byte-compiled files to those paths. This is a side-effect of import using file renaming to place the final byte-compiled file into place to prevent concurrent file writing issues. optimize controls the optimization level and is passed to the built-in compile() function. The default of -1 selects the optimization level of the current interpreter. invalidation_mode should be a member of the PycInvalidationMode enum and controls how the generated bytecode cache is invalidated at runtime. The default is PycInvalidationMode.CHECKED_HASH if the SOURCE_DATE_EPOCH environment variable is set, otherwise the default is PycInvalidationMode.TIMESTAMP. Changed in version 3.2: Changed default value of cfile to be PEP 3147-compliant. Previous default was file + 'c' ('o' if optimization was enabled). Also added the optimize parameter. Changed in version 3.4: Changed code to use importlib for the byte-code cache file writing. This means file creation/writing semantics now match what importlib does, e.g. permissions, write-and-move semantics, etc. Also added the caveat that FileExistsError is raised if cfile is a symlink or non-regular file. Changed in version 3.7: The invalidation_mode parameter was added as specified in PEP 552. If the SOURCE_DATE_EPOCH environment variable is set, invalidation_mode will be forced to PycInvalidationMode.CHECKED_HASH. Changed in version 3.7.2: The SOURCE_DATE_EPOCH environment variable no longer overrides the value of the invalidation_mode argument, and determines its default value instead. Changed in version 3.8: The quiet parameter was added.
python.library.py_compile#py_compile.compile
py_compile.main(args=None) Compile several source files. The files named in args (or on the command line, if args is None) are compiled and the resulting byte-code is cached in the normal manner. This function does not search a directory structure to locate source files; it only compiles files named explicitly. If '-' is the only parameter in args, the list of files is taken from standard input. Changed in version 3.2: Added support for '-'.
python.library.py_compile#py_compile.main
class py_compile.PycInvalidationMode A enumeration of possible methods the interpreter can use to determine whether a bytecode file is up to date with a source file. The .pyc file indicates the desired invalidation mode in its header. See Cached bytecode invalidation for more information on how Python invalidates .pyc files at runtime. New in version 3.7. TIMESTAMP The .pyc file includes the timestamp and size of the source file, which Python will compare against the metadata of the source file at runtime to determine if the .pyc file needs to be regenerated. CHECKED_HASH The .pyc file includes a hash of the source file content, which Python will compare against the source at runtime to determine if the .pyc file needs to be regenerated. UNCHECKED_HASH Like CHECKED_HASH, the .pyc file includes a hash of the source file content. However, Python will at runtime assume the .pyc file is up to date and not validate the .pyc against the source file at all. This option is useful when the .pycs are kept up to date by some system external to Python like a build system.
python.library.py_compile#py_compile.PycInvalidationMode
CHECKED_HASH The .pyc file includes a hash of the source file content, which Python will compare against the source at runtime to determine if the .pyc file needs to be regenerated.
python.library.py_compile#py_compile.PycInvalidationMode.CHECKED_HASH
TIMESTAMP The .pyc file includes the timestamp and size of the source file, which Python will compare against the metadata of the source file at runtime to determine if the .pyc file needs to be regenerated.
python.library.py_compile#py_compile.PycInvalidationMode.TIMESTAMP
UNCHECKED_HASH Like CHECKED_HASH, the .pyc file includes a hash of the source file content. However, Python will at runtime assume the .pyc file is up to date and not validate the .pyc against the source file at all. This option is useful when the .pycs are kept up to date by some system external to Python like a build system.
python.library.py_compile#py_compile.PycInvalidationMode.UNCHECKED_HASH
exception py_compile.PyCompileError Exception raised when an error occurs while attempting to compile the file.
python.library.py_compile#py_compile.PyCompileError
queue — A synchronized queue class Source code: Lib/queue.py The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. The module implements three types of queue, which differ only in the order in which the entries are retrieved. In a FIFO queue, the first tasks added are the first retrieved. In a LIFO queue, the most recently added entry is the first retrieved (operating like a stack). With a priority queue, the entries are kept sorted (using the heapq module) and the lowest valued entry is retrieved first. Internally, those three types of queues use locks to temporarily block competing threads; however, they are not designed to handle reentrancy within a thread. In addition, the module implements a “simple” FIFO queue type, SimpleQueue, whose specific implementation provides additional guarantees in exchange for the smaller functionality. The queue module defines the following classes and exceptions: class queue.Queue(maxsize=0) Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite. class queue.LifoQueue(maxsize=0) Constructor for a LIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite. class queue.PriorityQueue(maxsize=0) Constructor for a priority queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite. The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]). A typical pattern for entries is a tuple in the form: (priority_number, data). If the data elements are not comparable, the data can be wrapped in a class that ignores the data item and only compares the priority number: from dataclasses import dataclass, field from typing import Any @dataclass(order=True) class PrioritizedItem: priority: int item: Any=field(compare=False) class queue.SimpleQueue Constructor for an unbounded FIFO queue. Simple queues lack advanced functionality such as task tracking. New in version 3.7. exception queue.Empty Exception raised when non-blocking get() (or get_nowait()) is called on a Queue object which is empty. exception queue.Full Exception raised when non-blocking put() (or put_nowait()) is called on a Queue object which is full. Queue Objects Queue objects (Queue, LifoQueue, or PriorityQueue) provide the public methods described below. Queue.qsize() Return the approximate size of the queue. Note, qsize() > 0 doesn’t guarantee that a subsequent get() will not block, nor will qsize() < maxsize guarantee that put() will not block. Queue.empty() Return True if the queue is empty, False otherwise. If empty() returns True it doesn’t guarantee that a subsequent call to put() will not block. Similarly, if empty() returns False it doesn’t guarantee that a subsequent call to get() will not block. Queue.full() Return True if the queue is full, False otherwise. If full() returns True it doesn’t guarantee that a subsequent call to get() will not block. Similarly, if full() returns False it doesn’t guarantee that a subsequent call to put() will not block. Queue.put(item, block=True, timeout=None) Put item into the queue. If optional args block is true and timeout is None (the default), block if necessary until a free slot is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Full exception if no free slot was available within that time. Otherwise (block is false), put an item on the queue if a free slot is immediately available, else raise the Full exception (timeout is ignored in that case). Queue.put_nowait(item) Equivalent to put(item, False). Queue.get(block=True, timeout=None) Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case). Prior to 3.0 on POSIX systems, and for all versions on Windows, if block is true and timeout is None, this operation goes into an uninterruptible wait on an underlying lock. This means that no exceptions can occur, and in particular a SIGINT will not trigger a KeyboardInterrupt. Queue.get_nowait() Equivalent to get(False). Two methods are offered to support tracking whether enqueued tasks have been fully processed by daemon consumer threads. Queue.task_done() Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue. Queue.join() Blocks until all items in the queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. Example of how to wait for enqueued tasks to be completed: import threading, queue q = queue.Queue() def worker(): while True: item = q.get() print(f'Working on {item}') print(f'Finished {item}') q.task_done() # turn-on the worker thread threading.Thread(target=worker, daemon=True).start() # send thirty task requests to the worker for item in range(30): q.put(item) print('All task requests sent\n', end='') # block until all tasks are done q.join() print('All work completed') SimpleQueue Objects SimpleQueue objects provide the public methods described below. SimpleQueue.qsize() Return the approximate size of the queue. Note, qsize() > 0 doesn’t guarantee that a subsequent get() will not block. SimpleQueue.empty() Return True if the queue is empty, False otherwise. If empty() returns False it doesn’t guarantee that a subsequent call to get() will not block. SimpleQueue.put(item, block=True, timeout=None) Put item into the queue. The method never blocks and always succeeds (except for potential low-level errors such as failure to allocate memory). The optional args block and timeout are ignored and only provided for compatibility with Queue.put(). CPython implementation detail: This method has a C implementation which is reentrant. That is, a put() or get() call can be interrupted by another put() call in the same thread without deadlocking or corrupting internal state inside the queue. This makes it appropriate for use in destructors such as __del__ methods or weakref callbacks. SimpleQueue.put_nowait(item) Equivalent to put(item), provided for compatibility with Queue.put_nowait(). SimpleQueue.get(block=True, timeout=None) Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case). SimpleQueue.get_nowait() Equivalent to get(False). See also Class multiprocessing.Queue A queue class for use in a multi-processing (rather than multi-threading) context. collections.deque is an alternative implementation of unbounded queues with fast atomic append() and popleft() operations that do not require locking and also support indexing.
python.library.queue