### Example: Install Python 2.5.1 on OpenBSD i386 Source: https://docs.python.org/3.11/using/unix.html An example demonstrating how to install Python 2.5.1 for i386 architecture on OpenBSD from a specific FTP path. ```shell pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz ``` -------------------------------- ### Run XML-RPC server from command line Source: https://docs.python.org/3.11/library/xmlrpc.server.html Start the example XML-RPC server module directly from the command line. ```bash python -m xmlrpc.server ``` -------------------------------- ### Run XML-RPC client from command line Source: https://docs.python.org/3.11/library/xmlrpc.server.html Start the example XML-RPC client module directly from the command line to interact with a running server. ```bash python -m xmlrpc.client ``` -------------------------------- ### Install Scripts with Distutils setup() Source: https://docs.python.org/3.11/distutils/setupscript.html Use the `scripts` keyword argument in `distutils.core.setup()` to specify a list of script files to be installed. Distutils will adjust the shebang line for Python scripts. ```python setup(..., scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val'] ) ``` -------------------------------- ### Get resource file contents with pkgutil.get_data() Source: https://docs.python.org/3.11/whatsnew/2.6.html The `pkgutil.get_data()` function retrieves the contents of resource files included with an installed Python package. This example shows how to get 'exception_hierarchy.txt' from the 'test' package. ```python import pkgutil print pkgutil.get_data('test', 'exception_hierarchy.txt') ``` -------------------------------- ### setup.py for C Extension Modules Source: https://docs.python.org/3.11/whatsnew/2.0.html Complex setup.py example for distributing C extensions with macro definitions, include directories, and source files. Required when packaging compiled C modules like the PyXML parser. ```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 ] ) ``` -------------------------------- ### Displaying build_ext Command Options Source: https://docs.python.org/3.11/distutils/configfile.html Shows how to use the `--help` option with `setup.py` to list available options for a specific Distutils command, such as `build_ext`. ```bash $ python setup.py --help build_ext [...] Options for 'build_ext' command: --build-lib (-b) directory for compiled extension modules --build-temp (-t) directory for temporary files (build by-products) --inplace (-i) ignore build-lib and put compiled extensions into the source directory alongside your pure Python modules --include-dirs (-I) list of directories to search for header files --define (-D) C preprocessor macros to define --undef (-U) C preprocessor macros to undefine --swig-opts list of SWIG command line options [...] ``` -------------------------------- ### Get Unicode Exception Start Index Source: https://docs.python.org/3.11/c-api/exceptions.html Retrieves the start attribute from a Unicode exception object. These functions are part of the Stable ABI. ```APIDOC ## PyUnicodeDecodeError_GetStart / PyUnicodeEncodeError_GetStart / PyUnicodeTranslateError_GetStart ### Description Get the _start_ attribute of the given exception object and place it into _*start_. _start_ must not be `NULL`. These functions are part of the Stable ABI. ### Parameters #### Function Parameters - **exc** (PyObject *) - Required - The exception object. - **start** (Py_ssize_t *) - Required - Pointer to a `Py_ssize_t` where the start attribute will be stored. Must not be `NULL`. ### Return Value #### Success Response - **int** - `0` on success. #### Error Response - **int** - `-1` on failure. ``` -------------------------------- ### Using patcher start and stop in unittest.TestCase Source: https://docs.python.org/3.11/library/unittest.mock.html Manage multiple patches across test methods by starting them in setUp and stopping them in tearDown. ```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() ``` -------------------------------- ### Linking with Math Library in Setup File Source: https://docs.python.org/3.11/install/index.html Shows how to link the 'foo' module with the math library (`libm.a`) by adding the `-lm` flag to its definition in the `Setup` file. ```text foo foomodule.c -lm ``` -------------------------------- ### Get version string for installed package Source: https://docs.python.org/3.11/library/importlib.metadata.html Import the version function from importlib.metadata and retrieve the version string for an installed distribution package. Requires the package to be installed via pip or similar tools. ```python from importlib.metadata import version version('wheel') ``` -------------------------------- ### Setup File Line Structure Source: https://docs.python.org/3.11/install/index.html Describes the general syntax for defining a single extension module within a `Setup` file, including module name, source files, C preprocessor arguments, and libraries. ```text module ... [sourcefile ...] [cpparg ...] [library ...] ``` -------------------------------- ### PyOS_InitInterrupts() - Removed Function Source: https://docs.python.org/3.11/whatsnew/changelog.html The undocumented PyOS_InitInterrupts() function has been removed. Signal handlers are now implicitly installed during Python initialization. ```APIDOC ## PyOS_InitInterrupts() - Removed ### Description The undocumented PyOS_InitInterrupts() function has been removed from the C API. ### Reason for Removal - Signal handlers are now implicitly installed during Py_Initialize() - Explicit initialization is no longer necessary - Simplifies initialization process ### Migration Instead of calling PyOS_InitInterrupts(), configure signal handler installation via PyConfig: ```c PyConfig config; PyConfig_InitPythonConfig(&config); config.install_signal_handlers = 1; // Enable signal handlers Py_InitializeFromConfig(&config); ``` ### Configuration Option - **PyConfig.install_signal_handlers** - Controls whether signal handlers are installed - Default: 1 (enabled) - Set to 0 to disable signal handler installation ### Notes - bpo-41713: Removed in Python 3.11 by Victor Stinner - Signal handlers are installed automatically - Use PyConfig for signal handler configuration ``` -------------------------------- ### Example compiler and linker commands for Unix Source: https://docs.python.org/3.11/extending/building.html Demonstration of how distutils translates setup.py arguments into system-level compiler and linker invocations. ```shell gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/local/include -I/usr/local/include/python2.2 -c demo.c -o build/temp.linux-i686-2.2/demo.o gcc -shared build/temp.linux-i686-2.2/demo.o -L/usr/local/lib -ltcl83 -o build/lib.linux-i686-2.2/demo.so ``` -------------------------------- ### Using enumerate() with default and custom start index Source: https://docs.python.org/3.11/library/functions.html Illustrates how to use enumerate() to get an iterator of (index, value) pairs, demonstrating both the default starting index of 0 and a custom starting index. ```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 /distutils/sysconfig/get_python_lib Source: https://docs.python.org/3.11/distutils/apiref.html Returns the directory for general or platform-dependent library installation. ```APIDOC ## GET distutils.sysconfig.get_python_lib\n\n### Description\nReturn the directory for either the general or platform-dependent library installation.\n\n### Method\nGET\n\n### Endpoint\ndistutils.sysconfig.get_python_lib(plat_specific=False, standard_lib=False, prefix=None)\n\n### Parameters\n#### Query Parameters\n- **plat_specific** (boolean) - Optional - If true, the platform-dependent directory is returned.\n- **standard_lib** (boolean) - Optional - If true, the directory for the standard library is returned.\n- **prefix** (string) - Optional - Used as the prefix instead of the default PREFIX.\n\n### Response\n#### Success Response (200)\n- **path** (string) - The directory path for library installation. ``` -------------------------------- ### Basic Module Definition in Setup File Source: https://docs.python.org/3.11/install/index.html Illustrates a simple entry in a `Setup` file to define an extension module named 'foo' from a single C source file 'foomodule.c'. ```text foo foomodule.c ``` -------------------------------- ### Configure package metadata and dependencies in setup() Source: https://docs.python.org/3.11/whatsnew/2.5.html Use setup() keyword parameters requires, provides, obsoletes, and download_url to specify package dependencies and distribution location. This metadata is recorded in PKG-INFO when building source distributions. ```python VERSION = '1.0' setup(name='PyPackage', version=VERSION, requires=['numarray', 'zlib (>=1.1.4)'], obsoletes=['OldPackage'] download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz' % VERSION), ) ``` -------------------------------- ### Configure advanced C extensions with macros and libraries Source: https://docs.python.org/3.11/extending/building.html setup.py configuration including preprocessor defines, include paths, and external library links for complex builds. ```python from distutils.core import setup, Extension module1 = Extension('demo', define_macros = [('MAJOR_VERSION', '1'), ('MINOR_VERSION', '0')], include_dirs = ['/usr/local/include'], libraries = ['tcl83'], library_dirs = ['/usr/local/lib'], sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', author = 'Martin v. Loewis', author_email = 'martin@v.loewis.de', url = 'https://docs.python.org/extending/building', long_description = ''' This is really just a demo package. ''', ext_modules = [module1]) ``` -------------------------------- ### GET site.USER_SITE Source: https://docs.python.org/3.11/library/site.html Retrieves the path to the user-specific site-packages directory for the current Python installation. ```APIDOC ## GET site.USER_SITE ### Description Path to the user site-packages for the running Python. Can be `None` if `getusersitepackages()` hasn’t been called yet. Default value is `~/.local/lib/python_X.Y_/site-packages` for UNIX and non-framework macOS builds, `~/Library/Python/_X.Y_/lib/python/site-packages` for macOS framework builds, and `_%APPDATA%_\\Python\\Python_XY_\\site-packages` on Windows. This directory is a site directory, which means that `.pth` files in it will be processed. ### Method GET ### Endpoint site.USER_SITE ### Response #### Success Response (200) - **USER_SITE** (str or None) - Path to the user site-packages directory. #### Response Example "/home/user/.local/lib/python3.11/site-packages" ``` -------------------------------- ### tracemalloc.get_traceback_limit() Source: https://docs.python.org/3.11/library/tracemalloc.html 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. ```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. ### Function Signature `tracemalloc.get_traceback_limit()` ### Parameters (None) ### Returns `int` - The maximum number of frames. ``` -------------------------------- ### GET site.USER_BASE Source: https://docs.python.org/3.11/library/site.html Retrieves the path to the base directory for user site-packages, used by Distutils for user installation schemes. ```APIDOC ## GET site.USER_BASE ### Description Path to the base directory for the user site-packages. Can be `None` if `getuserbase()` hasn’t been called yet. Default value is `~/.local` for UNIX and macOS non-framework builds, `~/Library/Python/_X.Y_` for macOS framework builds, and `_%APPDATA%_\\Python` for Windows. This value is used by Distutils to compute the installation directories for scripts, data files, Python modules, etc. for the user installation scheme. See also `PYTHONUSERBASE`. ### Method GET ### Endpoint site.USER_BASE ### Response #### Success Response (200) - **USER_BASE** (str or None) - Path to the user base directory. #### Response Example "/home/user/.local" ``` -------------------------------- ### Configuring RPM Distribution Options in setup.cfg Source: https://docs.python.org/3.11/distutils/configfile.html Provides an example of setting multiple options for the `bdist_rpm` command in `setup.cfg`, including release number, packager, and a list of documentation files. ```ini [bdist_rpm] release = 1 packager = Greg Ward doc_files = CHANGES.txt README.txt USAGE.txt doc/ examples/ ``` -------------------------------- ### Create WSGI Application with Environment Setup Source: https://docs.python.org/3.11/library/wsgiref.html Demonstrates a basic WSGI application that uses setup_testing_defaults to populate the environ dictionary and returns formatted environment variables as HTTP response. Requires wsgiref.simple_server and wsgiref.util modules. ```python def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) ret = [("%s: %s\n" % (key, value)).encode("utf-8") for key, value in environ.items()] return ret ``` -------------------------------- ### _PyObject_FunctionStr() - Function String Representation Source: https://docs.python.org/3.11/whatsnew/changelog.html New function to get a user-friendly string representation of a function-like object. ```APIDOC ## _PyObject_FunctionStr() ### Description Get a user-friendly string representation of a function-like object. ### Method Function call ### Signature PyObject *_PyObject_FunctionStr(PyObject *func) ### Parameters - **func** (PyObject*) - Required - Function-like object ### Return Value - Returns a new string object with user-friendly representation - Returns NULL on error ### Use Cases - Error messages and debugging - User-friendly function identification - Logging and tracing ### Notes - Patch by Jeroen Demeyer - Improves error reporting in C extensions ``` -------------------------------- ### FUNCTION distutils.core.run_setup Source: https://docs.python.org/3.11/distutils/apiref.html Runs a setup script in a controlled environment and returns the Distribution instance that drives the process. ```APIDOC ## FUNCTION distutils.core.run_setup ### Description Run a setup script in a somewhat controlled environment, and return the distutils.dist.Distribution instance. ### Method Python Function ### Endpoint distutils.core.run_setup(script_name[, script_args=None, stop_after='run']) ### Parameters #### Path Parameters - **script_name** (string) - Required - File that will be read and run with exec() #### Query Parameters - **script_args** (list of strings) - Optional - Arguments to supply to the setup script; replaces sys.argv[1:] - **stop_after** (string) - Optional - When to stop processing. Values: 'init', 'config', 'commandline', 'run' (default) ### Response #### Success Response (200) - **Distribution** (object) - The Distribution instance that drives the setup process ``` -------------------------------- ### Create and start a simple Process Source: https://docs.python.org/3.11/library/multiprocessing.html Basic example of spawning a single process with a target function and arguments. The if __name__ == '__main__' guard is required to prevent recursive process spawning on Windows and spawn start methods. ```python from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() ``` -------------------------------- ### F-string = feature for debugging Source: https://docs.python.org/3.11/whatsnew/changelog.html The = specifier in f-strings outputs the expression text, an equals sign, and the repr of the value. Default conversion is !r unless a format spec is provided. Example: f'{3*9+15=}' produces '3*9+15=42'. ```python f'{3*9+15=}' ``` -------------------------------- ### Basic setup.cfg Configuration Syntax Source: https://docs.python.org/3.11/distutils/configfile.html Illustrates the fundamental structure for defining options within a `setup.cfg` file, where `[command]` specifies the Distutils command and `option=value` sets its parameters. ```ini [command] option=value ... ``` -------------------------------- ### Python range Examples with Different Arguments Source: https://docs.python.org/3.11/library/stdtypes.html These examples demonstrate how to create `range` objects using various combinations of `start`, `stop`, and `step` arguments. Converting them to lists helps visualize the sequence of numbers generated by each `range`. ```Python >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> list(range(0, 30, 5)) [0, 5, 10, 15, 20, 25] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(0, -10, -1)) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] >>> list(range(0)) [] >>> list(range(1, 0)) [] ``` -------------------------------- ### Import and use spam module in Python Source: https://docs.python.org/3.11/extending/extending.html Example of calling the wrapped C function from Python after the extension module is built and installed. ```python >>> import spam >>> status = spam.system("ls -l") ``` -------------------------------- ### Build Command with Configuration File Equivalent Source: https://docs.python.org/3.11/install/index.html Command-line equivalent of the build configuration file example. Running this command executes the build, whereas config file entries only apply if the command is run. ```bash python setup.py build --build-base=blib --force ``` -------------------------------- ### Basic Hello World with asyncio.run Source: https://docs.python.org/3.11/library/asyncio.html Demonstrates the standard way to run a top-level entry point for an asyncio program using the run() function. ```python import asyncio async def main(): print('Hello ...') await asyncio.sleep(1) print('... World!') asyncio.run(main()) ``` -------------------------------- ### GET entry_points() Source: https://docs.python.org/3.11/library/importlib.metadata.html Returns a collection of entry points from installed packages. Entry points allow for extensible functionality across different distributions. ```APIDOC ## GET entry_points() ### Description Returns a collection of entry points. Entry points are represented by EntryPoint instances; each EntryPoint has .name, .group, and .value attributes and a .load() method to resolve the value. ### Method FUNCTION ### Endpoint importlib.metadata.entry_points(**kwargs) ### Parameters #### Query Parameters - **group** (string) - Optional - Filter entry points by group (e.g., 'console_scripts'). - **name** (string) - Optional - Filter entry points by name. ### Request Example entry_points(group='console_scripts', name='wheel') ### Response #### Success Response (200) - **EntryPoints** (Collection) - A collection of EntryPoint objects with name, group, and value attributes. #### Response Example EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts') ``` -------------------------------- ### Command-line execution examples Source: https://docs.python.org/3.11/library/argparse.html Demonstration of running prog.py with different argument combinations: finding the max of integers (default behavior) and summing integers with the --sum flag. ```text $ python prog.py 1 2 3 4 4 ``` ```text $ python prog.py 1 2 3 4 --sum 10 ``` -------------------------------- ### Basic setup.py for package metadata check Source: https://docs.python.org/3.11/distutils/examples.html Defines a minimal `setup.py` script with only a package name, used to illustrate missing metadata warnings when running the `check` command. ```python from distutils.core import setup setup(name='foobar') ``` -------------------------------- ### urllib.request.install_opener Source: https://docs.python.org/3.11/library/urllib.request.html Installs an `OpenerDirector` instance as the default global opener. This is used to customize how `urlopen` behaves globally, for example, to add proxy handling or authentication. ```APIDOC ## `urllib.request.install_opener` ### Description Install an `OpenerDirector` instance as the default global opener. Installing an opener is only necessary if you want `urlopen` to use that opener; otherwise, simply call `OpenerDirector.open()` instead of `urlopen()`. ### Parameters - **_opener_** (OpenerDirector instance or compatible) - Required - An `OpenerDirector` instance or any class with the appropriate interface. ### Returns - None (modifies global state). ### Example Usage ```python import urllib.request # Create a custom opener with a proxy handler proxy_handler = urllib.request.ProxyHandler({'http': 'http://proxy.example.com:8080'}) opener = urllib.request.build_opener(proxy_handler) # Install the custom opener globally urllib.request.install_opener(opener) # Now, urllib.request.urlopen will use the installed proxy try: with urllib.request.urlopen('http://www.example.com') as response: print(f"Successfully opened URL via proxy: {response.status}") except urllib.error.URLError as e: print(f"Error opening URL via proxy: {e.reason}") ``` ``` -------------------------------- ### Get distribution package requirements Source: https://docs.python.org/3.11/library/importlib.metadata.html Use requires() to retrieve the full set of dependencies and requirements for an installed distribution package, including conditional extras. ```python >>> requires('wheel') ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"] ``` -------------------------------- ### Build the extension module using setup.py Source: https://docs.python.org/3.11/extending/building.html Command to compile the C source and generate the shared object or DLL in the build directory. ```shell python setup.py build ``` -------------------------------- ### Complete script for custom logging handler Source: https://docs.python.org/3.11/howto/logging-cookbook.html A working example script named chowntest.py that integrates the factory function and dictConfig for a complete logging setup. ```python import logging, logging.config, os, shutil def owned_file_handler(filename, mode='a', encoding=None, owner=None): if owner: if not os.path.exists(filename): open(filename, 'a').close() shutil.chown(filename, *owner) return logging.FileHandler(filename, mode, encoding) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { 'file':{ # The values below are popped from this dictionary and # used to create the handler, set the handler's level and # its formatter. '()': owned_file_handler, 'level':'DEBUG', 'formatter': 'default', # The values below are passed to the handler creator callable # as keyword arguments. 'owner': ['pulse', 'pulse'], 'filename': 'chowntest.log', 'mode': 'w', 'encoding': 'utf-8', }, }, 'root': { 'handlers': ['file'], 'level': 'DEBUG', }, } logging.config.dictConfig(LOGGING) logger = logging.getLogger('mylogger') logger.debug('A debug message') ``` -------------------------------- ### Complete setup script for a single C extension (Python Distutils) Source: https://docs.python.org/3.11/distutils/setupscript.html This is a full `setup.py` script for a distribution containing only a single C extension module. It imports `setup` and `Extension` from `distutils.core` and defines the extension. ```python from distutils.core import setup, Extension setup(name='foo', version='1.0', ext_modules=[Extension('foo', ['foo.c'])], ) ``` -------------------------------- ### Start an HTTP server for documentation Source: https://docs.python.org/3.11/library/pydoc.html Run this command to start an HTTP server on a specified port (e.g., 1234) to browse documentation in a web browser. Port 0 selects an arbitrary unused port. ```bash python -m pydoc -p 1234 ``` -------------------------------- ### version() - Get Package Version Source: https://docs.python.org/3.11/library/importlib.metadata.html Retrieves the version string for an installed distribution package. This is a simple functional API call that returns the version number as a string. ```APIDOC ## version() ### Description Retrieve the version string for a distribution package. ### Function Signature ```python version(distribution_name: str) -> str ``` ### Parameters - **distribution_name** (str) - Required - The name of the installed distribution package ### Returns - (str) - The version string of the distribution package ### Example ```python from importlib.metadata import version version('wheel') # Returns: '0.32.3' ``` ``` -------------------------------- ### Define a basic C extension in setup.py Source: https://docs.python.org/3.11/extending/building.html Minimal configuration for building a single-source C extension module using the Extension class. ```python from distutils.core import setup, Extension module1 = Extension('demo', sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [module1]) ``` -------------------------------- ### Floor division and modulo operators Source: https://docs.python.org/3.11/tutorial/introduction.html Use // for floor division to get an integer result and % to find the remainder. The example also shows how to reconstruct the original number. ```python >>> 17 / 3 # classic division returns a float 5.666666666666667 >>> >>> 17 // 3 # floor division discards the fractional part 5 >>> 17 % 3 # the % operator returns the remainder of the division 2 >>> 5 * 3 + 2 # floored quotient * divisor + remainder 17 ``` -------------------------------- ### Handling Hashes in Multiline Config Values Source: https://docs.python.org/3.11/library/configparser.html Demonstrates that hashes are preserved as literal text when not at the start of a line. This example shows the retrieval of a shebang string from a configuration object. ```python ... interpolation not necessary = if # is not at line start ... even in multiline values = line #1 ... line #2 ... line #3 ... ") >>> print(parser['hashes']['shebang']) #!/usr/bin/env python ``` -------------------------------- ### EnvBuilder.setup_scripts() Source: https://docs.python.org/3.11/library/venv.html Installs activation scripts appropriate to the platform into the virtual environment. These scripts enable users to activate the virtual environment. ```APIDOC ## setup_scripts(_context_) ### Description Installs activation scripts appropriate to the platform into the virtual environment. ### Method Instance method of EnvBuilder class ### Parameters #### Context Parameter - **_context_** (Context object) - Required - The context object containing environment configuration details ``` -------------------------------- ### Display Directory Structure with tree Source: https://docs.python.org/3.11/library/shutil.html This command-line snippet uses the `tree` utility to display the directory structure of a temporary folder, illustrating the setup for the `base_dir` archiving example. ```bash $ tree tmp ``` -------------------------------- ### Get Distribution instance for a package Source: https://docs.python.org/3.11/library/importlib.metadata.html Import and instantiate a Distribution object to access detailed metadata for an installed package. This provides an alternative to convenience functions for advanced use cases. ```python >>> from importlib.metadata import distribution >>> dist = distribution('wheel') ``` -------------------------------- ### Parsing Command Line with 'store' Action Source: https://docs.python.org/3.11/library/optparse.html Example command-line input showing how arguments are passed for options configured with the 'store' action. ```bash -f foo.txt -p 1 -3.5 4 -fbar.txt ``` -------------------------------- ### Example of fcntl.ioctl for getting process group Source: https://docs.python.org/3.11/library/fcntl.html This snippet demonstrates how to use `fcntl.ioctl` to retrieve the process group ID associated with a terminal, using both a string and a mutable buffer argument. ```python import array, fcntl, struct, termios, os os.getpgrp() struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, " "))[0] buf = array.array('h', [0]) fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1) buf ``` -------------------------------- ### GUIDES sqlite3/how-to Source: https://docs.python.org/3.11/library/sqlite3.html Practical guides for common tasks such as using placeholders and adapting custom types. ```APIDOC ## GUIDES sqlite3/how-to ### Description Detailed instructions on handling specific tasks and implementing custom logic with the sqlite3 module. ### Method N/A ### Endpoint sqlite3/how-to ### Parameters #### Guide Topics - **Placeholders** (Task) - How to use placeholders to bind values in SQL queries. - **Custom Types** (Task) - How to adapt custom Python types and register adapter callables. - **Converters** (Task) - How to convert SQLite values to custom Python types. - **Connection Shortcuts** (Task) - How to use connection shortcut methods. - **Context Manager** (Task) - How to use the connection context manager. - **SQLite URIs** (Task) - How to work with SQLite URIs. - **Row Factories** (Task) - How to create and use row factories. - **Encodings** (Task) - How to handle non-UTF-8 text encodings. - **Transaction control** (Explanation) - In-depth background on transaction control. ### Request Example # Refer to specific guides for implementation details. ### Response #### Success Response (200) - **Guides** (Documentation) - Instructional content for sqlite3 tasks. #### Response Example N/A ``` -------------------------------- ### Get relative path with os.path.relpath() Source: https://docs.python.org/3.11/whatsnew/2.6.html The new `os.path.relpath(path, start='.')` function calculates a relative path from a specified start path or the current working directory to a destination path. ```python os.path.relpath(path, start='.') ``` -------------------------------- ### Implementing an asyncio Server with serve_forever Source: https://docs.python.org/3.11/library/asyncio-eventloop.html Shows how to create and run an `asyncio` server using `asyncio.start_server()` and `srv.serve_forever()` to handle incoming client connections until cancelled. ```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)) ``` -------------------------------- ### Get Help for Build Command Options Source: https://docs.python.org/3.11/install/index.html Displays all available options for the build command. ```bash python setup.py build --help ``` -------------------------------- ### Get memory block traceback with Python tracemalloc Source: https://docs.python.org/3.11/library/tracemalloc.html Retrieve the traceback for the largest memory allocation by starting the tracer with a frame limit. Requires calling tracemalloc.start() before allocations occur. ```python import tracemalloc # Store 25 frames tracemalloc.start(25) # ... run your application ... snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('traceback') # pick the biggest memory block stat = top_stats[0] print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024)) for line in stat.traceback.format(): print(line) ``` ```text 903 memory blocks: 870.1 KiB File "", line 716 File "", line 1036 File "", line 934 File "", line 1068 File "", line 619 File "", line 1581 File "", line 1614 File "/usr/lib/python3.4/doctest.py", line 101 import pdb File "", line 284 File "", line 938 File "", line 1068 File "", line 619 File "", line 1581 File "", line 1614 File "/usr/lib/python3.4/test/support/__init__.py", line 1728 import doctest File "/usr/lib/python3.4/test/test_pickletools.py", line 21 support.run_doctest(pickletools) File "/usr/lib/python3.4/test/regrtest.py", line 1276 test_runner() File "/usr/lib/python3.4/test/regrtest.py", line 976 display_failure=not verbose) File "/usr/lib/python3.4/test/regrtest.py", line 761 match_tests=ns.match_tests) File "/usr/lib/python3.4/test/regrtest.py", line 1563 main() File "/usr/lib/python3.4/test/__main__.py", line 3 regrtest.main_in_temp_cwd() File "/usr/lib/python3.4/runpy.py", line 73 exec(code, run_globals) File "/usr/lib/python3.4/runpy.py", line 160 "__main__", fname, loader, pkg_name) ``` -------------------------------- ### Get server from BaseManager and serve forever Source: https://docs.python.org/3.11/library/multiprocessing.html Retrieve the underlying Server object from a BaseManager instance and start serving connections. The server listens on the specified address and authentication key. ```python >>> from multiprocessing.managers import BaseManager >>> manager = BaseManager(address=('', 50000), authkey=b'abc') >>> server = manager.get_server() >>> server.serve_forever() ``` -------------------------------- ### turtle.setup() Source: https://docs.python.org/3.11/library/turtle.html Sets the size and position of the main turtle graphics window. Parameters allow specifying dimensions in pixels or as a fraction of the screen, and initial coordinates. ```APIDOC ## turtle.setup() ### 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. ### Method N/A (Python function call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **_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) screen.setup(width=.75, height=0.5, startx=None, starty=None) ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Fetch and load PyPI project data Source: https://docs.python.org/3.11/library/pprint.html Imports required modules and retrieves project information from PyPI using urllib and json. This setup is used for all subsequent pp() examples. ```python >>> 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'] ``` -------------------------------- ### Define Distutils setup.py with Classifiers for PyPI Source: https://docs.python.org/3.11/whatsnew/2.3.html Example `setup.py` demonstrating how to add `classifiers` to package metadata for PyPI. This snippet ensures compatibility with older Distutils versions. ```python from distutils import core kw = {'name': "Quixote", 'version': "0.5.1", 'description': "A highly Pythonic Web application framework", # ... } if (hasattr(core, 'setup_keywords') and 'classifiers' in core.setup_keywords): kw['classifiers'] = \ ['Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: Developers'], core.setup(**kw) ``` -------------------------------- ### Managing Patches with setUp and tearDown in unittest Source: https://docs.python.org/3.11/library/unittest.mock-examples.html Shows how to manage patches using `patch.start()` in the `setUp` method and `patch.stop()` in the `tearDown` method for `unittest.TestCase`. ```python class MyTest(unittest.TestCase): def setUp(self): self.patcher = patch('mymodule.foo') self.mock_foo = self.patcher.start() def test_foo(self): self.assertIs(mymodule.foo, self.mock_foo) def tearDown(self): self.patcher.stop() MyTest('test_foo').run() ``` -------------------------------- ### Summarize IP Address Range with ipaddress.summarize_address_range Source: https://docs.python.org/3.11/library/ipaddress.html This example shows how to get an iterator of summarized network ranges between a first and last IP address. It requires `IPv4Address` or `IPv6Address` objects of the same version. ```python >>> [ipaddr for ipaddr in ipaddress.summarize_address_range( ... ipaddress.IPv4Address('192.0.2.0'), ... ipaddress.IPv4Address('192.0.2.130'))] [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')] ``` -------------------------------- ### Create a Listener server with authentication Source: https://docs.python.org/3.11/library/multiprocessing.html Sets up a server on localhost using a byte string authentication key. It demonstrates sending pickled objects and raw bytes to a connected 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])) ``` -------------------------------- ### Get a specific line from a file using linecache.getline Source: https://docs.python.org/3.11/library/linecache.html This example demonstrates how to use `linecache.getline` to retrieve a specific line from a Python file, in this case, the `linecache` module's own source file. ```python >>> import linecache >>> linecache.getline(linecache.__file__, 8) 'import sys\n' ``` -------------------------------- ### Various equivalent command-line option syntaxes Source: https://docs.python.org/3.11/library/optparse.html These examples illustrate different valid command-line syntaxes for specifying the same options, demonstrating `optparse`'s flexibility in parsing. ```shell -f outfile --quiet --quiet --file outfile -q -foutfile -qfoutfile ``` -------------------------------- ### Get distribution files with PackagePath objects Source: https://docs.python.org/3.11/library/importlib.metadata.html Use files() to retrieve all files installed by a distribution package. Each returned PackagePath object includes dist, size, and hash properties from metadata. ```python >>> util = [p for p in files('wheel') if 'util.py' in str(p)][0] >>> util PackagePath('wheel/util.py') >>> util.size 859 >>> util.dist >>> util.hash ```