### Example Python 2.5.1 Installation on OpenBSD i386 Source: https://github.com/python/cpython/blob/main/Doc/using/unix.rst This is an example command for installing Python 2.5.1 on an i386 OpenBSD system. ```sh pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz ``` -------------------------------- ### Setup Virtual Environment and Install Package Source: https://github.com/python/cpython/blob/main/Doc/library/importlib.metadata.rst Initializes a Python virtual environment and installs the 'wheel' distribution package using pip. This setup is a prerequisite for subsequent examples. ```shell-session $ python -m venv example $ source example/bin/activate (example) $ python -m pip install wheel ``` -------------------------------- ### Setup for Collections Module Examples Source: https://github.com/python/cpython/blob/main/Doc/library/collections.rst Imports all symbols from the `collections` module and `itertools` for subsequent examples. Sets `__name__` for doctest compatibility. ```python from collections import * import itertools __name__ = '' ``` -------------------------------- ### Setup Turtle for home Example in Python Source: https://github.com/python/cpython/blob/main/Doc/library/turtle.rst Sets the turtle's heading and position to prepare for demonstrating the `home()` function. ```python >>> turtle.setheading(90) >>> turtle.goto(0, -10) ``` -------------------------------- ### Setup Turtle for sety Example in Python Source: https://github.com/python/cpython/blob/main/Doc/library/turtle.rst Initializes the turtle's position to (0, 40) for subsequent `sety` demonstrations. ```python >>> turtle.goto(0, 40) ``` -------------------------------- ### Setup Turtle for setx Example in Python Source: https://github.com/python/cpython/blob/main/Doc/library/turtle.rst Initializes the turtle's position to (0, 240) for subsequent `setx` demonstrations. ```python >>> turtle.goto(0, 240) ``` -------------------------------- ### Example .start file for startup entry points Source: https://github.com/python/cpython/blob/main/Doc/library/site.rst This .start file defines an entry point pkg.mod:callable to be invoked at interpreter startup. The callable must be resolvable by pkgutil.resolve_name and take no arguments. ```text # foo package startup code foo.submod:initialize ``` -------------------------------- ### post_setup(context) Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst This is a placeholder method designed for third-party implementations to extend the virtual environment creation process, allowing for pre-installation of packages or other custom steps. ```APIDOC ## Method: 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. ### Signature `post_setup(self, context)` ### Arguments - **context** (types.SimpleNamespace) - Required - The context object for the virtual environment. ``` -------------------------------- ### Multiprocessing Process Failing with Spawn/Forkserver Source: https://github.com/python/cpython/blob/main/Doc/library/multiprocessing.rst This example shows a multiprocessing setup that will fail with a RuntimeError when using the 'spawn' or 'forkserver' start methods due to an unsafe main module import without proper entry point protection. ```python from multiprocessing import Process def foo(): print('hello') p = Process(target=foo) p.start() ``` -------------------------------- ### setup.py for C Extension Modules Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.0.rst Example of a setup.py script for building and distributing C extension modules. It defines the extension, including macros, include directories, and source files. ```python from distutils.core import setup, Extension expat_extension = Extension('xml.parsers.pyexpat', define_macros = [('XML_NS', None)], include_dirs = [ 'extensions/expat/xmltok', 'extensions/expat/xmlparse' ], sources = [ 'extensions/pyexpat.c', 'extensions/expat/xmltok/xmltok.c', 'extensions/expat/xmltok/xmlrole.c', ] ) setup (name = "PyXML", version = "0.5.4", ext_modules =[ expat_extension ] ) ``` -------------------------------- ### Generate a Random Even Integer within a Range in Python Source: https://github.com/python/cpython/blob/main/Doc/library/random.rst Use `randrange(start, stop, step)` to get a random integer from a specified range with a given step. This example generates an even integer between 0 and 100 inclusive. ```python >>> randrange(0, 101, 2) 26 ``` -------------------------------- ### setup_scripts(context) Source: https://github.com/python/cpython/blob/main/Doc/library/venv.rst This method installs the appropriate activation scripts for the platform into the virtual environment, allowing users to activate it. ```APIDOC ## Method: setup_scripts(context) ### Description Installs activation scripts appropriate to the platform into the virtual environment. ### Signature `setup_scripts(self, context)` ### Arguments - **context** (types.SimpleNamespace) - Required - The context object for the virtual environment. ``` -------------------------------- ### StartupState.process() Source: https://github.com/python/cpython/blob/main/Doc/library/site.rst Applies the accumulated state by first adding path extensions to `sys.path`, then executing `.start` file entry points and `.pth` file `import` lines. ```APIDOC ## StartupState.process() ### Description Apply the accumulated state by first adding the path extensions to `sys.path`, then executing the `.start` file entry points and `.pth` file `import` lines. This method is not idempotent and must not be called more than once on the same instance. ### Signature `process()` ### Parameters (None) ### Example ```python import site state = site.StartupState() state.addsitedir('/path/to/dir1') state.addsitedir('/path/to/dir2') state.process() ``` ``` -------------------------------- ### Indented Doctest Example Source: https://github.com/python/cpython/blob/main/Doc/library/doctest.rst This example illustrates that the starting column of doctest examples does not affect their execution. Leading whitespace from the expected output is stripped based on the indentation of the initial '>>>' line. ```python >>> assert "Easy!" >>> import math >>> math.floor(1.9) 1 ``` -------------------------------- ### window.insdelln(nlines) Source: https://github.com/python/cpython/blob/main/Doc/library/curses.rst Insert *nlines* lines into the specified window above the current line. The *nlines* bottom lines are lost. For negative *nlines*, delete *nlines* lines starting with the one under the cursor, and move the remaining lines up. The bottom *nlines* lines are cleared. The current cursor position remains the same. ```APIDOC ## Method: `window.insdelln(nlines)` ### Description Insert *nlines* lines into the specified window above the current line. The *nlines* bottom lines are lost. For negative *nlines*, delete *nlines* lines starting with the one under the cursor, and move the remaining lines up. The bottom *nlines* lines are cleared. The current cursor position remains the same. ### Parameters - **`nlines`** (`int`) - Required - The number of lines to insert or delete. ``` -------------------------------- ### setup.py for Python Packages Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/2.0.rst This script demonstrates how to define a setup.py for distributing software organized into packages and subpackages, specifying the package hierarchy. ```python from distutils.core import setup setup (name = "foo", version = "1.0", packages = ["package", "package.subpackage"]) ``` -------------------------------- ### window.overlay(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol]) Source: https://github.com/python/cpython/blob/main/Doc/library/curses.rst Overlay the window on top of *destwin*. The windows need not be the same size, only the overlapping region is copied. This copy is non-destructive, which means that the current background character does not overwrite the old contents of *destwin*. To get fine-grained control over the copied region, the second form of :meth:`overlay` can be used. *sminrow* and *smincol* are the upper-left coordinates of the source window, and the other variables mark a rectangle in the destination window. ```APIDOC ## window.overlay(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol]) ### Description Overlays the current window onto `destwin` non-destructively, copying only the overlapping region. Optional parameters allow fine-grained control over the source and destination regions. ### Method overlay ### Parameters #### Positional Parameters - **destwin** (window) - Required - The destination window to overlay onto. - **sminrow** (int) - Optional - Upper-left row coordinate of the source window region. - **smincol** (int) - Optional - Upper-left column coordinate of the source window region. - **dminrow** (int) - Optional - Upper-left row coordinate of the destination window region. - **dmincol** (int) - Optional - Upper-left column coordinate of the destination window region. - **dmaxrow** (int) - Optional - Lower-right row coordinate of the destination window region. - **dmaxcol** (int) - Optional - Lower-right column coordinate of the destination window region. ``` -------------------------------- ### Perform a GET Request with URL Parameters in Python Source: https://github.com/python/cpython/blob/main/Doc/library/urllib.request.rst This example demonstrates how to construct a URL with query parameters using `urllib.parse.urlencode` for a GET request. ```python >>> import urllib.request >>> import urllib.parse >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> url = "https://www.python.org/?%s" % params >>> with urllib.request.urlopen(url) as f: ... print(f.read().decode('utf-8')) ... ``` -------------------------------- ### Advanced Python Initialization with Custom Paths and Executable (C) Source: https://github.com/python/cpython/blob/main/Doc/c-api/init_config.rst This example shows how to initialize Python, read default configuration, and then override specific parameters like the program name, module search paths, and executable path. It highlights that some parameters are not calculated until initialization. ```C PyStatus init_python(const char *program_name) { PyStatus status; PyConfig config; PyConfig_InitPythonConfig(&config); /* Set the program name before reading the configuration (decode byte string from the locale encoding). Implicitly preinitialize Python. */ status = PyConfig_SetBytesString(&config, &config.program_name, program_name); if (PyStatus_Exception(status)) { goto done; } /* Read all configuration at once */ status = PyConfig_Read(&config); if (PyStatus_Exception(status)) { goto done; } /* Specify sys.path explicitly */ /* If you want to modify the default set of paths, finish initialization first and then use PySys_GetAttrString("path") */ config.module_search_paths_set = 1; status = PyWideStringList_Append(&config.module_search_paths, L"/path/to/stdlib"); if (PyStatus_Exception(status)) { goto done; } status = PyWideStringList_Append(&config.module_search_paths, L"/path/to/more/modules"); if (PyStatus_Exception(status)) { goto done; } /* Override executable computed by PyConfig_Read() */ status = PyConfig_SetString(&config, &config.executable, L"/path/to/my_executable"); if (PyStatus_Exception(status)) { goto done; } status = Py_InitializeFromConfig(&config); done: PyConfig_Clear(&config); return status; } ``` -------------------------------- ### int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) Source: https://github.com/python/cpython/blob/main/Doc/c-api/exceptions.rst Get the `start` attribute of the given Unicode exception object and store it in `*start`. Returns `0` on success, `-1` on failure. `start` must not be `NULL`. ```APIDOC ## int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) ## int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) ## int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) ### Description Get the *start* attribute of the given exception object and place it into `*start`. *start* must not be `NULL`. Return `0` on success, `-1` on failure. ### Parameters - **exc** (PyObject*) - Required - The Unicode exception object. - **start** (Py_ssize_t*) - Required - Pointer to store the start attribute. ### Returns int - `0` on success, `-1` on failure. ``` -------------------------------- ### Get Package Version with importlib.metadata Source: https://github.com/python/cpython/blob/main/Doc/library/importlib.metadata.rst Retrieves the version string of an installed distribution package using `importlib.metadata.version`. This requires the package to be installed in the current environment. ```pycon (example) $ python >>> from importlib.metadata import version # doctest: +SKIP >>> version('wheel') # doctest: +SKIP '0.32.3' ``` -------------------------------- ### StartupState.addusersitepackages() Source: https://github.com/python/cpython/blob/main/Doc/library/site.rst Accumulates startup data for the per-user site-packages directory, if enabled and existing, for later processing by the `process()` method. ```APIDOC ## StartupState.addusersitepackages() ### Description Add the per-user site-packages directory, if enabled and if it exists. The directory's startup data is accumulated for later processing by `process()`. ### Signature `addusersitepackages()` ### Parameters (None) ### Example ```python import site state = site.StartupState() state.addusersitepackages() state.process() ``` ``` -------------------------------- ### window.overwrite(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol]) Source: https://github.com/python/cpython/blob/main/Doc/library/curses.rst Overwrite the window on top of *destwin*. The windows need not be the same size, in which case only the overlapping region is copied. This copy is destructive, which means that the current background character overwrites the old contents of *destwin*. To get fine-grained control over the copied region, the second form of :meth:`overwrite` can be used. *sminrow* and *smincol* are the upper-left coordinates of the source window, the other variables mark a rectangle in the destination window. ```APIDOC ## window.overwrite(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol]) ### Description Overwrites the current window onto `destwin` destructively, copying only the overlapping region. Optional parameters allow fine-grained control over the source and destination regions. ### Method overwrite ### Parameters #### Positional Parameters - **destwin** (window) - Required - The destination window to overwrite onto. - **sminrow** (int) - Optional - Upper-left row coordinate of the source window region. - **smincol** (int) - Optional - Upper-left column coordinate of the source window region. - **dminrow** (int) - Optional - Upper-left row coordinate of the destination window region. - **dmincol** (int) - Optional - Upper-left column coordinate of the destination window region. - **dmaxrow** (int) - Optional - Lower-right row coordinate of the destination window region. - **dmaxcol** (int) - Optional - Lower-right column coordinate of the destination window region. ``` -------------------------------- ### Build Python Installer for Testing (Basic Options) Source: https://github.com/python/cpython/blob/main/Tools/msi/README.txt Use this batch script to build the Python installer for testing, specifying target architectures and optionally including documentation files. ```Batch build.bat [-x86] [-x64] [-ARM64] [--doc] ``` -------------------------------- ### Setup for TracebackException Examples in Python Source: https://github.com/python/cpython/blob/main/Doc/library/traceback.rst This setup code defines functions that raise an `IndexError` and demonstrates capturing both a single exception and a chained exception for further processing with `TracebackException`. ```python >>> import sys >>> from traceback import TracebackException >>> >>> def lumberjack(): ... bright_side_of_life() ... >>> def bright_side_of_life(): ... t = "bright", "side", "of", "life" ... return t[5] ... >>> try: ... lumberjack() ... except IndexError as e: ... exc = e ... >>> try: ... try: ... lumberjack() ... except: ... 1/0 ... except Exception as e: ... chained_exc = e ``` -------------------------------- ### Creating an Enum with a Custom Start Value Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/3.5.rst This example demonstrates how to create an `Enum` where the initial value for members is specified using the `start` parameter, useful for custom numbering schemes. ```python >>> Animal = enum.Enum('Animal', 'cat dog', start=10) >>> Animal.cat >>> Animal.dog ``` -------------------------------- ### window.getkey([y, x]) Source: https://github.com/python/cpython/blob/main/Doc/library/curses.rst Get a character, returning a string instead of an integer, as `getch` does. Function keys, keypad keys and other special keys return a multibyte string containing the key name. In no-delay mode, raise an exception if there is no input. ```APIDOC ## Method: `window.getkey([y, x])` ### Description Get a character, returning a string instead of an integer, as `getch` does. Function keys, keypad keys and other special keys return a multibyte string containing the key name. In no-delay mode, raise an exception if there is no input. ### Parameters - **`y`** (`int`) - Optional - The row coordinate. - **`x`** (`int`) - Optional - The column coordinate. ### Returns A `str` representing the character or key name. ``` -------------------------------- ### Main Application Entry Point with Logging and PyQt Source: https://github.com/python/cpython/blob/main/Doc/howto/logging-cookbook.rst Sets up the main thread name, configures the root logger level, initializes a PyQt application, and runs its event loop. ```python def main(): QtCore.QThread.currentThread().setObjectName('MainThread') logging.getLogger().setLevel(logging.DEBUG) app = QtWidgets.QApplication(sys.argv) example = Window(app) example.show() if hasattr(app, 'exec'): rc = app.exec() else: rc = app.exec_() sys.exit(rc) ``` -------------------------------- ### Get Python Interpreter Version String Example Source: https://github.com/python/cpython/blob/main/Doc/c-api/interp-lifecycle.rst This snippet shows an example of the string format returned by Py_GetVersion(), which provides the version of the Python interpreter along with build details. ```text "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]" ``` -------------------------------- ### StartupState.addsitepackages(prefixes=None) Source: https://github.com/python/cpython/blob/main/Doc/library/site.rst Accumulates startup data for global site-packages directories, computed from provided prefixes or global defaults, for later processing by the `process()` method. ```APIDOC ## StartupState.addsitepackages(prefixes=None) ### Description Add global site-packages directories, computed from *prefixes* or from the global `PREFIXES` when *prefixes* is `None`. Each directory's startup data is accumulated for later processing by `process()`. ### Signature `addsitepackages(prefixes=None)` ### Parameters - **prefixes** (list of str, optional) - A list of paths to use as prefixes for computing global site-packages directories. Defaults to `None`, using global `PREFIXES`. ### Example ```python import site state = site.StartupState() state.addsitepackages() state.process() ``` ``` -------------------------------- ### Accessing Package Metadata with importlib.metadata Source: https://github.com/python/cpython/blob/main/Doc/whatsnew/3.8.rst Use `importlib.metadata` to programmatically retrieve metadata from installed third-party packages, such as version numbers, required dependencies, and file lists. This example requires the 'requests' package to be installed. ```python # Note following example requires that the popular "requests" # package has been installed. from importlib.metadata import version, requires, files version('requests') '2.22.0' list(requires('requests')) ['chardet (<3.1.0,>=3.0.2)'] list(files('requests'))[:5] [PackagePath('requests-2.22.0.dist-info/INSTALLER'), PackagePath('requests-2.22.0.dist-info/LICENSE'), PackagePath('requests-2.22.0.dist-info/METADATA'), PackagePath('requests-2.22.0.dist-info/RECORD'), PackagePath('requests-2.22.0.dist-info/WHEEL')] ``` -------------------------------- ### Python islice Example Source: https://github.com/python/cpython/blob/main/Doc/library/itertools.rst Extracts elements from an iterable with a specified start, stop, and step using `islice`. ```python reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele'] for name in islice(reportlines, 3, None, 2): print(name.title()) ``` -------------------------------- ### unittest.TestCase with setUp Method for Test Setup Source: https://github.com/python/cpython/blob/main/Doc/library/unittest.rst Implement `setUp` to factor out repetitive setup code that needs to run before each test method in the `TestCase` subclass. ```python import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def test_default_widget_size(self): self.assertEqual(self.widget.size(), (50,50), 'incorrect default size') def test_widget_resize(self): self.widget.resize(100,150) self.assertEqual(self.widget.size(), (100,150), ``` -------------------------------- ### Unattend XML Configuration for Per-User Python Installation Source: https://github.com/python/cpython/blob/main/Doc/using/windows.rst This XML configuration file, unattend.xml, specifies options for a per-user Python installation, mirroring the simplified command-line example for personal use without the test suite. ```xml ``` -------------------------------- ### window.getch([y, x]) Source: https://github.com/python/cpython/blob/main/Doc/library/curses.rst Get a character. Note that the integer returned does not have to be in ASCII range: function keys, keypad keys and so on are represented by numbers higher than 255. In no-delay mode, return `-1` if there is no input, otherwise wait until a key is pressed. A multibyte character is returned as its encoded bytes one at a time; use `get_wch` to read it as a single character. ```APIDOC ## Method: `window.getch([y, x])` ### Description Get a character. Note that the integer returned does not have to be in ASCII range: function keys, keypad keys and so on are represented by numbers higher than 255. In no-delay mode, return `-1` if there is no input, otherwise wait until a key is pressed. A multibyte character is returned as its encoded bytes one at a time; use `get_wch` to read it as a single character. ### Parameters - **`y`** (`int`) - Optional - The row coordinate. - **`x`** (`int`) - Optional - The column coordinate. ### Returns An integer representing the character or key pressed. ``` -------------------------------- ### Create and run a simple WSGI HTTP server with make_server Source: https://github.com/python/cpython/blob/main/Doc/library/wsgiref.rst This example demonstrates how to create a WSGI server instance, bind it to a host and port, and serve a WSGI application indefinitely or for a single request. ```python from wsgiref.simple_server import make_server, demo_app with make_server('', 8000, demo_app) as httpd: print("Serving HTTP on port 8000...") # Respond to requests until process is killed httpd.serve_forever() # Alternative: serve one request, then exit httpd.handle_request() ``` -------------------------------- ### Perform GET Request with http.client Source: https://github.com/python/cpython/blob/main/Doc/library/http.client.rst Use http.client.HTTPSConnection to send a GET request, retrieve the response, and read data. Includes examples for reading entire content, reading in chunks, and handling 404 Not Found errors. ```python import http.client conn = http.client.HTTPSConnection("www.python.org") conn.request("GET", "/") r1 = conn.getresponse() print(r1.status, r1.reason) 200 OK data1 = r1.read() # This will return entire content. # The following example demonstrates reading data in chunks. conn.request("GET", "/") r1 = conn.getresponse() while chunk := r1.read(200): print(repr(chunk)) b'\n