plistlib — Generate and parse Apple .plist files Source code: Lib/plistlib.py This module provides an interface for reading and writing the “property list” files used by Apple, primarily on macOS and iOS. This module supports both binary and XML plist files. The property list (.plist) file format is a simple serialization supporting basic object types, like dictionaries, lists, numbers and strings. Usually the top level object is a dictionary. To write out and to parse a plist file, use the dump() and load() functions. To work with plist data in bytes objects, use dumps() and loads(). Values can be strings, integers, floats, booleans, tuples, lists, dictionaries (but only with string keys), bytes, bytearray or datetime.datetime objects.  Changed in version 3.4: New API, old API deprecated. Support for binary format plists added.   Changed in version 3.8: Support added for reading and writing UID tokens in binary plists as used by NSKeyedArchiver and NSKeyedUnarchiver.   Changed in version 3.9: Old API removed.   See also  PList manual page

Apple’s documentation of the file format.    This module defines the following functions:
plistlib.load(fp, *, fmt=None, dict_type=dict)
Read a plist file. fp should be a readable and binary file object. Return the unpacked root object (which usually is a dictionary). The fmt is the format of the file and the following values are valid:
None: Autodetect the file format
FMT_XML: XML file format
FMT_BINARY: Binary plist format  The dict_type is the type used for dictionaries that are read from the plist file. XML data for the FMT_XML format is parsed using the Expat parser from xml.parsers.expat – see its documentation for possible exceptions on ill-formed XML. Unknown elements will simply be ignored by the plist parser. The parser for the binary format raises InvalidFileException when the file cannot be parsed.  New in version 3.4.

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.

plistlib.dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
Write value to a plist file. Fp should be a writable, binary file object. The fmt argument specifies the format of the plist file and can be one of the following values:
FMT_XML: XML formatted plist file
FMT_BINARY: Binary formatted plist file  When sort_keys is true (the default) the keys for dictionaries will be written to the plist in sorted order, otherwise they will be written in the iteration order of the dictionary. When skipkeys is false (the default) the function raises TypeError when a key of a dictionary is not a string, otherwise such keys are skipped. A TypeError will be raised if the object is of an unsupported type or a container that contains objects of unsupported types. An OverflowError will be raised for integer values that cannot be represented in (binary) plist files.  New in version 3.4.

plistlib.dumps(value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
Return value as a plist-formatted bytes object. See the documentation for dump() for an explanation of the keyword arguments of this function.  New in version 3.4.
 The following classes are available:
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.
 The following constants are available:
plistlib.FMT_XML
The XML format for plist files.  New in version 3.4.

plistlib.FMT_BINARY
The binary format for plist files  New in version 3.4.
 Examples Generating a plist: pl = dict(
    aString = "Doodah",
    aList = ["A", "B", 12, 32.1, [1, 2, 3]],
    aFloat = 0.1,
    anInt = 728,
    aDict = dict(
        anotherString = "<hello & hi there!>",
        aThirdString = "M\xe4ssig, Ma\xdf",
        aTrueValue = True,
        aFalseValue = False,
    ),
    someData = b"<binary gunk>",
    someMoreData = b"<lots of binary gunk>" * 10,
    aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
)
with open(fileName, 'wb') as fp:
    dump(pl, fp)
 Parsing a plist: with open(fileName, 'rb') as fp:
    pl = load(fp)
print(pl["aKey"])


plistlib.dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
Write value to a plist file. Fp should be a writable, binary file object. The fmt argument specifies the format of the plist file and can be one of the following values:
FMT_XML: XML formatted plist file
FMT_BINARY: Binary formatted plist file  When sort_keys is true (the default) the keys for dictionaries will be written to the plist in sorted order, otherwise they will be written in the iteration order of the dictionary. When skipkeys is false (the default) the function raises TypeError when a key of a dictionary is not a string, otherwise such keys are skipped. A TypeError will be raised if the object is of an unsupported type or a container that contains objects of unsupported types. An OverflowError will be raised for integer values that cannot be represented in (binary) plist files.  New in version 3.4.


plistlib.dumps(value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)
Return value as a plist-formatted bytes object. See the documentation for dump() for an explanation of the keyword arguments of this function.  New in version 3.4.


plistlib.FMT_BINARY
The binary format for plist files  New in version 3.4.


plistlib.FMT_XML
The XML format for plist files.  New in version 3.4.


plistlib.load(fp, *, fmt=None, dict_type=dict)
Read a plist file. fp should be a readable and binary file object. Return the unpacked root object (which usually is a dictionary). The fmt is the format of the file and the following values are valid:
None: Autodetect the file format
FMT_XML: XML file format
FMT_BINARY: Binary plist format  The dict_type is the type used for dictionaries that are read from the plist file. XML data for the FMT_XML format is parsed using the Expat parser from xml.parsers.expat – see its documentation for possible exceptions on ill-formed XML. Unknown elements will simply be ignored by the plist parser. The parser for the binary format raises InvalidFileException when the file cannot be parsed.  New in version 3.4.


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.


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.


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())


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.


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.


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.


POP3.apop(user, secret)
Use the more secure APOP authentication to log into 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.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.getwelcome()
Returns the greeting string sent by the POP3 server.


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.noop()
Do nothing. Might be used as a keep-alive.


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.quit()
Signoff: commit changes, unlock mailbox, drop connection.


POP3.retr(which)
Retrieve whole message number which, and set its seen flag. Result is in form (response, ['line', ...], octets).


POP3.rpop(user)
Use RPOP authentication (similar to UNIX r-commands) to log into POP3 server.


POP3.rset()
Remove any deletion marks for the mailbox.


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.stat()
Get mailbox status. The result is a tuple of 2 integers: (message count,
mailbox size).


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.


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.user(username)
Send user command, response should indicate that a password is required.


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.


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.


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.


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.


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.


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'}


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.


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']


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', (...)))))))


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.


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.


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.


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']"


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.


exception ProcessLookupError
Raised when a given process doesn’t exist. Corresponds to errno ESRCH.


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)


create_stats()
Stop collecting profiling data and record the results internally as the current profile.


disable()
Stop collecting profiling data. Only in cProfile.


dump_stats(filename)
Write the results of the current profile to filename.


enable()
Start collecting profiling data. Only in cProfile.


print_stats(sort=-1)
Create a Stats object based on the current profile and print the results to stdout.


runcall(func, /, *args, **kwargs)
Profile func(*args, **kwargs)


runctx(cmd, globals, locals)
Profile the cmd via exec() with the specified global and local environment.


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.


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.


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.


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.


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.


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.


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.


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_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.


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.


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.


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.


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)


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.


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.


pwd.getpwall()
Return a list of all available password database entries, in arbitrary order.


pwd.getpwnam(name)
Return the password database entry for the given user name.


pwd.getpwuid(uid)
Return the password database entry for the given numeric user ID.


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.


Class.children
A dictionary mapping names to descriptors for nested functions and classes.  New in version 3.7.


Class.file
Name of the file in which the class is defined.


Class.lineno
The line number in the file where the definition starts.


Class.methods
A dictionary mapping method names to line numbers. This can be derived from the newer children dictionary, but remains for back-compatibility.


Class.module
The name of the module defining the class described.


Class.parent
For top-level classes, None. For nested classes, the parent.  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.


Function.children
A dictionary mapping names to descriptors for nested functions and classes.  New in version 3.7.


Function.file
Name of the file in which the function is defined.


Function.lineno
The line number in the file where the definition starts.


Function.module
The name of the module defining the function described.


Function.parent
For top-level functions, None. For nested functions, the parent.  New in version 3.7.


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.


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.


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.