### Starting and Serving with asyncio Source: https://devdocs.io/python~3.14/library/asyncio-eventloop This example demonstrates how to start a server and have it serve connections indefinitely using `serve_forever()`. It includes a basic client connection handler. ```python async def client_connected(reader, writer): # Communicate with the client with # reader/writer streams. For example: await reader.readline() async def main(host, port): srv = await asyncio.start_server( client_connected, host, port) await srv.serve_forever() asyncio.run(main('127.0.0.1', 0)) ``` -------------------------------- ### Process Example Usage Source: https://devdocs.io/python~3.14/library/multiprocessing Example demonstrating the usage of Process methods like start(), is_alive(), terminate(), and accessing exitcode. ```APIDOC ## Example usage of some of the methods of `Process`: ```python >>> import multiprocessing, time, signal >>> mp_context = multiprocessing.get_context('spawn') >>> p = mp_context.Process(target=time.sleep, args=(1000,)) >>> print(p, p.is_alive()) <...Process ... initial> False >>> p.start() >>> print(p, p.is_alive()) <...Process ... started> True >>> p.terminate() >>> time.sleep(0.1) >>> print(p, p.is_alive()) <...Process ... stopped exitcode=-SIGTERM> False >>> p.exitcode == -signal.SIGTERM True ``` ``` -------------------------------- ### Basic optparse Usage Source: https://devdocs.io/python~3.14/library/optparse Demonstrates the basic setup and usage of optparse for defining and parsing command-line options. This example shows how to add options and process arguments. ```python import optparse if __name__ == '__main__': parser = optparse.OptionParser() parser.add_option('-o', '--output') parser.add_option('-v', dest='verbose', action='store_true') opts, args = parser.parse_args() process(args, output=opts.output, verbose=opts.verbose) ``` -------------------------------- ### Example Log Output Source: https://devdocs.io/python~3.14/howto/logging-cookbook Illustrates the expected output format from the configured logging setup, showing messages from different loggers and levels. ```text 2005-03-23 23:47:11,663 - spam_application - INFO - creating an instance of auxiliary_module.Auxiliary 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO - creating an instance of Auxiliary 2005-03-23 23:47:11,665 - spam_application - INFO - created an instance of auxiliary_module.Auxiliary 2005-03-23 23:47:11,668 - spam_application - INFO - calling auxiliary_module.Auxiliary.do_something 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO - doing something 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO - done doing something 2005-03-23 23:47:11,670 - spam_application - INFO - finished auxiliary_module.Auxiliary.do_something 2005-03-23 23:47:11,671 - spam_application - INFO - calling auxiliary_module.some_function() 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO - received a call to 'some_function' 2005-03-23 23:47:11,673 - spam_application - INFO - done with auxiliary_module.some_function() ``` -------------------------------- ### Start Command Implementation Source: https://devdocs.io/python~3.14/howto/logging-cookbook This snippet shows the implementation for the 'start' command in a separate module. It logs debug information before starting a service and an info message upon completion. ```python # start.py import logging logger = logging.getLogger(__name__) def command(options): logger.debug('About to start %s', options.name) # actually do the command processing here ... logger.info('Started the \'%s\' service.', options.name) ``` -------------------------------- ### Basic argparse Usage Source: https://devdocs.io/python~3.14/library/optparse Illustrates the equivalent basic setup and usage of argparse for defining and parsing command-line options. This example highlights the differences in how positional arguments are handled compared to optparse. ```python import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-o', '--output') parser.add_argument('-v', dest='verbose', action='store_true') parser.add_argument('rest', nargs='*') args = parser.parse_args() process(args.rest, output=args.output, verbose=args.verbose) ``` -------------------------------- ### Configure Setup for New Python Modules Source: https://devdocs.io/python~3.14/extending/newtypes_tutorial Modify the `setup.py` file to include new extension modules, ensuring they are correctly compiled and installed with the project. ```python from setuptools import Extension, setup setup(ext_modules=[ Extension("custom", ["custom.c"]), Extension("custom2", ["custom2.c"]), ]) ``` -------------------------------- ### count() example Source: https://devdocs.io/python~3.14/library/itertools Creates an iterator that returns evenly spaced values starting with 'start' and incrementing by 'step'. ```python from itertools import count count(10) # Output: 10 11 12 13 14 ... ``` -------------------------------- ### turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom']) Source: https://devdocs.io/python~3.14/library/turtle Sets the size and position of the main window. ```APIDOC ## turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom']) ### Description Set the size and position of the main window. Default values of arguments are stored in the configuration dictionary and can be changed via a `turtle.cfg` file. ### Parameters * **width** (integer or float) - Optional - if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen * **height** (integer or float) - Optional - if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen * **startx** (integer or None) - Optional - if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if `None`, center window horizontally * **starty** (integer or None) - Optional - if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if `None`, center window vertically ### Request Example ```python screen.setup (width=200, height=200, startx=0, starty=0) # sets window to 200x200 pixels, in upper left of screen screen.setup(width=.75, height=0.5, startx=None, starty=None) # sets window to 75% of screen by 50% of screen and centers ``` ``` -------------------------------- ### Get Start Attribute of Unicode Exception Source: https://devdocs.io/python~3.14/c-api/exceptions Retrieves the start attribute from a given Unicode exception object. The start attribute is placed into *start. This function returns 0 on success and -1 on failure. ```c int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) ``` ```c int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) ``` ```c int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) ``` -------------------------------- ### curses.setupterm Source: https://devdocs.io/python~3.14-command-line-interface-libraries Initialize the curses application. ```APIDOC ## curses.setupterm(term=None, file=None) ### Description Initialize the curses application. This function should be called only once, at the beginning of a curses application. It initializes the terminal to the curses mode. ### Method Call ### Endpoint curses.setupterm(term=None, file=None) ``` -------------------------------- ### Unattended Installation Configuration Source: https://devdocs.io/python~3.14/using/windows An example of an unattended installation file (`unattend.xml`) that configures Python installation options. Values can be provided as attributes (converted to numbers if possible) or element text (always strings). ```xml ``` -------------------------------- ### Basic ls command examples Source: https://devdocs.io/python~3.14/howto/argparse Demonstrates the default behavior of the 'ls' command and how to specify a directory. Also shows 'ls -l' for detailed output and 'ls --help' for usage information. ```bash $ ls cpython devguide prog.py pypy rm-unused-function.patch ``` ```bash $ ls pypy ctypes_configure demo dotviewer include lib_pypy lib-python ... ``` ```bash $ ls -l total 20 drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide -rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy -rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch ``` ```bash $ ls --help Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. ... ``` -------------------------------- ### SETUP_WITH Context Manager Setup Source: https://devdocs.io/python~3.14/library/dis Sets up a context manager for 'with' or 'async with' statements. Like SETUP_CLEANUP, but pops an additional item from the stack before transferring control to the exception handler. ```python SETUP_WITH(target) ``` -------------------------------- ### setup_scripts Source: https://devdocs.io/python~3.14/library/venv Installs activation scripts appropriate to the platform into the virtual environment. ```APIDOC ## setup_scripts(context) ### Description Installs activation scripts appropriate to the platform into the virtual environment. ### Method N/A (Function Call) ### Parameters * **context** (object) - Required - Context object for venv creation. ``` -------------------------------- ### Doctest with Leading Whitespace Source: https://devdocs.io/python~3.14/library/doctest Demonstrates that doctest handles examples with varying leading whitespace. The starting column of the example does not affect its execution, and leading whitespace in expected output is stripped accordingly. ```python >>> assert "Easy!" >>> import math >>> math.floor(1.9) 1 ``` -------------------------------- ### Config.site File Example Source: https://devdocs.io/python~3.14/using/configure Example content for a `config.site` file used for configure overrides during cross-compilation. ```bash # config.site-aarch64 ac_cv_buggy_getaddrinfo=no ac_cv_file__dev_ptmx=yes ac_cv_file__dev_ptc=no ``` -------------------------------- ### patch methods: start and stop Source: https://devdocs.io/python~3.14/library/unittest.mock All patchers have start() and stop() methods, which allow for manual control over patch lifecycles. This is useful for applying patches in setUp methods or when avoiding nested decorators/context managers. ```APIDOC ## patch methods: start and stop ### Description All the patchers have `start()` and `stop()` methods. These make it simpler to do patching in `setUp` methods or where you want to do multiple patches without nesting decorators or with statements. ### Usage Call `patch()`, `patch.object()`, or `patch.dict()` as normal and keep a reference to the returned `patcher` object. You can then call `start()` to put the patch in place and `stop()` to undo it. If you are using `patch()` to create a mock for you then it will be returned by the call to `patcher.start`. ```python >>> patcher = patch('package.module.ClassName') >>> from package import module >>> original = module.ClassName >>> new_mock = patcher.start() >>> assert module.ClassName is not original >>> assert module.ClassName is new_mock >>> patcher.stop() >>> assert module.ClassName is original >>> assert module.ClassName is not new_mock ``` ### Use in setUp/tearDown A typical use case is for doing multiple patches in the `setUp` method of a `TestCase`. ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher1 = patch('package.module.Class1') ... self.patcher2 = patch('package.module.Class2') ... self.MockClass1 = self.patcher1.start() ... self.MockClass2 = self.patcher2.start() ... ... def tearDown(self): ... self.patcher1.stop() ... self.patcher2.stop() ... ... def test_something(self): ... assert package.module.Class1 is self.MockClass1 ... assert package.module.Class2 is self.MockClass2 ... >>> MyTest('test_something').run() ``` ### Using addCleanup `unittest.TestCase.addCleanup()` can simplify managing patches, especially when exceptions might occur in `setUp`. ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... patcher = patch('package.module.Class') ... self.MockClass = patcher.start() ... self.addCleanup(patcher.stop) ... ... def test_something(self): ... assert package.module.Class is self.MockClass ... ``` ``` -------------------------------- ### Getting a String Input with getstr() Source: https://devdocs.io/python~3.14/howto/curses Use `getstr()` to read a line of text input. It supports basic editing with backspace and Enter. This example shows how to get a 15-character string from the top line of the screen. ```python curses.echo() # Enable echoing of characters # Get a 15-character string, with the cursor on the top line s = stdscr.getstr(0,0, 15) ``` -------------------------------- ### tracemalloc.get_traceback_limit() Source: https://devdocs.io/python~3.14/library/tracemalloc Gets the maximum number of frames stored in the traceback of a trace. This limit is set by the `start()` function. ```APIDOC ## tracemalloc.get_traceback_limit() ### Description Get the maximum number of frames stored in the traceback of a trace. The `tracemalloc` module must be tracing memory allocations to get the limit, otherwise an exception is raised. The limit is set by the `start()` function. ``` -------------------------------- ### Example Command Line for 'extend' Action Source: https://devdocs.io/python~3.14/library/optparse Demonstrates how multiple values can be passed to an 'extend' action, either as a comma-delimited string or as separate arguments. ```text --names=foo,bar --names blah --names ding,dong ``` -------------------------------- ### DST Start Transition Example Source: https://devdocs.io/python~3.14/library/datetime Demonstrates how UTC times are converted to local time across a DST start transition. Note how the hour '02:00:00' is skipped in local time and the timezone changes from EST to EDT. ```python >>> import datetime as dt >>> from tzinfo_examples import HOUR, Eastern >>> u0 = dt.datetime(2016, 3, 13, 5, tzinfo=dt.timezone.utc) >>> for i in range(4): ... u = u0 + i*HOUR ... t = u.astimezone(Eastern) ... print(u.time(), 'UTC =', t.time(), t.tzname()) ... ``` -------------------------------- ### setup_python Source: https://devdocs.io/python~3.14/library/venv Creates a copy or symlink to the Python executable in the virtual environment. ```APIDOC ## setup_python(context) ### Description Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable `python3.x` was used, symlinks to `python` and `python3` will be created pointing to that executable, unless files with those names already exist. ### Method N/A (Function Call) ### Parameters * **context** (object) - Required - Context object for venv creation. ``` -------------------------------- ### post_setup Source: https://devdocs.io/python~3.14/library/venv A placeholder method that can be overridden for post-creation steps like pre-installing packages. ```APIDOC ## post_setup(context) ### Description A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps. ### Method N/A (Function Call) ### Parameters * **context** (object) - Required - Context object for venv creation. ``` -------------------------------- ### Get Installation Prefix Source: https://devdocs.io/python~3.14/c-api/interp-lifecycle Retrieves the prefix for installed platform-independent files. This value is derived from the program name and environment variables. Returns NULL if called before Py_Initialize(). The returned string points into static storage and should not be modified. ```c wchar_t *Py_GetPrefix() ``` -------------------------------- ### Basic Client Usage Example Source: https://devdocs.io/python~3.14/library/xmlrpc.client Demonstrates how to create a ServerProxy and call a remote method. ```APIDOC ## Client Code Example ### Description This example shows a client connecting to an XML-RPC server and invoking a remote function. ### Code ```python import xmlrpc.client with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy: print("3 is even: %s" % str(proxy.is_even(3))) print("100 is even: %s" % str(proxy.is_even(100))) ``` ### Method `proxy.is_even(number)` ### Parameters #### Path Parameters - **number** (integer) - Required - The number to check for evenness. ### Response - **boolean** - True if the number is even, False otherwise. ``` -------------------------------- ### Certificate Chain Example Source: https://devdocs.io/python~3.14/library/ssl Concatenation of certificates forming a chain, starting with the specific certificate and ending with a self-signed root certificate. ```text -----BEGIN CERTIFICATE----- ... (certificate for your server)... -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- ... (the certificate for the CA)... -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- ... (the root certificate for the CA's issuer)... -----END CERTIFICATE----- ``` -------------------------------- ### Build System Configuration (setup.py) Source: https://devdocs.io/python~3.14/extending/newtypes_tutorial Configures the setup for building Python extensions, specifying the custom module and its source file. ```python from setuptools import Extension, setup setup(ext_modules=[Extension("custom", ["custom.c"])] ``` -------------------------------- ### Iterate with Index using enumerate Source: https://devdocs.io/python~3.14/library/functions Use enumerate to get both the index and value while iterating over a sequence. The starting index can be specified. ```python >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] ``` -------------------------------- ### Get available pip version Source: https://devdocs.io/python~3.14/library/ensurepip This function returns a string specifying the available version of pip that will be installed when bootstrapping an environment. ```python import ensurepip print(ensurepip.version()) ``` -------------------------------- ### Example Command-line Arguments Source: https://devdocs.io/python~3.14/library/optparse Demonstrates various equivalent ways users can invoke a script using options defined with optparse. This includes long and short options, merged short options, and options with or without arguments. ```bash --file=outfile -q ``` ```bash -f outfile --quiet ``` ```bash --quiet --file outfile ``` ```bash -q -foutfile ``` ```bash -qfoutfile ``` -------------------------------- ### Private Name Mangling Example Source: https://devdocs.io/python~3.14/reference/expressions Shows how identifiers starting with double underscores in a class definition are transformed to prevent naming conflicts. ```python The transformation rule is defined as follows: * The class name, with leading underscores removed and a single leading underscore inserted, is inserted in front of the identifier, e.g., the identifier `__spam` occurring in a class named `Foo`, `_Foo` or `__Foo` is transformed to `_Foo__spam`. * If the class name consists only of underscores, the transformation is the identity, e.g., the identifier `__spam` occurring in a class named `_` or `__` is left as is. ``` -------------------------------- ### curses.setupterm(term=None, fd=-1) Source: https://devdocs.io/python~3.14/library/curses Initializes the terminal, optionally specifying the terminal type and file descriptor. ```APIDOC ## curses.setupterm(term=None, fd=-1) ### Description Initialize the terminal. _term_ is a string giving the terminal name, or `None`; if omitted or `None`, the value of the `TERM` environment variable will be used. _fd_ is the file descriptor to which any initialization sequences will be sent; if not supplied or `-1`, the file descriptor for `sys.stdout` will be used. Raise a `curses.error` if the terminal could not be found or its terminfo database entry could not be read. If the terminal has already been initialized, this function has no effect. ### Method `curses.setupterm(term=None, fd=-1)` ### Parameters #### Path Parameters - **term** (str) - Optional - The terminal name. Defaults to the TERM environment variable. - **fd** (int) - Optional - The file descriptor for initialization sequences. Defaults to sys.stdout's file descriptor. ``` -------------------------------- ### Get Background Color Example Source: https://devdocs.io/python~3.14/library/turtle Demonstrates how to set and retrieve the background color of the TurtleScreen using string or RGB tuple inputs. ```python >>> screen.bgcolor("orange") >>> screen.bgcolor() "orange" >>> screen.bgcolor(0.5,0,0.5) >>> screen.bgcolor() "#800080" ``` -------------------------------- ### Get Symbol Table Line Number Source: https://devdocs.io/python~3.14/library/symtable The `get_lineno()` method returns the starting line number of the block associated with this symbol table. ```python get_lineno() ``` -------------------------------- ### Running the timeit Module Source: https://devdocs.io/python~3.14/using/cmdline This example demonstrates how to use the -m option to run the timeit module for benchmarking code. Use -h for detailed options. ```text python -m timeit -s "setup here" "benchmarked code here" ``` ```text python -m timeit -h # for details ``` -------------------------------- ### ThreadingUDPServer Example Source: https://devdocs.io/python~3.14/library/socketserver Demonstrates creating a ThreadingUDPServer by inheriting from ThreadingMixIn and UDPServer. The mix-in class should be listed first. ```python class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass ``` -------------------------------- ### Purge all managed Python runtimes Source: https://devdocs.io/python~3.14/using/windows Remove all runtimes managed by the Python install manager, including associated Start menu entries, registry keys, and download caches, by using the `--purge` option. This command does not affect runtimes installed manually. ```bash py uninstall [-y|--yes] --purge ``` -------------------------------- ### Basic ArgumentParser Setup Source: https://devdocs.io/python~3.14/howto/argparse Initializes an ArgumentParser and parses arguments. This basic setup provides a free --help option. ```python import argparse parser = argparse.ArgumentParser() parser.parse_args() ``` -------------------------------- ### List Slicing Examples Source: https://devdocs.io/python~3.14/reference/expressions Illustrates various ways to slice a list to extract sub-sequences, including start, stop, step, and omitting expressions. ```python >>> number_names = ['zero', 'one', 'two', 'three', 'four', 'five'] >>> number_names[1:3] ['one', 'two'] >>> number_names[1:] ['one', 'two', 'three', 'four', 'five'] >>> number_names[:3] ['zero', 'one', 'two'] >>> number_names[:] ['zero', 'one', 'two', 'three', 'four', 'five'] >>> number_names[::2] ['zero', 'two', 'four'] >>> number_names[:-3] ['zero', 'one', 'two'] ``` -------------------------------- ### Create and Write Configuration File Source: https://devdocs.io/python~3.14/library/configparser Demonstrates how to programmatically create a ConfigParser object, populate it with sections and key-value pairs, and write it to an INI file. ```python import configparser config = configparser.ConfigParser() config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['forge.example'] = {} config['forge.example']['User'] = 'hg' config['topsecret.server.example'] = {} topsecret = config['topsecret.server.example'] topsecret['Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile: config.write(configfile) ``` -------------------------------- ### Basic Process Creation and Execution Source: https://devdocs.io/python~3.14/library/multiprocessing Shows how to create a Process object, specify a target function and arguments, start the process, and wait for it to complete using join(). ```Python from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() ``` -------------------------------- ### Get Exec Prefix - C API Source: https://devdocs.io/python~3.14/c-api/interp-lifecycle Retrieves the exec-prefix for installed platform-dependent files. Should not be called before Py_Initialize(). Deprecated in favor of sys.base_exec_prefix and sys.exec_prefix. ```c wchar_t *Py_GetExecPrefix() _Part of the Stable ABI._ Return the _exec-prefix for installed platform-_dependent_ files. This is derived through a number of complicated rules from the program name set with `PyConfig.program_name` and some environment variables; for example, if the program name is `'/usr/local/bin/python'`, the exec-prefix is `'/usr/local'`. The returned string points into static storage; the caller should not modify its value. This corresponds to the **exec_prefix** variable in the top-level `Makefile` and the `--exec-prefix` argument to the **configure** script at build time. The value is available to Python code as `sys.base_exec_prefix`. It is only useful on Unix. Background: The exec-prefix differs from the prefix when platform dependent files (such as executables and shared libraries) are installed in a different directory tree. In a typical installation, platform dependent files may be installed in the `/usr/local/plat` subtree while platform independent may be installed in `/usr/local`. Generally speaking, a platform is a combination of hardware and software families, e.g. Sparc machines running the Solaris 2.x operating system are considered the same platform, but Intel machines running Solaris 2.x are another platform, and Intel machines running Linux are yet another platform. Different major revisions of the same operating system generally also form different platforms. Non-Unix operating systems are a different story; the installation strategies on those systems are so different that the prefix and exec-prefix are meaningless, and set to the empty string. Note that compiled Python bytecode files are platform independent (but not independent from the Python version by which they were compiled!). System administrators will know how to configure the **mount** or **automount** programs to share `/usr/local` between platforms while having `/usr/local/plat` be a different filesystem for each platform. This function should not be called before `Py_Initialize()`, otherwise it returns `NULL`. Changed in version 3.10: It now returns `NULL` if called before `Py_Initialize()`. Deprecated since version 3.13, will be removed in version 3.15: Use `PyConfig_Get("base_exec_prefix")` (`sys.base_exec_prefix`) instead. Use `PyConfig_Get("exec_prefix")` (`sys.exec_prefix`) if virtual environments need to be handled. ``` -------------------------------- ### Functional API with Whitespace-Separated Names Source: https://devdocs.io/python~3.14/howto/enum Example of defining enum members using a whitespace-separated string of names. Values will be auto-assigned integers starting from 1. ```python 'RED GREEN BLUE' ``` -------------------------------- ### Handler Configuration Example Source: https://devdocs.io/python~3.14/library/logging.config Demonstrates how to configure StreamHandler and RotatingFileHandler with specific levels, formatters, and other arguments. ```yaml handlers: console: class : logging.StreamHandler formatter: brief level : INFO filters: [allow_foo] stream : ext://sys.stdout file: class : logging.handlers.RotatingFileHandler formatter: precise filename: logconfig.log maxBytes: 1024 backupCount: 3 ``` -------------------------------- ### Functional API with Comma-Separated Names Source: https://devdocs.io/python~3.14/howto/enum Example of defining enum members using a comma-separated string of names. Values will be auto-assigned integers starting from 1. ```python 'RED,GREEN,BLUE' ``` -------------------------------- ### Basic INI Structure Example Source: https://devdocs.io/python~3.14/library/configparser Demonstrates simple key-value pairs, keys and values with spaces, and the use of ':' as a delimiter. ```ini [Simple Values] key=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values ``` -------------------------------- ### Get Resource Usage for Process Source: https://devdocs.io/python~3.14/library/resource Retrieves resource usage statistics for the calling process. This example demonstrates fetching usage after a sleep and after a CPU-bound task. ```python from resource import * import time # a non CPU-bound task time.sleep(3) print(getrusage(RUSAGE_SELF)) # a CPU-bound task for i in range(10 ** 8): _ = 1 + 1 print(getrusage(RUSAGE_SELF)) ``` -------------------------------- ### Example Class Hierarchy for MRO Calculation Source: https://devdocs.io/python~3.14/howto/mro Defines a class hierarchy used to illustrate MRO calculation. This setup is crucial for understanding the linearization process. ```python >>> O = object >>> class F(O): pass >>> class E(O): pass >>> class D(O): pass >>> class C(D,F): pass >>> class B(D,E): pass >>> class A(B,C): pass ``` -------------------------------- ### Multiprocessing Server Example Source: https://devdocs.io/python~3.14/library/multiprocessing Creates a listener with authentication, accepts a connection, and sends various data types to the client. Ensure the server address and authentication key match the client. ```python from multiprocessing.connection import Listener from array import array address = ('localhost', 6000) # family is deduced to be 'AF_INET' with Listener(address, authkey=b'secret password') as listener: with listener.accept() as conn: print('connection accepted from', listener.last_accepted) conn.send([2.25, None, 'junk', float]) conn.send_bytes(b'hello') conn.send_bytes(array('i', [42, 1729])) ``` -------------------------------- ### Download and Build OpenSSL Source: https://devdocs.io/python~3.14/using/unix Steps to download, extract, configure, build, and install a custom version of OpenSSL. Ensure 'install_sw' is used to avoid overwriting 'openssl.cnf'. ```bash $ curl -O https://www.openssl.org/source/openssl-VERSION.tar.gz $ tar xzf openssl-VERSION $ pushd openssl-VERSION $ ./config \ --prefix=/usr/local/custom-openssl \ --libdir=lib \ --openssldir=/etc/ssl $ make -j1 depend $ make -j8 $ make install_sw $ popd ``` -------------------------------- ### Example DTrace output for Python script Source: https://devdocs.io/python~3.14/howto/instrumentation This is an example of the output generated by the DTrace script when tracing a Python script. It shows the timestamp, probe type, file, function name, and line number for each function entry and return event within the 'start' function's scope. ```text 156641360502280 function-entry:call_stack.py:start:23 156641360518804 function-entry: call_stack.py:function_1:1 156641360532797 function-entry: call_stack.py:function_3:9 156641360546807 function-return: call_stack.py:function_3:10 156641360563367 function-return: call_stack.py:function_1:2 156641360578365 function-entry: call_stack.py:function_2:5 156641360591757 function-entry: call_stack.py:function_1:1 156641360605556 function-entry: call_stack.py:function_3:9 156641360617482 function-return: call_stack.py:function_3:10 156641360629814 function-return: call_stack.py:function_1:2 156641360642285 function-return: call_stack.py:function_2:6 156641360656770 function-entry: call_stack.py:function_3:9 156641360669707 function-return: call_stack.py:function_3:10 156641360687853 function-entry: call_stack.py:function_4:13 156641360700719 function-return: call_stack.py:function_4:14 156641360719640 function-entry: call_stack.py:function_5:18 156641360732567 function-return: call_stack.py:function_5:21 156641360747370 function-return:call_stack.py:start:28 ``` -------------------------------- ### Logging Configuration Server Example Source: https://devdocs.io/python~3.14/howto/logging-cookbook This Python script sets up a logging configuration server that listens on a specified port for configuration updates. It logs messages at various levels in a loop until interrupted. ```python import logging import logging.config import time import os # read initial config file logging.config.fileConfig('logging.conf') # create and start listener on port 9999 t = logging.config.listen(9999) t.start() logger = logging.getLogger('simpleExample') try: # loop through logging calls to see the difference # new configurations make, until Ctrl+C is pressed while True: logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') time.sleep(5) except KeyboardInterrupt: # cleanup logging.config.stopListening() t.join() ``` -------------------------------- ### tracemalloc.start(nframe: int = 1) Source: https://devdocs.io/python~3.14/library/tracemalloc Starts tracing Python memory allocations by installing hooks. The `nframe` parameter limits the number of frames stored in each traceback (default is 1). ```APIDOC ## tracemalloc.start(nframe: int = 1) ### Description Start tracing Python memory allocations: install hooks on Python memory allocators. Collected tracebacks of traces will be limited to _nframe_ frames. By default, a trace of a memory block only stores the most recent frame: the limit is `1`. _nframe_ must be greater or equal to `1`. You can still read the original number of total frames that composed the traceback by looking at the `Traceback.total_nframe` attribute. Storing more than `1` frame is only useful to compute statistics grouped by `'traceback'` or to compute cumulative statistics: see the `Snapshot.compare_to()` and `Snapshot.statistics()` methods. Storing more frames increases the memory and CPU overhead of the `tracemalloc` module. Use the `get_tracemalloc_memory()` function to measure how much memory is used by the `tracemalloc` module. The `PYTHONTRACEMALLOC` environment variable (`PYTHONTRACEMALLOC=NFRAME`) and the `-X` `tracemalloc=NFRAME` command line option can be used to start tracing at startup. ### See Also `stop()`, `is_tracing()` and `get_traceback_limit()` functions. ``` -------------------------------- ### Multiprocessing Client Example Source: https://devdocs.io/python~3.14/library/multiprocessing Connects to a server using a specific address and authentication key, then receives and prints data. Verify the address and authentication key match the server. ```python from multiprocessing.connection import Client from array import array address = ('localhost', 6000) with Client(address, authkey=b'secret password') as conn: print(conn.recv()) print(conn.recv_bytes()) arr = array('i', [0, 0, 0, 0, 0]) print(conn.recv_bytes_into(arr)) print(arr) ``` -------------------------------- ### Manage multiple patches in unittest setUp and tearDown Source: https://devdocs.io/python~3.14/library/unittest.mock Demonstrates using `patcher.start()` and `patcher.stop()` within a `unittest.TestCase`'s `setUp` and `tearDown` methods to manage multiple patches. ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher1 = patch('package.module.Class1') ... self.patcher2 = patch('package.module.Class2') ... self.MockClass1 = self.patcher1.start() ... self.MockClass2 = self.patcher2.start() ... ... def tearDown(self): ... self.patcher1.stop() ... self.patcher2.stop() ... ... def test_something(self): ... assert package.module.Class1 is self.MockClass1 ... assert package.module.Class2 is self.MockClass2 ... >>> MyTest('test_something').run() ``` -------------------------------- ### Process Creation Error Example Source: https://devdocs.io/python~3.14/library/multiprocessing Demonstrates an AttributeError that can occur when a target function for a Process is defined in the main script and not an importable module, especially with 'spawn' or 'forkserver' start methods. ```python >>> import multiprocessing as mp >>> def knigit(): ... print("Ni!") ... >>> process = mp.Process(target=knigit) >>> process.start() >>> Traceback (most recent call last): File ".../multiprocessing/spawn.py", line ..., in spawn_main File ".../multiprocessing/spawn.py", line ..., in _main AttributeError: module '__main__' has no attribute 'knigit' >>> process ``` -------------------------------- ### Basic Unit Test Boilerplate Source: https://devdocs.io/python~3.14/library/test A standard structure for unit tests using the `unittest` module. Includes `setUp` and `tearDown` for test preparation and cleanup, and example test methods. ```python import unittest from test import support class MyTestCase1(unittest.TestCase): # Only use setUp() and tearDown() if necessary def setUp(self): ... code to execute in preparation for tests ... def tearDown(self): ... code to execute to clean up after tests ... def test_feature_one(self): # Test feature one. ... testing code ... def test_feature_two(self): # Test feature two. ... testing code ... ... more test methods ... class MyTestCase2(unittest.TestCase): ... same structure as MyTestCase1 ... ... more test classes ... if __name__ == '__main__': unittest.main() ``` -------------------------------- ### Process run() Method Example Source: https://devdocs.io/python~3.14/library/multiprocessing Illustrates the usage of the Process constructor with a target function and arguments, and how the run() method executes the target. Supports both list and tuple for args. ```python >>> from multiprocessing import Process >>> p = Process(target=print, args=[1]) >>> p.run() 1 >>> p = Process(target=print, args=(1,)) >>> p.run() 1 ``` -------------------------------- ### Get Global Monitoring Events Source: https://devdocs.io/python~3.14/library/sys.monitoring Retrieves the integer representing all currently active global events for a given tool ID. No setup is required beyond having a valid tool ID. ```python sys.monitoring.get_events(tool_id: int, /) → int ``` -------------------------------- ### Basic Schedular Usage Example Source: https://devdocs.io/python~3.14/library/sched Demonstrates how to create a scheduler instance, define event functions, and schedule events using `enter` and `enterabs`. Shows how events are executed based on time and priority, and how `run` executes the scheduled tasks. ```python import sched, time s = sched.scheduler(time.time, time.sleep) def print_time(a='default'): print("From print_time", time.time(), a) def print_some_times(): print(time.time()) s.enter(10, 1, print_time) s.enter(5, 2, print_time, argument=('positional',)) # despite having higher priority, 'keyword' runs after 'positional' as enter() is relative s.enter(5, 1, print_time, kwargs={'a': 'keyword'}) s.enterabs(1_650_000_000, 10, print_time, argument=("first enterabs",)) s.enterabs(1_650_000_000, 5, print_time, argument=("second enterabs",)) s.run() print(time.time()) print_some_times() ``` -------------------------------- ### Example CLI Application Output Source: https://devdocs.io/python~3.14/howto/logging-cookbook These examples demonstrate the output of the CLI application with different commands and arguments, showing how log messages are displayed based on the configured level. ```bash $ python app.py start foo INFO start Started the 'foo' service. ``` ```bash $ python app.py stop foo bar INFO stop Stopped the 'foo' and 'bar' services. ``` ```bash $ python app.py restart foo bar baz INFO restart Restarted the 'foo', 'bar' and 'baz' services. ``` -------------------------------- ### HTTP Server Avoiding KeyboardInterrupt Source: https://devdocs.io/python~3.14/library/signal This example shows an HTTP server that installs a custom SIGINT handler to gracefully shut down by sending a signal through a socket pair, rather than relying on KeyboardInterrupt. ```python import signal import socket from selectors import DefaultSelector, EVENT_READ from http.server import HTTPServer, SimpleHTTPRequestHandler interrupt_read, interrupt_write = socket.socketpair() def handler(signum, frame): print('Signal handler called with signal', signum) interrupt_write.send(b'\0') signal.signal(signal.SIGINT, handler) def serve_forever(httpd): sel = DefaultSelector() sel.register(interrupt_read, EVENT_READ) sel.register(httpd, EVENT_READ) while True: for key, _ in sel.select(): if key.fileobj == interrupt_read: interrupt_read.recv(1) return if key.fileobj == httpd: httpd.handle_request() print("Serving on port 8000") httpd = HTTPServer(('', 8000), SimpleHTTPRequestHandler) serve_forever(httpd) print("Shutdown...") ``` -------------------------------- ### Example: Programmatic Tracing and Reporting Source: https://devdocs.io/python~3.14/library/trace This example demonstrates initializing a Trace object, ignoring specific directories, running a command, and writing coverage results to the current directory. ```python import sys import trace # create a Trace object, telling it what to ignore, and whether to # do tracing or line-counting or both. tracer = trace.Trace( ignoredirs=[sys.prefix, sys.exec_prefix], trace=0, count=1) # run the new command using the given tracer tracer.run('main()') # make a report, placing output in the current directory r = tracer.results() r.write_results(show_missing=True, coverdir=".") ``` -------------------------------- ### Get slice indices (legacy) Source: https://devdocs.io/python~3.14/c-api/slice Retrieves start, stop, and step indices from a slice object for a sequence of a given length. Treats out-of-bounds indices as errors. This function is generally not recommended. ```c int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) ``` -------------------------------- ### Install Packages from requirements.txt Source: https://devdocs.io/python~3.14/tutorial/venv Installs all packages listed in a requirements file, ensuring the correct versions are set up. ```bash (tutorial-env) $ python -m pip install -r requirements.txt Collecting novas==3.1.1.3 (from -r requirements.txt (line 1)) ... Collecting numpy==1.9.2 (from -r requirements.txt (line 2)) ... Collecting requests==2.7.0 (from -r requirements.txt (line 3)) ... Installing collected packages: novas, numpy, requests Running setup.py install for novas Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0 ``` -------------------------------- ### Instantiate Pdb with Skip Pattern Source: https://devdocs.io/python~3.14/library/pdb Instantiates the Pdb debugger class, specifying a list of glob-style module name patterns to skip during stepping. This example shows how to skip modules starting with 'django.'. ```python import pdb pdb.Pdb(skip=['django.*']).set_trace() ``` -------------------------------- ### Dictionary Creation Examples Source: https://devdocs.io/python~3.14/library/stdtypes Illustrates multiple ways to create dictionaries, including using keyword arguments, literal syntax, the zip function, and from iterables. All examples result in an equivalent dictionary. ```python >>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> f = dict({'one': 1, 'three': 3}, two=2) >>> a == b == c == d == e == f True ``` -------------------------------- ### IDLE Shell Output Example Source: https://devdocs.io/python~3.14/library/idle Demonstrates how IDLE's Shell displays strings with special characters and escape codes. The output representation can vary based on the operating system and installed fonts. ```python >>> s = 'a\tb\x07<\x02><\r>\x08c\nd' # Enter 22 chars. >>> len(s) 14 >>> s # Display repr(s) 'a\tb\x07<\x02><\r>\x08c\nd' >>> print(s, end='') # Display s as is. # Result varies by OS and font. Try it. ``` -------------------------------- ### Finding Adverbs and Positions with re.finditer Source: https://devdocs.io/python~3.14/library/re Use re.finditer to get Match objects for all pattern occurrences, providing start and end positions along with the matched text. This is useful for detailed analysis of matches. ```python >>> text = "He was carefully disguised but captured quickly by police." >>> for m in re.finditer(r"\w+ly\b", text): ... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) 07-16: carefully 40-47: quickly ``` -------------------------------- ### Timeit Command-Line Option: Setup Statement Source: https://devdocs.io/python~3.14/library/timeit Provide a statement to be executed once initially before timing begins. The default setup is 'pass'. ```bash -s S, --setup=S ``` -------------------------------- ### Basic asyncio Hello World Source: https://devdocs.io/python~3.14/library/asyncio A simple example demonstrating the basic usage of asyncio to print messages with a delay. ```python import asyncio async def main(): print('Hello ...') await asyncio.sleep(1) print('... World!') asyncio.run(main()) ```