### Installation path functions in sysconfig Source: https://devdocs.io/python~3.12/contents Demonstrates using sysconfig's path functions to get various installation directories. ```python import sysconfig # Get the installation prefix prefix = sysconfig.get_path('prefix') print(f"Installation prefix: {prefix}") # Get the script directory scripts_dir = sysconfig.get_path('scripts') print(f"Scripts directory: {scripts_dir}") ``` -------------------------------- ### Basic gettext Setup and Usage Source: https://devdocs.io/python~3.12/library/gettext This example demonstrates how to set up the gettext module for internationalization. It binds a text domain to a specific directory and aliases the `gettext` function to `_` for easier use. Ensure the specified directory contains the translated message catalogs. ```python import gettext gettext.bindtextdomain('myapplication', '/path/to/my/language/directory') gettext.textdomain('myapplication') _ = gettext.gettext # ... print(_('This is a translatable string.')) ``` -------------------------------- ### Install Python Source: https://devdocs.io/python~3.12/using/configure Builds Python and installs it to the configured installation prefix. ```makefile make install ``` -------------------------------- ### Installation paths with sysconfig Source: https://devdocs.io/python~3.12/contents Demonstrates how to retrieve installation paths using the sysconfig module. ```python import sysconfig # Get the installation scheme for the current platform scheme = sysconfig.get_default_scheme() # Get installation paths based on the scheme include_dir = sysconfig.get_path('include', scheme) stdlib_dir = sysconfig.get_path('stdlib', scheme) print(f"Include directory: {include_dir}") print(f"Standard library directory: {stdlib_dir}") ``` -------------------------------- ### Provide setup imports using setup parameter Source: https://devdocs.io/python~3.12/library/timeit To give timeit access to user-defined functions, use the setup parameter with an import statement from __main__. ```python def test(): """Stupid test function""" L = [i for i in range(100)] if __name__ == '__main__': import timeit print(timeit.timeit("test()", setup="from __main__ import test")) ``` -------------------------------- ### Example .pth file contents Source: https://devdocs.io/python~3.12/library/site Configuration files used to add directories to sys.path. Blank lines and comments are ignored, while lines starting with 'import' are executed. ```text # foo package configuration foo bar bletch ``` ```text # bar package configuration bar ``` -------------------------------- ### Start Command Implementation (start.py) Source: https://devdocs.io/python~3.12/howto/logging-cookbook Implements the 'start' subcommand for the CLI application. It logs debug and info messages related to starting a service. ```python # start.py import logging logger = logging.getLogger(__name__) def command(options): logger.debug('About to start %s', options.name) # actually do the command processing here ... logger.info('Started the \'%s\' service.', options.name) ``` -------------------------------- ### Compiler Command Examples Source: https://devdocs.io/python~3.12/using/configure Examples of compiler commands used in the build process. ```bash gcc -pthread ``` ```bash g++ -pthread ``` -------------------------------- ### Installing Python Modules Source: https://devdocs.io/python~3.12/contents Guidance on installing Python modules, including key terms, basic usage, common 'how-to' scenarios, and troubleshooting installation issues. ```APIDOC ## Installing Python Modules ### Description This section provides comprehensive instructions and advice for installing Python packages and modules, covering various scenarios and potential problems. ### Installation Guide - Key terms - Basic usage - How do I …? - … install `pip` in versions of Python prior to Python 3.4? - … install packages just for the current user? - … install scientific Python packages? - … work with multiple versions of Python installed in parallel? - Common installation issues - Installing into the system Python on Linux - Pip not installed - Installing binary extensions ``` -------------------------------- ### Unattended Installation Configuration Source: https://devdocs.io/python~3.12/using/windows This XML file configures unattended installation options, mirroring the command-line arguments. It sets up a per-user installation without the launcher or test suite, and includes a custom description for the simplified UI. ```xml ``` -------------------------------- ### POP3 Example Usage Source: https://devdocs.io/python~3.12/library/poplib A minimal example demonstrating how to connect to a POP3 server, authenticate, and retrieve all messages. ```APIDOC ## POP3 Example ### Description Here is a minimal example (without error checking) that opens a mailbox and retrieves and prints all messages: ### Method ```python import getpass, poplib M = poplib.POP3('localhost') M.user(getpass.getuser()) M.pass_(getpass.getpass()) numMessages = len(M.list()[1]) for i in range(numMessages): for j in M.retr(i+1)[1]: print(j) ``` ### Endpoint N/A (This is a code example, not an API endpoint) ### Parameters N/A ### Request Body N/A ### Request Example N/A ### Response N/A ### Response Example N/A ``` -------------------------------- ### Basic Example of profile and cProfile Source: https://devdocs.io/python~3.12/contents A simple example demonstrating how to profile a function using the cProfile module. ```python import cProfile def my_function(): for _ in range(100000): pass # Profile the function cProfile.run('my_function()') ``` -------------------------------- ### Install Custom Opener Source: https://devdocs.io/python~3.12/howto/urllib2 Installs a custom opener globally for all urllib.request.urlopen calls. ```python urllib.request.install_opener(opener) ``` -------------------------------- ### Server Socket Example Source: https://devdocs.io/python~3.12/library/ssl Provides an example of setting up a secure server socket that listens for incoming connections. ```APIDOC ## Server Socket Example ### Description This example demonstrates how to configure and start a secure server socket. It uses `PROTOCOL_TLS_SERVER`, loads a certificate chain and private key, binds to a local address, and listens for incoming connections. ### Method N/A (This is a Python code example, not a direct API endpoint call) ### Endpoint N/A ### Parameters N/A ### Request Example ```python context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key') with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: sock.bind(('127.0.0.1', 8443)) sock.listen(5) with context.wrap_socket(sock, server_side=True) as ssock: conn, addr = ssock.accept() ... ``` ### Response #### Success Response (200) N/A (Accepts a connection and returns the connection object and address) #### Response Example ``` (connection_object, ('127.0.0.1', port_number)) ``` ``` -------------------------------- ### Initialize Qt Application and Window Source: https://devdocs.io/python~3.12/howto/logging-cookbook Sets up the Qt application, creates the main window, and starts the event loop. Ensures the main thread is named for logging purposes. ```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) ``` -------------------------------- ### Getting Start Attribute Source: https://devdocs.io/python~3.12/c-api/exceptions Functions to retrieve the start attribute from Unicode exception objects. ```APIDOC ## PyUnicodeDecodeError_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. ### Method `int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)` ``` ```APIDOC ## PyUnicodeEncodeError_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. ### Method `int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)` ``` ```APIDOC ## 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. ### Method `int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)` ### Return Value Part of the Stable ABI. ``` -------------------------------- ### Basic Example of zipapp Source: https://devdocs.io/python~3.12/contents A simple example demonstrating the creation of an executable Python zip archive. ```python import zipapp import pathlib # Create a directory with a script (pathlib.Path('./my_app') / '__main__.py').write_text('print("Hello from zipapp!")') # Create the zipapp zipapp.create_archive('./my_app', 'my_app.pyz') ``` -------------------------------- ### Example config.site File Source: https://devdocs.io/python~3.12/using/configure An example of a site configuration file used to specify build overrides for the configure script. ```bash # config.site-aarch64 ac_cv_buggy_getaddrinfo=no ac_cv_file__dev_ptmx=yes ac_cv_file__dev_ptc=no ``` -------------------------------- ### Start Python Interpreter Source: https://devdocs.io/python~3.12/faq/windows To start the Python interpreter in interactive mode, type 'py' in the command prompt. Ensure Python is installed and in your PATH. ```bash C:\Users\YourName> py ``` -------------------------------- ### Initialize and Read Configuration Source: https://devdocs.io/python~3.12/library/configparser Demonstrates creating a ConfigParser instance, writing defaults to a file, and reading multiple configuration files with priority overrides. ```python >>> config_override = configparser.ConfigParser() >>> config_override['DEFAULT'] = {'ServerAliveInterval': '-1'} >>> with open('override.ini', 'w') as configfile: ... config_override.write(configfile) ... >>> config_override = configparser.ConfigParser() >>> config_override.read(['example.ini', 'override.ini']) ['example.ini', 'override.ini'] >>> print(config_override.get('DEFAULT', 'ServerAliveInterval')) -1 ``` -------------------------------- ### Example PATH Environment Variable on Windows Source: https://devdocs.io/python~3.12/using/windows An example of a PATH environment variable that includes a Python installation directory. This allows the system to find the python.exe executable from the command line. ```text C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.9 ``` -------------------------------- ### FTP Client Example with ftplib Source: https://devdocs.io/python~3.12/contents Demonstrates connecting to an FTP server and performing basic operations like listing directories. Requires an accessible FTP server. ```python from ftplib import FTP with FTP('ftp.example.com') as ftp: ftp.login('user', 'password') print(ftp.getwelcome()) print(ftp.nlst()) ``` -------------------------------- ### GET random.randrange Source: https://devdocs.io/python~3.12/library/random Returns a randomly selected element from range(start, stop, step). ```APIDOC ## GET random.randrange ### Description Return a randomly selected element from range(start, stop, step). This is optimized for large ranges. ### Method GET ### Parameters #### Path Parameters - **start** (int) - Optional - The starting value of the range. - **stop** (int) - Required - The upper bound of the range. - **step** (int) - Optional - The increment value. ### Response #### Success Response (200) - **value** (int) - A randomly selected integer from the specified range. ``` -------------------------------- ### Interactive Mode Session Source: https://devdocs.io/python~3.12/tutorial/interpreter Example of the output displayed when starting the Python interpreter in interactive mode. ```text $ python3.12 Python 3.12 (default, April 4 2022, 09:25:04) [GCC 10.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> ``` -------------------------------- ### Start an HTTP documentation server Source: https://devdocs.io/python~3.12/library/pydoc These commands launch a local HTTP server to browse documentation via a web browser. ```bash python -m pydoc -p 1234 ``` ```bash python -m pydoc -n ``` ```bash python -m pydoc -b ``` -------------------------------- ### Start Logging Configuration Server Source: https://devdocs.io/python~3.12/howto/logging-cookbook Sets up a logging configuration server that listens on a specified port. It reads an initial configuration file and then listens for updates. Use Ctrl+C to stop. ```python import logging import logging.config import time import os # read initial config file logging.config.fileConfig('logging.conf') # create and start listener on port 9999 t = logging.config.listen(9999) t.start() logger = logging.getLogger('simpleExample') try: # loop through logging calls to see the difference # new configurations make, until Ctrl+C is pressed while True: logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') time.sleep(5) except KeyboardInterrupt: # cleanup logging.config.stopListening() t.join() ``` -------------------------------- ### User scheme paths with sysconfig Source: https://devdocs.io/python~3.12/contents Shows how to get user-specific installation paths using sysconfig. ```python import sysconfig # Get user scheme paths for POSIX systems posix_user_lib = sysconfig.get_path('purelib', 'posix_user') print(f"POSIX user library path: {posix_user_lib}") # Get user scheme paths for Windows systems nt_user_lib = sysconfig.get_path('purelib', 'nt_user') print(f"Windows user library path: {nt_user_lib}") # Get user scheme paths for macOS systems osx_user_lib = sysconfig.get_path('purelib', 'osx_framework_user') print(f"macOS user library path: {osx_user_lib}") ``` -------------------------------- ### Instantiating a CustomAdapter Source: https://devdocs.io/python~3.12/howto/logging-cookbook Example of initializing a custom adapter with a logger and contextual data. ```python logger = logging.getLogger(__name__) adapter = CustomAdapter(logger, {'connid': some_conn_id}) ``` -------------------------------- ### Start and Stop Patches Manually with patcher.start() and patcher.stop() Source: https://devdocs.io/python~3.12/library/unittest.mock Use the `start()` and `stop()` methods on a patcher object to manually apply and remove patches. This is useful for setup methods or when not using decorators or context managers. ```python >>> patcher = patch('package.module.ClassName') >>> from package import module >>> original = module.ClassName >>> new_mock = patcher.start() >>> assert module.ClassName is not original >>> assert module.ClassName is new_mock >>> patcher.stop() >>> assert module.ClassName is original >>> assert module.ClassName is not new_mock ``` -------------------------------- ### Prefix scheme paths with sysconfig Source: https://devdocs.io/python~3.12/contents Shows how to get installation paths relative to a specific prefix directory. ```python import sysconfig # Get prefix scheme paths for POSIX systems posix_prefix_lib = sysconfig.get_path('purelib', 'posix_prefix') print(f"POSIX prefix library path: {posix_prefix_lib}") # Get prefix scheme paths for Windows systems nt_prefix_lib = sysconfig.get_path('purelib', 'nt') print(f"Windows prefix library path: {nt_prefix_lib}") ``` -------------------------------- ### Manage Patches in setUp and tearDown with unittest.TestCase Source: https://devdocs.io/python~3.12/library/unittest.mock Demonstrates how to use `patcher.start()` and `patcher.stop()` within `setUp` and `tearDown` methods of a `unittest.TestCase` for managing multiple patches. ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher1 = patch('package.module.Class1') ... self.patcher2 = patch('package.module.Class2') ... self.MockClass1 = self.patcher1.start() ... self.MockClass2 = self.patcher2.start() ... ... def tearDown(self): ... self.patcher1.stop() ... self.patcher2.stop() ... ... def test_something(self): ... assert package.module.Class1 is self.MockClass1 ... assert package.module.Class2 is self.MockClass2 ... >>> MyTest('test_something').run() ``` -------------------------------- ### Setting and Getting the First Weekday Source: https://devdocs.io/python~3.12/library/calendar Details on how to set and retrieve the starting day of the week for calendar generation. ```APIDOC ## Setting and Getting the First Weekday ### Description These functions allow you to control which day of the week is considered the start of a week in calendar representations. ### Functions - `calendar.setfirstweekday(weekday)`: Sets the weekday (0=Monday, 6=Sunday) to start each week. Accepts constants like `calendar.MONDAY` or `calendar.SUNDAY`. Example: ```python import calendar calendar.setfirstweekday(calendar.SUNDAY) ``` - `calendar.firstweekday()`: Returns the current setting for the first weekday of the week. ``` -------------------------------- ### Setup for PyArg_ParseTuple Source: https://devdocs.io/python~3.12/extending/extending Required macro and header for using argument parsing functions. ```c #define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */ #include ``` -------------------------------- ### Python Threading Example with Initial Sleep Source: https://devdocs.io/python~3.12/faq/library Addresses the issue of threads appearing to run sequentially by adding a small `time.sleep()` at the start of the thread's task. This can help the OS scheduler start threads in parallel. ```python def thread_task(name, n): time.sleep(0.001) # <--------------------! for i in range(n): print(name, i) for i in range(10): T = threading.Thread(target=thread_task, args=(str(i), i)) T.start() time.sleep(10) ``` -------------------------------- ### POP3 Client Example with poplib Source: https://devdocs.io/python~3.12/contents Shows how to connect to a POP3 server to retrieve emails. Ensure POP3 access is enabled on the mail server. ```python import poplib mail_server = poplib.POP3('pop.example.com') mail_server.user('myemail@example.com') mail_server.pass_('mypassword') num_messages = len(mail_server.list()[1]) print(f'You have {num_messages} messages.') mail_server.quit() ``` -------------------------------- ### heapq Module - Basic Examples Source: https://devdocs.io/python~3.12/library/bisect Provides basic examples of using the `heapq` module for heap queue algorithm implementations. ```APIDOC ## heapq Module - Basic Examples ### Description The `heapq` module implements the heap queue algorithm, also known as the priority queue algorithm. It provides functions for manipulating lists as heaps. ### Basic Usage - **Heapify**: Convert a list into a heap, in-place, in linear time. - **Push**: Push a new value onto the heap. - **Pop**: Pop and return the smallest item from the heap. ``` -------------------------------- ### ioctl Example: Get Process Group ID Source: https://devdocs.io/python~3.12/library/fcntl Demonstrates using ioctl with termios.TIOCGPGRP to retrieve the process group ID associated with a file descriptor. This example shows both direct integer argument usage and mutable buffer usage. ```python >>> import array, fcntl, struct, termios, os >>> os.getpgrp() 13341 >>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, " "))[0] 13341 >>> buf = array.array('h', [0]) >>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1) 0 >>> buf array('h', [13341]) ``` -------------------------------- ### Get Current Event Loop Policy Source: https://devdocs.io/python~3.12/library/asyncio-policy Use this function to retrieve the policy currently in effect for the process. No setup is required. ```python asyncio.get_event_loop_policy() ``` -------------------------------- ### Configure Module in Setup.local Source: https://devdocs.io/python~3.12/extending/extending Add this line to the Modules/Setup.local file to register a new module for static linking. ```text spam spammodule.o ``` -------------------------------- ### Example usage of ModuleFinder Source: https://devdocs.io/python~3.12/contents Demonstrates how to use the ModuleFinder class to find modules used by a script. No specific setup is required beyond importing the class. ```python from modulefinder import ModuleFinder finder = ModuleFinder() finder.run_script('my_script.py') print(finder.any("my_module")) ``` -------------------------------- ### Enable Python UTF-8 Mode via Preinitialization Source: https://devdocs.io/python~3.12/c-api/init_config Example demonstrating how to initialize a PyPreConfig structure, enable UTF-8 mode, and apply it before starting the Python interpreter. ```c PyStatus status; PyPreConfig preconfig; PyPreConfig_InitPythonConfig(&preconfig); preconfig.utf8_mode = 1; status = Py_PreInitialize(&preconfig); if (PyStatus_Exception(status)) { Py_ExitStatusException(status); } /* at this point, Python speaks UTF-8 */ Py_Initialize(); /* ... use Python API here ... */ Py_Finalize(); ``` -------------------------------- ### Starting and Serving Connections with asyncio.Server Source: https://devdocs.io/python~3.12/library/asyncio-eventloop Demonstrates how to start a server to accept connections indefinitely using `serve_forever()`. This method is suitable for long-running server applications. Ensure the `client_connected` callback is defined to handle incoming client communication. ```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)) ``` -------------------------------- ### Logging from Multiple Threads Example Source: https://devdocs.io/python~3.12/howto/logging-cookbook Demonstrates thread-safe logging by showing how to log messages from both the main thread and a worker thread. Ensure the logging configuration is set up before starting threads. ```python import logging import threading import time def worker(arg): while not arg['stop']: logging.debug('Hi from myfunc') time.sleep(0.5) def main(): logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s') info = {'stop': False} thread = threading.Thread(target=worker, args=(info,)) thread.start() while True: try: logging.debug('Hello from main') time.sleep(0.75) except KeyboardInterrupt: info['stop'] = True break thread.join() if __name__ == '__main__': main() ``` -------------------------------- ### EnvBuilder.setup_python() Method Source: https://devdocs.io/python~3.12/library/venv Sets up the Python interpreter within the virtual environment. ```APIDOC ## EnvBuilder.setup_python(context) ### Description Configures the Python interpreter within the newly created virtual environment based on the provided context. ### Method `setup_python` ### Parameters #### Request Body - **context** (types.SimpleNamespace) - Required - The context object containing environment details. ### Request Example ```python import venv builder = venv.EnvBuilder() context = builder.ensure_directories('./my_env') builder.create_configuration(context) builder.setup_python(context) # Python interpreter setup is completed for the environment ``` ``` -------------------------------- ### Get Boolean Fallback Values Source: https://devdocs.io/python~3.12/library/configparser The fallback argument can be used with getboolean() for boolean values. The example shows how a key not present defaults to the fallback, and how a changed value affects the result. ```python >>> 'BatchMode' in topsecret False >>> topsecret.getboolean('BatchMode', fallback=True) True >>> config['DEFAULT']['BatchMode'] = 'no' >>> topsecret.getboolean('BatchMode', fallback=True) False ``` -------------------------------- ### Client Socket Example (Default Context) Source: https://devdocs.io/python~3.12/library/ssl Demonstrates how to create a secure client socket using the default SSL context for a given hostname. ```APIDOC ## Client Socket Example (Default Context) ### Description This example shows how to establish a secure connection to a server using the default SSL context. It connects to 'www.python.org' on port 443 and prints the TLS version used. ### Method N/A (This is a Python code example, not a direct API endpoint call) ### Endpoint N/A ### Parameters N/A ### Request Example ```python import socket import ssl hostname = 'www.python.org' context = ssl.create_default_context() with socket.create_connection((hostname, 443)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: print(ssock.version()) ``` ### Response #### Success Response (200) N/A (Prints the TLS version to standard output) #### Response Example ``` TLSv1.3 ``` ``` -------------------------------- ### Doctest Directives on Subsequent Lines Source: https://devdocs.io/python~3.12/library/doctest When a directive comment is too long to fit on the same line as the code, directives can be placed on subsequent lines starting with '... # doctest:'. This allows for cleaner formatting of complex examples. ```python >>> print(list(range(20))) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE [0, 1, ..., 18, 19] ``` -------------------------------- ### Install packages from requirements.txt Source: https://devdocs.io/python~3.12/tutorial/venv Install all packages listed in a `requirements.txt` file. This command is used to set up an environment with all necessary dependencies. ```bash (tutorial-env) $ python -m pip install -r requirements.txt Collecting novas==3.1.1.3 (from -r requirements.txt (line 1)) ... Collecting numpy==1.9.2 (from -r requirements.txt (line 2)) ... Collecting requests==2.7.0 (from -r requirements.txt (line 3)) ... Installing collected packages: novas, numpy, requests Running setup.py install for novas Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0 ``` -------------------------------- ### Get ISO Calendar Date Source: https://devdocs.io/python~3.12/library/datetime Returns a named tuple with year, week, and weekday according to the ISO calendar. The ISO year consists of 52 or 53 full weeks, starting on Monday. ```python from datetime import date date(2003, 12, 29).isocalendar() date(2004, 1, 4).isocalendar() ``` -------------------------------- ### Create and run an archive via command line Source: https://devdocs.io/python~3.12/library/zipapp Use the zipapp module as a script to package a directory and execute the resulting archive. ```bash $ python -m zipapp myapp $ python myapp.pyz ``` -------------------------------- ### Configure Readline for Tab Completion Source: https://devdocs.io/python~3.12/library/rlcompleter This example demonstrates how to import the rlcompleter module and configure the readline module to use tab for completion. This setup is typically automatic when Python is run interactively on Unix-like systems. ```python import rlcompleter import readline readline.parse_and_bind("tab: complete") ``` -------------------------------- ### Invoke Interactive Help System Source: https://devdocs.io/python~3.12/library/functions Use `help()` without arguments to start the interactive help system on the interpreter console. Provide a module, function, class, or object as an argument to get specific documentation. ```python help() ``` -------------------------------- ### User-Specific Python Installation with Simplified UI Source: https://devdocs.io/python~3.12/using/windows This command installs Python for the current user, disables the launcher and test suite, and displays a simplified initial page with a custom description. It's suitable for users who don't need the test suite and prefer a streamlined installation. ```bash python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0 SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite." ``` -------------------------------- ### Configure STARTUPINFO Flags Source: https://devdocs.io/python~3.12/library/subprocess Use STARTF_USESTDHANDLES and STARTF_USESHOWWINDOW flags to control standard handles and window visibility for a new process. ```python si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW ``` -------------------------------- ### Basic unittest Boilerplate Source: https://devdocs.io/python~3.12/library/test A standard structure for creating test cases using the unittest module. Include setUp and tearDown methods if necessary for test preparation and cleanup. Test methods should start with 'test_' and have a descriptive comment. ```python import unittest from test import support class MyTestCase1(unittest.TestCase): # Only use setUp() and tearDown() if necessary def setUp(self): ... code to execute in preparation for tests ... def tearDown(self): ... code to execute to clean up after tests ... def test_feature_one(self): # Test feature one. ... testing code ... def test_feature_two(self): # Test feature two. ... testing code ... ... more test methods ... class MyTestCase2(unittest.TestCase): ... same structure as MyTestCase1 ... ... more test classes ... if __name__ == '__main__': unittest.main() ``` -------------------------------- ### Equivalent PyArg_ParseTuple Call for PyArg_UnpackTuple Example Source: https://devdocs.io/python~3.12/c-api/arg Shows the equivalent PyArg_ParseTuple call for the PyArg_UnpackTuple example, demonstrating how to parse the same arguments using a format string. ```c PyArg_ParseTuple(args, "O|O:ref", &object, &callback) ``` -------------------------------- ### EnvBuilder create method Source: https://devdocs.io/python~3.12/library/venv The `create` method orchestrates the virtual environment creation process. It can be overridden by subclasses to customize environment setup. It ensures directories are created, configuration is set up, Python is installed, scripts are set up, and performs post-setup actions. ```python def create(self, env_dir): """ Create a virtualized Python environment in a directory. env_dir is the target directory to create an environment in. """ env_dir = os.path.abspath(env_dir) context = self.ensure_directories(env_dir) self.create_configuration(context) self.setup_python(context) self.setup_scripts(context) self.post_setup(context) ``` -------------------------------- ### Counting XML Depth with XMLParser Source: https://devdocs.io/python~3.12/library/xml.etree.elementtree This example demonstrates how to use XMLParser with a custom target object to count the maximum depth of an XML document. The target object implements `start`, `end`, `data`, and `close` methods to handle parsing events. ```python from xml.etree.ElementTree import XMLParser class MaxDepth: maxDepth = 0 depth = 0 def start(self, tag, attrib): self.depth += 1 if self.depth > self.maxDepth: self.maxDepth = self.depth def end(self, tag): self.depth -= 1 def data(self, data): pass def close(self): return self.maxDepth target = MaxDepth() parser = XMLParser(target=target) exampleXml = """ """ parser.feed(exampleXml) parser.close() ``` -------------------------------- ### Using sysconfig as a script Source: https://devdocs.io/python~3.12/contents Shows how to use the sysconfig module from the command line. ```bash python -m sysconfig --vars python -m sysconfig --paths ``` -------------------------------- ### Cross-Compiling Configuration Example Source: https://devdocs.io/python~3.12/using/configure An example of how to use the 'CONFIG_SITE' environment variable along with configure options for cross-compiling Python. ```bash CONFIG_SITE=config.site-aarch64 ../configure \ --build=x86_64-pc-linux-gnu \ --host=aarch64-unknown-linux-gnu \ --with-build-python=../x86_64/python ``` -------------------------------- ### Instantiating and Running a Server Source: https://devdocs.io/python~3.12/library/socketserver Instantiate one of the server classes, passing the server's address and the request handler class. Use a `with` statement for recommended usage. Process requests using `handle_request()` or `serve_forever()`, and close the server with `server_close()`. ```APIDOC ## Server Instantiation and Operation ### Description Demonstrates how to instantiate and run a server. ### Steps 1. Instantiate a server class (e.g., `TCPServer`). 2. Use a `with` statement for proper resource management. 3. Call `handle_request()` to process a single request or `serve_forever()` to process requests indefinitely. 4. Ensure `server_close()` is called if not using a `with` statement. ### Example Usage ```python import socketserver class MyHandler(socketserver.BaseRequestHandler): def handle(self): # Process request here pass with socketserver.TCPServer(("localhost", 8080), MyHandler) as server: server.serve_forever() ``` ``` -------------------------------- ### Install pip without the pipX script Source: https://devdocs.io/python~3.12/library/ensurepip If an alternate installation is requested, the pipX script will not be installed. The pipX.Y script will still be installed. ```bash python -m ensurepip --altinstall ``` -------------------------------- ### Download and Build Custom OpenSSL Source: https://devdocs.io/python~3.12/using/unix Steps to download, configure, build, and install a custom version of OpenSSL. Use `install_sw` to avoid overwriting `openssl.cnf`. ```bash $ curl -O https://www.openssl.org/source/openssl-VERSION.tar.gz $ tar xzf openssl-VERSION $ pushd openssl-VERSION $ ./config \ --prefix=/usr/local/custom-openssl \ --libdir=lib \ --openssldir=/etc/ssl $ make -j1 depend $ make -j8 $ make install_sw $ popd ``` -------------------------------- ### Ensure Pip is Installed Source: https://devdocs.io/python~3.12/installing/index If pip is not installed by default, use this command to install it. This command ensures that pip is available for the default Python installation. ```python python -m ensurepip --default-pip ``` -------------------------------- ### Setting up an importer Source: https://devdocs.io/python~3.12/contents Shows how to set up a custom importer for a module. This allows for custom loading mechanisms. ```python import importlib.abc import importlib.util class MyLoader(importlib.abc.Loader): def create_module(self, spec): return None # Use default module creation def exec_module(self, module): module.my_attribute = 42 spec = importlib.util.ModuleSpec(name="my_module", loader=MyLoader()) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # use module here ``` -------------------------------- ### Install pip using ensurepip Source: https://devdocs.io/python~3.12/library/ensurepip This command installs pip if it is not already installed. It installs pip into the current virtual environment or the system site packages. ```bash python -m ensurepip ``` -------------------------------- ### Programmatically create and save a configuration file Source: https://devdocs.io/python~3.12/library/configparser Demonstrates initializing a ConfigParser object, populating it with data, and writing 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) ... ``` -------------------------------- ### os.startfile() Source: https://devdocs.io/python~3.12/library/os Opens a file with its associated application. This function is only available on Windows. ```APIDOC ## os.startfile() ### Description Opens a file with its associated application. The default working directory is inherited but can be overridden by the `_cwd` argument. A relative `_path` will be resolved against this argument. Use `_show_cmd` to override the default window style. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import os os.startfile("example.txt") ``` ### Response #### Success Response (200) N/A (Function returns immediately after launching the application) #### Response Example N/A ``` -------------------------------- ### Install gettext functions into built-in namespace Source: https://devdocs.io/python~3.12/library/gettext This method installs gettext() into the built-in namespace, binding it to '_'. You can also install other supported names like 'ngettext', 'pgettext', and 'npgettext'. Localized modules should use a module-specific installation to avoid global namespace pollution. ```python import gettext t = gettext.translation('mymodule', ...) _ = t.gettext ``` -------------------------------- ### Home scheme paths with sysconfig Source: https://devdocs.io/python~3.12/contents Demonstrates how to retrieve installation paths relative to the user's home directory. ```python import sysconfig # Get home scheme paths for POSIX systems posix_home_lib = sysconfig.get_path('purelib', 'posix_home') print(f"POSIX home library path: {posix_home_lib}") ``` -------------------------------- ### Imaginary Literal Examples Source: https://devdocs.io/python~3.12/reference/lexical_analysis Examples of valid imaginary literals. ```python 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j ```