### Basic Logging Setup with Custom Handler Source: https://docs.python.org/3/howto/logging-cookbook.html This example demonstrates the basic setup for a logging system within a Qt application. It initializes the application, sets up a root logger, and attaches a custom QtHandler to it. The handler is configured with a specific formatter to control the output format of log messages. ```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) if __name__=='__main__': main() ``` -------------------------------- ### Command-line Usage Example Source: https://docs.python.org/3/library/sysconfig.html Demonstrates how to use the sysconfig module from the command line to display platform, Python version, and the current installation scheme. ```bash python -m sysconfig ``` -------------------------------- ### Basic Qt GUI Logging Setup Source: https://docs.python.org/3/howto/logging-cookbook.html Initializes logging and imports necessary modules for a Qt GUI logging example. This includes logging, random, sys, and time. ```python import logging import random import sys import time ``` -------------------------------- ### Example Command Line Outputs (Default Log Level) Source: https://docs.python.org/3/howto/logging-cookbook.html Demonstrates the console output of start, stop, and restart commands at the default logging level (INFO). ```bash $ python app.py start foo INFO start Started the 'foo' service. $ python app.py stop foo bar INFO stop Stopped the 'foo' and 'bar' services. $ python app.py restart foo bar baz INFO restart Restarted the 'foo', 'bar' and 'baz' services. ``` -------------------------------- ### Using patch.start() and patch.stop() in setUp/tearDown Source: https://docs.python.org/3/library/unittest.mock-examples.html Manage patches manually using start() and stop() within setUp and tearDown methods. Ensure stop() is called to clean up the patch. ```python from unittest.mock import patch import unittest 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() ``` -------------------------------- ### Setup for New Custom Type Module Source: https://docs.python.org/3/extending/newtypes_tutorial.html Update the setup.py file to include a new extension module for the custom type, allowing it to be installed and imported. ```python from setuptools import Extension, setup setup(ext_modules=[ Extension("custom", ["custom.c"]), Extension("custom2", ["custom2.c"]), ]) ``` -------------------------------- ### Create a Socket Source: https://docs.python.org/3/howto/sockets.html This example demonstrates the basic steps to create a socket object. It's a fundamental starting point for network communication. ```Python import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("www.python.org", 80)) ``` -------------------------------- ### HTTPConnection.request (GET Example) Source: https://docs.python.org/3/library/http.client.html Example of making a GET request to the root path and retrieving the response. ```APIDOC ## HTTPConnection.request (GET Example) ### Description Example of making a GET request to the root path and retrieving the response. ### Method GET ### Endpoint / ### Request Example ```python import http.client conn = http.client.HTTPSConnection("www.python.org") conn.request("GET", "/") r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() conn.close() ``` ### Response #### Success Response (200) - **status** (int) - The HTTP status code. - **reason** (string) - The reason phrase for the status code. - **data** (bytes) - The response body. ``` -------------------------------- ### Multiple Patches in setUp and tearDown Source: https://docs.python.org/3/library/unittest.mock.html Manage multiple patches within a `unittest.TestCase` 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() ``` -------------------------------- ### Install a Package Source: https://docs.python.org/3/library/importlib.metadata.html Demonstrates the commands to create a virtual environment and install a package using pip. ```bash $ python -m venv example $ source example/bin/activate (example) $ python -m pip install wheel ``` -------------------------------- ### Install Python Source: https://docs.python.org/3/using/configure.html Builds the 'all' target and then installs Python to the system. ```make make install ``` -------------------------------- ### Install Specific Python Version on OpenBSD Source: https://docs.python.org/3/using/unix.html Example of installing a specific version (2.5.1) of Python on OpenBSD for i386 architecture. ```bash pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz ``` -------------------------------- ### Setup for C Extension Modules Source: https://docs.python.org/3/whatsnew/2.0.html This example demonstrates setting up a C extension module, including defining macros, include directories, and source files. It's suitable for complex extensions like those in the PyXML package. ```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 ] ) ``` -------------------------------- ### Get a Specific Installation Path Source: https://docs.python.org/3/library/sysconfig.html Retrieve a specific installation path by its name, optionally specifying a scheme, variables, or disabling path expansion. ```python sysconfig.get_path("stdlib") ``` -------------------------------- ### Distutils setup.py with Classifiers Source: https://docs.python.org/3/whatsnew/2.3.html Example setup.py file demonstrating the use of the optional 'classifiers' keyword argument for Distutils, compatible with older 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) ``` -------------------------------- ### Get All Installation Paths for a Scheme Source: https://docs.python.org/3/library/sysconfig.html Retrieve a dictionary of all installation paths for a given scheme. Paths can be expanded using provided variables or left unexpanded. ```python sysconfig.get_paths() ``` -------------------------------- ### Setting up a Custom Importer Source: https://docs.python.org/3/library/importlib.html This example shows the basic imports needed to begin setting up a custom importer, which involves managing both finder and loader aspects. ```Python import importlib.machinery import sys ``` -------------------------------- ### PyUnicodeDecodeError_GetStart / PyUnicodeEncodeError_GetStart / PyUnicodeTranslateError_GetStart Source: https://docs.python.org/3/c-api/exceptions.html Gets the start attribute of the exception object. The start attribute is clipped to [0, len(object) - 1] if the object is not empty. ```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`. Return `0` on success, `-1` on failure. If the `UnicodeError.object` is an empty sequence, the resulting _start_ is `0`. Otherwise, it is clipped to `[0, len(object) - 1]`. ### Signature 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) ``` -------------------------------- ### multiprocessing.get_start_method Source: https://docs.python.org/3/library/multiprocessing.html Gets the name of the currently used start method for processes. ```APIDOC ## multiprocessing.get_start_method ### Description Return the name of start method used for starting processes. If the global start method is not set and _allow_none_ is `False`, the global start method is set to the default, and its name is returned. ### Method GET ### Endpoint /multiprocessing/start_method ### Parameters #### Query Parameters - **allow_none** (boolean) - Optional - If true, allows the return value to be None. ### Returns - string: The name of the start method ('fork', 'spawn', 'forkserver', or None). ``` -------------------------------- ### Build System Configuration (setup.py) Source: https://docs.python.org/3/extending/newtypes_tutorial.html Configures the Python setup script to build the custom extension module. ```python from setuptools import Extension, setup setup(ext_modules=[Extension("custom", ["custom.c"])]) ``` -------------------------------- ### setup_scripts Source: https://docs.python.org/3/library/venv.html Installs activation scripts appropriate to the platform into the virtual environment. ```APIDOC ## setup_scripts ### Description Installs activation scripts appropriate to the platform into the virtual environment. ### Method N/A (Internal method) ### Parameters * `_context_` (object) - The context object for the environment creation. ``` -------------------------------- ### Perform GET Request with HTTPSConnection Source: https://docs.python.org/3/library/http.client.html Example of performing a GET request to a secure HTTPS URL using HTTPSConnection. Ensures the Host header is correctly set. ```python import http.client host = "docs.python.org" conn = http.client.HTTPSConnection(host) conn.request("GET", "/3/", headers={"Host": host}) response = conn.getresponse() print(response.status, response.reason) ``` -------------------------------- ### Flag Length Example Source: https://docs.python.org/3/library/enum.html Demonstrates how to get the number of members in a Flag enumeration. ```python from enum import Flag, auto class Color(Flag): RED = auto() GREEN = auto() BLUE = auto() white = Color.RED | Color.GREEN | Color.BLUE print(len(Color.GREEN)) print(len(white)) ``` -------------------------------- ### Python 3.10+ SyntaxError: Invalid Range Example Source: https://docs.python.org/3/whatsnew/changelog.html Demonstrates the SyntaxError for invalid ranges, as updated in Python 3.10+. This highlights a change in how invalid range specifications are handled. ```python >>> range(1, 0) SyntaxError: invalid range ``` -------------------------------- ### Basic Subcommand Setup with argparse Source: https://docs.python.org/3/library/argparse.html Demonstrates creating a top-level parser with subparsers for 'a' and 'b' commands, each with their own arguments. Shows how to parse arguments for these subcommands. ```python >>> # create the top-level parser >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('--foo', action='store_true', help='foo help') >>> subparsers = parser.add_subparsers(help='subcommand help') >>> >>> # create the parser for the "a" command >>> parser_a = subparsers.add_parser('a', help='a help') >>> parser_a.add_argument('bar', type=int, help='bar help') >>> >>> # create the parser for the "b" command >>> parser_b = subparsers.add_parser('b', help='b help') >>> parser_b.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz help') >>> >>> # parse some argument lists >>> parser.parse_args(['a', '12']) Namespace(bar=12, foo=False) >>> parser.parse_args(['--foo', 'b', '--baz', 'Z']) Namespace(baz='Z', foo=True) ``` -------------------------------- ### Globally Installing gettext for an Application Source: https://docs.python.org/3/library/gettext.html Install the gettext translation function globally for an application. This allows all files to use the '_' shortcut for translations without explicit setup in each file. ```python import gettext gettext.install('myapplication') ``` -------------------------------- ### DocTestParser Class Source: https://docs.python.org/3/library/doctest.html The DocTestParser class is responsible for extracting interactive examples from a string and creating DocTest objects. It provides methods to get doctests, examples, and parse strings. ```APIDOC ## class doctest.DocTestParser ### Description A processing class used to extract interactive examples from a string, and use them to create a `DocTest` object. ### Methods #### get_doctest(string, globs, name, filename, lineno) ##### Description Extract all doctest examples from the given string, and collect them into a `DocTest` object. ##### Parameters * **string** (str) - The string to parse for doctests. * **globs** (dict) - A dictionary of global variables for the `DocTest` object. * **name** (str) - The name for the `DocTest` object. * **filename** (str) - The filename associated with the doctest. * **lineno** (int) - The line number where the doctest starts. #### get_examples(string, name='') ##### Description Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based. ##### Parameters * **string** (str) - The string to parse for examples. * **name** (str) - Optional - A name identifying this string, used for error messages. Defaults to ''. #### parse(string, name='') ##### Description Divide the given string into examples and intervening text, and return them as a list of alternating `Example`s and strings. Line numbers for the `Example`s are 0-based. ##### Parameters * **string** (str) - The string to parse. * **name** (str) - Optional - A name identifying this string, used for error messages. Defaults to ''. ``` -------------------------------- ### Create and Write Configuration File Source: https://docs.python.org/3/library/configparser.html Demonstrates how to create a ConfigParser object, populate it with sections and key-value pairs, and write it to a 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) ``` -------------------------------- ### Error Handler Fix for Encoders Source: https://docs.python.org/3/whatsnew/changelog.html Crashes in built-in encoders with error handlers that return a position less than or equal to the starting position of non-encodable characters have been fixed. ```python Fix crashes in built-in encoders with error handlers that return position less or equal than the starting position of non-encodable characters. ``` -------------------------------- ### Basic Application Logging Setup Source: https://docs.python.org/3/library/logging.html This snippet shows how to set up basic logging for an application, including creating a logger, configuring basic logging to a file, and logging messages. ```python import logging import mylib logger = logging.getLogger(__name__) def main(): logging.basicConfig(filename='myapp.log', level=logging.INFO) logger.info('Started') mylib.do_something() logger.info('Finished') if __name__ == '__main__': main() ``` -------------------------------- ### Example: Getting Process Group ID with ioctl Source: https://docs.python.org/3/library/fcntl.html A practical example demonstrating how to retrieve the process group ID associated with a file descriptor using `fcntl.ioctl` and `termios.TIOCGPGRP`. ```python import array import fcntl import struct import termios import os # Get the current process group ID print(f"Current PGID: {os.getpgrp()}") # Use struct.unpack to get the PGID from a string buffer (less common) # The " " represents a buffer of 2 bytes, which might be sufficient for 'h' (short) # This is a simplified example and might not be robust across all systems. pgid_from_string = struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, " "))[0] print(f"PGID from string buffer: {pgid_from_string}") # Use array.array for a mutable buffer, which is the recommended approach buf = array.array('h', [0]) # 'h' for signed short, matching the expected return type fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1) print(f"PGID from array buffer: {buf[0]}") # Verify the result assert buf[0] == os.getpgrp() ``` -------------------------------- ### Running XML-RPC Server from Command Line Source: https://docs.python.org/3/library/xmlrpc.server.html Demonstrates how to start the built-in XML-RPC server directly from the command line without writing a separate Python script. This is a quick way to launch a basic server for testing. ```bash python -m xmlrpc.server ``` -------------------------------- ### Get Start Attribute of Unicode Error Source: https://docs.python.org/3/c-api/exceptions.html Retrieves the start attribute from a given Unicode exception object and stores it in the provided Py_ssize_t pointer. Returns 0 on success, -1 on failure. The start attribute is clipped to the valid range of the object. ```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) ``` -------------------------------- ### Install Setuptools in Virtual Environment Source: https://docs.python.org/3/library/venv.html Installs setuptools using a script from a URL and cleans up downloaded archives. This is part of extending the environment builder. ```python def install_setuptools(self, context): """ Install setuptools in the virtual environment. :param context: The information for the virtual environment creation request being processed. """ url = "https://bootstrap.pypa.io/ez_setup.py" self.install_script(context, 'setuptools', url) # clear up the setuptools archive which gets downloaded pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz') files = filter(pred, os.listdir(context.bin_path)) for f in files: f = os.path.join(context.bin_path, f) os.unlink(f) ``` -------------------------------- ### Get Preferred Installation Scheme Source: https://docs.python.org/3/library/sysconfig.html Retrieve the preferred scheme name for a given installation layout key ('prefix', 'home', or 'user'). The returned scheme can be used with other sysconfig functions. ```python sysconfig.get_preferred_scheme("prefix") ``` -------------------------------- ### Get Current First Weekday Source: https://docs.python.org/3/library/calendar.html Retrieves the current setting for the weekday that starts each week. ```python import calendar calendar.firstweekday() ``` -------------------------------- ### Access Distribution Version Source: https://docs.python.org/3/library/importlib.metadata.html Gets the version number of an installed distribution package from its Distribution instance. ```python >>> dist.version '0.32.3' ``` -------------------------------- ### Basic ArgumentParser Setup Source: https://docs.python.org/3/whatsnew/2.7.html Demonstrates how to set up an ArgumentParser for basic command-line argument parsing, including optional switches and positional arguments. Use this for new scripts requiring robust command-line interface handling. ```python import argparse parser = argparse.ArgumentParser(description='Command-line example.') # Add optional switches parser.add_argument('-v', action='store_true', dest='is_verbose', help='produce verbose output') parser.add_argument('-o', action='store', dest='output', metavar='FILE', help='direct output to FILE instead of stdout') parser.add_argument('-C', action='store', type=int, dest='context', metavar='NUM', default=0, help='display NUM lines of added context') # Allow any number of additional arguments. parser.add_argument(nargs='*', action='store', dest='inputs', help='input filenames (default is stdin)') args = parser.parse_args() print args.__dict__ ``` -------------------------------- ### Package Metadata with Distutils Source: https://docs.python.org/3/whatsnew/2.5.html Demonstrates the use of new keyword parameters in Distutils' setup() function for package metadata like dependencies and download URL. ```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), ) ``` -------------------------------- ### Get Package Version Source: https://docs.python.org/3/library/importlib.metadata.html Shows how to retrieve the version string of an installed package using importlib.metadata.version. ```python >>> from importlib.metadata import version >>> version('wheel') '0.32.3' ``` -------------------------------- ### concurrent.interpreters.get_main() Source: https://docs.python.org/3/library/concurrent.interpreters.html Gets the Interpreter object for the main interpreter, which is typically the one that started the script or REPL. ```APIDOC ## concurrent.interpreters.get_main() ### Description Return an `Interpreter` object for the main interpreter. This is the interpreter the runtime created to run the REPL or the script given at the command-line. It is usually the only one. ### Returns - `Interpreter` - The Interpreter object for the main interpreter. ``` -------------------------------- ### HTTPPasswordMgrWithDefaultRealm Example Source: https://docs.python.org/3/howto/urllib2.html Demonstrates setting up a password manager with a default username and password for a given URL. ```python password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() url = "http://example.com/some/path" password_mgr.add_password(None, url, "user", "password") # Create the opener that will use the password manager handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(handler) # Install the opener (optional, but convenient) urllib2.install_opener(opener) ``` -------------------------------- ### Example `.pth` file content Source: https://docs.python.org/3/library/site.html This is an example of a `.pth` file's content, specifying directories to be added to `sys.path`. Lines starting with `#` are comments, and blank lines are ignored. Non-existent paths are omitted. ```python # foo package configuration foo bar bletch ``` -------------------------------- ### Test Case with Multiple Test Methods Source: https://docs.python.org/3/library/unittest.html A `unittest.TestCase` subclass that includes multiple test methods, utilizing `setUp` for common setup. This example shows how to test different aspects of a widget's functionality. ```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), 'wrong size after resize') ``` -------------------------------- ### Example Command Line Usage Source: https://docs.python.org/3/library/optparse.html Illustrates how users can invoke a script configured with optparse. This shows a common way to pass options and arguments. ```bash --file=outfile -q ``` -------------------------------- ### Example Class Hierarchy Setup Source: https://docs.python.org/3/howto/mro.html Defines a sample class hierarchy for demonstrating the C3 MRO algorithm. ```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 ``` -------------------------------- ### setup_python Source: https://docs.python.org/3/library/venv.html Creates a copy or symlink to the Python executable in the virtual environment. ```APIDOC ## setup_python ### 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 (Internal method) ### Parameters * `_context_` (object) - The context object for the environment creation. ``` -------------------------------- ### tracemalloc.get_traceback_limit() Source: https://docs.python.org/3/library/tracemalloc.html Gets the maximum number of frames stored in the traceback of a trace. This limit is configured when starting tracemalloc. ```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. ``` -------------------------------- ### Demonstrate Valid Instance Creation Source: https://docs.python.org/3/howto/descriptor.html This example shows a successful instance creation when all provided inputs adhere to the defined validation rules. ```python >>> c = Component('WIDGET', 'metal', 5) # Allowed: The inputs are valid ``` -------------------------------- ### Get Symbol Table Line Number Source: https://docs.python.org/3/library/symtable.html Returns the starting line number of the block represented by the symbol table. ```python get_lineno() ``` -------------------------------- ### Initialize Python with Custom Configuration Source: https://docs.python.org/3/c-api/init_config.html Example of initializing Python with custom configuration, specifically enabling Python Development Mode. Returns -1 on error. ```c int init_python(void) { PyInitConfig *config = PyInitConfig_Create(); if (config == NULL) { printf("PYTHON INIT ERROR: memory allocation failed\n"); return -1; } // Enable the Python Development Mode if (PyInitConfig_SetInt(config, "dev_mode", 1) < 0) { goto error; } // Initialize Python with the configuration if (Py_InitializeFromInitConfig(config) < 0) { goto error; } PyInitConfig_Free(config); return 0; error: { // Display the error message. // // This uncommon braces style is used, because you cannot make // goto targets point to variable declarations. const char *err_msg; (void)PyInitConfig_GetError(config, &err_msg); printf("PYTHON INIT ERROR: %s\n", err_msg); PyInitConfig_Free(config); return -1; } } ``` -------------------------------- ### Get Distribution Files Source: https://docs.python.org/3/library/importlib.metadata.html Retrieves all files installed by a named distribution package. Each file is returned as a PackagePath object. ```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 ``` -------------------------------- ### post_setup Source: https://docs.python.org/3/library/venv.html A placeholder method that can be overridden to pre-install packages or perform other post-creation steps. ```APIDOC ## post_setup ### 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 (Internal method) ### Parameters * `_context_` (object) - The context object for the environment creation. ``` -------------------------------- ### Get Distribution Metadata Source: https://docs.python.org/3/library/importlib.metadata.html Retrieves the metadata for a specified installed distribution package. Raises PackageNotFoundError if the package is not found. ```python >>> wheel_metadata = metadata('wheel') ``` -------------------------------- ### Get Python Exec-Prefix C API Source: https://docs.python.org/3/c-api/interp-lifecycle.html Retrieves the exec-prefix for installed platform-dependent files. This function should not be called before Py_Initialize(). ```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. ``` -------------------------------- ### Defining Command-Line Options with optparse Source: https://docs.python.org/3/whatsnew/2.3.html Illustrates how to set up an OptionParser to define input and length options for a script. ```python import sys from optparse import OptionParser op = OptionParser() op.add_option('-i', '--input', action='store', type='string', dest='input', help='set input filename') op.add_option('-l', '--length', action='store', type='int', dest='length', help='set maximum length of output') ``` -------------------------------- ### bandclass/__main__.py Example Source: https://docs.python.org/3/library/__main__.html A sample `__main__.py` file for the 'bandclass' package, demonstrating how to handle command-line arguments and perform actions like searching for students. ```python # bandclass/__main__.py import sys from .student import search_students student_name = sys.argv[1] if len(sys.argv) >= 2 else '' print(f'Found student: {search_students(student_name)}') ``` -------------------------------- ### Get source lines and starting line number Source: https://docs.python.org/3/library/inspect.html Use `getsourcelines` to obtain a list of source code lines and the starting line number for an object. Raises `OSError` if source code retrieval fails and `TypeError` for built-in types. ```python inspect.getsourcelines(_object_) ``` -------------------------------- ### Configuring 'store' action options Source: https://docs.python.org/3/library/optparse.html Demonstrates how to configure options with the 'store' action, including specifying types, number of arguments, and destination. Shows how optparse parses command-line arguments based on these configurations. ```python parser.add_option("-f") parser.add_option("-p", type="float", nargs=3, dest="point") ``` ```python -f foo.txt -p 1 -3.5 4 -fbar.txt ``` ```python options.f = "foo.txt" options.point = (1.0, -3.5, 4.0) options.f = "bar.txt" ``` -------------------------------- ### Client-side ProtocolError Example Setup Source: https://docs.python.org/3/library/xmlrpc.client.html This client code snippet is intended to cause a ProtocolError by providing an invalid URI to the ServerProxy. ```python import xmlrpc.client ``` -------------------------------- ### Create and Run a Simple WSGI Server Source: https://docs.python.org/3/library/wsgiref.html This snippet demonstrates how to create a WSGI server instance using make_server, serve a demo application, and optionally handle 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() ``` -------------------------------- ### Get Distribution Version Source: https://docs.python.org/3/library/importlib.metadata.html Retrieves the version string for a specified installed distribution package. Raises PackageNotFoundError if the package is not found. ```python >>> version('wheel') '0.32.3' ``` -------------------------------- ### Usage Example for Fetch HTTP Headers Source: https://docs.python.org/3/library/asyncio-stream.html Demonstrates how to run the HTTP header fetching script with a URL argument. ```bash python example.py http://example.com/path/page.html ``` ```bash python example.py https://example.com/path/page.html ``` -------------------------------- ### FileConfig Formatters Section Example Source: https://docs.python.org/3/library/logging.config.html Defines the names of formatters to be configured in a fileConfig setup. This section lists various formatter names. ```ini [formatters] keys=form01,form02,form03,form04,form05,form06,form07,form08,form09 ``` -------------------------------- ### FileConfig Handlers Section Example Source: https://docs.python.org/3/library/logging.config.html Defines the names of handlers to be configured in a fileConfig setup. This section lists various handler names. ```ini [handlers] keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09 ``` -------------------------------- ### Instantiate ConfigParser with Defaults and Read File Source: https://docs.python.org/3/library/configparser.html Creates a ConfigParser instance with default values for 'bar' and 'baz', then reads configuration from 'example.cfg'. Demonstrates getting an option and removing options. ```python config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'}) config.read('example.cfg') print(config.get('Section1', 'foo')) # -> "Python is fun!" config.remove_option('Section1', 'bar') config.remove_option('Section1', 'baz') print(config.get('Section1', 'foo')) # -> "Life is hard!" ``` -------------------------------- ### Basic `optparse` Example Source: https://docs.python.org/3/library/optparse.html Demonstrates basic command-line option parsing using `optparse`. Non-option arguments are processed separately after option parsing. ```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) ```