### Class Method Setup Example Source: https://docs.python.org/3.12/library/unittest.html Demonstrates how to define a class method for setup that runs before tests in a class. It must be decorated with @classmethod. ```python @classmethod def setUpClass(cls): ... ``` -------------------------------- ### Safe Process Creation with Spawn/Forkserver Source: https://docs.python.org/3.12/library/multiprocessing.html This example shows how to safely create and start a process using 'spawn' start method by protecting the entry point with `if __name__ == '__main__':` and using `freeze_support()` and `set_start_method()`. ```python from multiprocessing import Process, freeze_support, set_start_method def foo(): print('hello') if __name__ == '__main__': freeze_support() set_start_method('spawn') p = Process(target=foo) p.start() ``` -------------------------------- ### Multiple Patches in setUp and tearDown Source: https://docs.python.org/3.12/library/unittest.mock.html Shows a common use case for start() and stop() within a unittest.TestCase's setUp and tearDown methods to manage multiple patches. ```python >>> class MyTest(unittest.TestCase): ... def setUp(self): ... self.patcher1 = patch('package.module.Class1') ... self.patcher2 = patch('package.module.Class2') ... self.MockClass1 = self.patcher1.start() ... self.MockClass2 = self.patcher2.start() ... ... def tearDown(self): ... self.patcher1.stop() ... self.patcher2.stop() ... ... def test_something(self): ... assert package.module.Class1 is self.MockClass1 ... assert package.module.Class2 is self.MockClass2 ... >>> MyTest('test_something').run() ``` -------------------------------- ### Basic Logging Setup Source: https://docs.python.org/3.12/library/logging.html This example demonstrates idiomatic usage of the logging module by setting up a basic configuration for the root logger and using module-level loggers. ```python # myapp.py 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() ``` ```python # mylib.py import logging logger = logging.getLogger(__name__) def do_something(): logger.info('Doing something') ``` -------------------------------- ### Example GET Request Source: https://docs.python.org/3.12/library/http.client.html Demonstrates making a GET request and retrieving the response status, reason, and body. ```APIDOC ## Example GET Request ### Description Here is an example session that uses the `GET` method: ### 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() # This will return entire content. # Example of reading data in chunks. conn.request("GET", "/") r1 = conn.getresponse() while chunk := r1.read(200): print(repr(chunk)) # Example of an invalid request conn = http.client.HTTPSConnection("docs.python.org") conn.request("GET", "/parrot.spam") r2 = conn.getresponse() print(r2.status, r2.reason) data2 = r2.read() conn.close() ``` ``` -------------------------------- ### Example: Get Linux Distribution IDs Source: https://docs.python.org/3.12/library/platform.html An example function demonstrating how to retrieve Linux distribution IDs and ID_LIKE information from the os-release data. ```python def get_like_distro(): info = platform.freedesktop_os_release() ids = [info["ID"]] if "ID_LIKE" in info: # ids are space separated and ordered by precedence ids.extend(info["ID_LIKE"].split()) return ids ``` -------------------------------- ### Example of re-enabling garbage collection during timing Source: https://docs.python.org/3.12/library/timeit.html This example shows how to re-enable garbage collection within the setup string if it's a significant part of the performance being measured. ```python timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit() ``` -------------------------------- ### Basic `optparse` Usage Example Source: https://docs.python.org/3.12/library/optparse.html Demonstrates the fundamental setup for using `optparse` to define and parse command-line options. It shows how to create an `OptionParser` instance, add options with destinations and help messages, and parse arguments. ```python from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() ``` -------------------------------- ### TestCase with setUp and multiple tests Source: https://docs.python.org/3.12/library/unittest.html Demonstrates using `setUp()` for common test fixture setup and defining multiple test methods within a single `TestCase` subclass. The `assertEqual` method is used for assertions. ```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') ``` -------------------------------- ### Multiprocessing Pool Example Setup Source: https://docs.python.org/3.12/library/multiprocessing.html This code sets up functions for use with Python's multiprocessing Pool. It includes helper functions for calculating results, performing multiplication and addition with simulated delays, and handling potential errors. ```python import multiprocessing import time import random import sys # # Functions used by test code # def calculate(func, args): result = func(*args) return '%s says that %s%s = %s' % ( multiprocessing.current_process().name, func.__name__, args, result ) def calculatestar(args): return calculate(*args) def mul(a, b): time.sleep(0.5 * random.random()) return a * b def plus(a, b): time.sleep(0.5 * random.random()) return a + b def f(x): return 1.0 / (x - 5.0) def pow3(x): return x ** 3 def noop(x): pass # # Test code ``` -------------------------------- ### SimpleXMLRPCServer Example Source: https://docs.python.org/3.12/library/xmlrpc.server.html Provides a complete example of setting up an XML-RPC server with registered functions and instances, and demonstrates how a client can interact with it. ```APIDOC ## SimpleXMLRPCServer Example ### Server Code ```python from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestHandler # Restrict to a particular path. class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2',) # Create server with SimpleXMLRPCServer(('localhost', 8000), requestHandler=RequestHandler) as server: server.register_introspection_functions() # Register pow() function; this will use the value of # pow.__name__ as the name, which is just 'pow'. server.register_function(pow) # Register a function under a different name def adder_function(x, y): return x + y server.register_function(adder_function, 'add') # Register an instance; all the methods of the instance are # published as XML-RPC methods (in this case, just 'mul'). class MyFuncs: def mul(self, x, y): return x * y server.register_instance(MyFuncs()) # Run the server's main loop server.serve_forever() ``` ### Client Code ```python import xmlrpc.client s = xmlrpc.client.ServerProxy('http://localhost:8000') print(s.pow(2,3)) # Returns 2**3 = 8 print(s.add(2,3)) # Returns 5 print(s.mul(5,2)) # Returns 5*2 = 10 ``` ``` -------------------------------- ### Get Distribution Package Version Source: https://docs.python.org/3.12/library/importlib.metadata.html Use the `version()` function to retrieve the installed version of a distribution package. Raises `PackageNotFoundError` if the package is not installed. ```python >>> version('wheel') '0.32.3' ``` -------------------------------- ### turtle.setup() Source: https://docs.python.org/3.12/library/turtle.html Sets the size and position of the main window. Default values can be configured via a `turtle.cfg` file. ```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 `setup(_width =_CFG['width']_, _height =_CFG['height']_, _startx =_CFG['leftright']_, _starty =_CFG['topbottom']_) ### Parameters #### Path Parameters * **width** (integer or float) - Required - if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen * **height** (integer or float) - Required - if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen * **startx** (integer or None) - Required - 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) - Required - 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) ``` ``` -------------------------------- ### urllib.request.install_opener Source: https://docs.python.org/3.12/library/urllib.request.html Install an OpenerDirector instance as the default global opener. This allows urlopen to use the installed opener for subsequent requests. ```APIDOC ## install_opener(_opener_) ### Description Installs an `OpenerDirector` instance as the default global opener. This is necessary if you want `urlopen()` to use that specific opener; otherwise, you can directly call `OpenerDirector.open()`. ### Parameters - **_opener_**: `OpenerDirector` instance - The opener to install as the default global opener. ### Returns None ``` -------------------------------- ### Handler Configuration Example Source: https://docs.python.org/3.12/library/logging.config.html Demonstrates how to configure 'console' and 'file' handlers with specific classes, formatters, levels, filters, and other constructor arguments. ```yaml handlers: console: class : logging.StreamHandler formatter: brief level : INFO filters: [allow_foo] stream : ext://sys.stdout file: class : logging.handlers.RotatingFileHandler formatter: precise filename: logconfig.log maxBytes: 1024 backupCount: 3 ``` -------------------------------- ### Send GET Request with URL Parameters Source: https://docs.python.org/3.12/library/urllib.request.html An example session demonstrating how to send a GET request with URL parameters using urllib.request and urllib.parse. ```python import urllib.request import urllib.parse params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) url = "http://www.musi-cal.com/cgi-bin/query?%s" % params with urllib.request.urlopen(url) as f: print(f.read().decode('utf-8')) ``` -------------------------------- ### Starting and Serving Forever with asyncio Source: https://docs.python.org/3.12/library/asyncio-eventloop.html Shows how to start an asyncio server and keep it running indefinitely to accept connections, handling client communication within a callback function. ```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)) ``` -------------------------------- ### Making a GET Request with HTTPSConnection Source: https://docs.python.org/3.12/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) 200 OK ``` -------------------------------- ### Install wheel package Source: https://docs.python.org/3.12/library/importlib.metadata.html This snippet shows how to create a virtual environment and install the 'wheel' package using pip. ```bash python -m venv example source example/bin/activate (example) $ python -m pip install wheel ``` -------------------------------- ### EnvBuilder.post_setup Source: https://docs.python.org/3.12/library/venv.html A placeholder method for third-party implementations to perform post-creation steps like pre-installing packages. ```APIDOC ## EnvBuilder.post_setup ### Description A placeholder method that can be overridden to perform custom actions after the virtual environment is set up, such as pre-installing packages. ### Method `post_setup(_context_) ### Parameters * **_context_** (object) - The context of the virtual environment creation. ``` -------------------------------- ### SETUP_WITH Instruction Source: https://docs.python.org/3.12/library/dis.html Used for 'with' and 'async with' constructs. Sets up an exception handler and pops an extra item from the stack before transferring control. ```python SETUP_WITH(_target_) ``` -------------------------------- ### Get Distribution Metadata Source: https://docs.python.org/3.12/library/importlib.metadata.html Retrieve all metadata fields for an installed distribution package. ```APIDOC ## Get Distribution Metadata ### Description Retrieves all metadata fields for a given distribution package. ### Function Signature `metadata(name: str) -> email.message.Message` ### Parameters * **name** (str) - The name of the distribution package. ### Returns * (email.message.Message) - A message object containing the distribution's metadata. ### Raises * `PackageNotFoundError` - If the specified package is not installed. ### Example ```python from importlib.metadata import metadata print(list(metadata('wheel'))) ``` ``` -------------------------------- ### subprocess.getstatusoutput example Source: https://docs.python.org/3.12/library/subprocess.html Demonstrates the usage of subprocess.getstatusoutput to get the exit code and output of a shell command. Examples include successful execution, file not found, and command not found. ```python >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> subprocess.getstatusoutput('cat /bin/junk') (1, 'cat: /bin/junk: No such file or directory') >>> subprocess.getstatusoutput('/bin/junk') (127, 'sh: /bin/junk: not found') >>> subprocess.getstatusoutput('/bin/kill $$') (-15, '') ``` -------------------------------- ### curses.setupterm() Source: https://docs.python.org/3.12/library/curses.html Initializes the terminal using the specified terminfo name or the TERM environment variable. ```APIDOC ## curses.setupterm(_term=None_, _fd=-1_) ### Description Initialize the terminal. _term_ is a string giving the terminal name, or `None`; if omitted or `None`, the value of the `TERM` environment variable will be used. _fd_ is the file descriptor to which any initialization sequences will be sent; if not supplied or `-1`, the file descriptor for `sys.stdout` will be used. ### Method Call ### Parameters * **_term_** (str, optional) - The terminal name. Defaults to `None` (uses TERM environment variable). * **_fd_** (int, optional) - The file descriptor for initialization sequences. Defaults to -1 (uses sys.stdout). ``` -------------------------------- ### Doctest Example with Leading Whitespace Source: https://docs.python.org/3.12/library/doctest.html Illustrates that the starting column of an example does not matter, and leading whitespace is stripped from the expected output based on the initial code line's indentation. ```python >>> assert "Easy!" >>> import math >>> math.floor(1.9) 1 ``` -------------------------------- ### Standard Formats Examples (64-bit) Source: https://docs.python.org/3.12/library/struct.html Demonstrates the behavior of calcsize and pack with standard format strings on a 64-bit machine. These examples highlight byte order and size calculations. ```python >>> calcsize('>> pack('>> calcsize('@llh') 18 >>> pack('@llh', 1, 2, 3) == pack('>> calcsize('>> calcsize('@llh0l') 24 >>> pack('@llh0l', 1, 2, 3) == pack(' str` ### Parameters * **name** (str) - The name of the distribution package. ### Returns * (str) - The version string of the package. ### Raises * `PackageNotFoundError` - If the specified package is not installed. ### Example ```python from importlib.metadata import version print(version('wheel')) ``` ``` -------------------------------- ### Get package version Source: https://docs.python.org/3.12/library/importlib.metadata.html Retrieve the version string for an installed package like 'wheel'. ```python from importlib.metadata import version version('wheel') ``` -------------------------------- ### Running the Example Script (Success Case) Source: https://docs.python.org/3.12/library/__main__.html This command shows the output when the 'start.py' script is executed with the 'my_name' variable defined in the __main__ scope, successfully printing the name and its file location. ```bash $ python start.py Dinsdale found in file /path/to/start.py ``` -------------------------------- ### Get Distribution Version Source: https://docs.python.org/3.12/library/importlib.metadata.html Access the version number of an installed distribution package through its Distribution instance. ```python dist.version ``` -------------------------------- ### Basic Sub-command Setup with argparse Source: https://docs.python.org/3.12/library/argparse.html Demonstrates the creation of a top-level parser with subparsers for 'a' and 'b' commands, each with their own arguments. Shows how to parse arguments for these sub-commands. ```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) ``` -------------------------------- ### Basic FTP Session Example Source: https://docs.python.org/3.12/library/ftplib.html Demonstrates a typical FTP session including connecting, logging in, changing directories, listing contents, retrieving a file, and quitting. ```python from ftplib import FTP ftp = FTP('ftp.us.debian.org') # connect to host, default port ftp.login() # user anonymous, passwd anonymous@ ftp.cwd('debian') # change into "debian" directory ftp.retrlines('LIST') # list directory contents with open('README', 'wb') as fp: ftp.retrbinary('RETR README', fp.write) ftp.quit() ``` -------------------------------- ### Example of ioctl with array.array and termios Source: https://docs.python.org/3.12/library/fcntl.html This example demonstrates using ioctl to get the process group ID associated with a terminal. It shows how to use an array.array object as a mutable buffer for the ioctl call. ```python import array, fcntl, struct, termios, os os.getpgrp() struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, " "))[0] buf = array.array('h', [0]) cntl.ioctl(0, termios.TIOCGPGRP, buf, 1) buf ``` -------------------------------- ### EnvBuilder.setup_scripts Source: https://docs.python.org/3.12/library/venv.html Installs activation scripts appropriate to the platform into the virtual environment. ```APIDOC ## EnvBuilder.setup_scripts ### Description Installs platform-specific activation scripts into the virtual environment. ### Method `setup_scripts(_context_) ### Parameters * **_context_** (object) - The context of the virtual environment creation. ``` -------------------------------- ### Get Distribution Instance Source: https://docs.python.org/3.12/library/importlib.metadata.html Retrieve a Distribution instance for a specified package. Raises PackageNotFoundError if the package is not installed. ```python from importlib.metadata import distribution dist = distribution('wheel') type(dist) ``` -------------------------------- ### test.support.import_helper.modules_setup Source: https://docs.python.org/3.12/library/test.html Returns a copy of sys.modules. ```APIDOC ## test.support.import_helper.modules_setup() ### Description Return a copy of `sys.modules`. ### Method N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### os.startfile Source: https://docs.python.org/3.12/library/os.html Start a file with its associated application. ```APIDOC ## os.startfile(_path_[, _operation_][, _arguments_][, _cwd_][, _show_cmd_]) ### Description Start a file with its associated application. When `_operation_` is not specified, this acts like double-clicking the file in Windows Explorer or giving the file name as an argument to the `start` command from the interactive command shell. ### Parameters * `_path_` (string) - The path to the file to start. * `_operation_` (string, optional) - The operation to perform on the file (e.g., 'open', 'print'). * `_arguments_` (string, optional) - Arguments to pass to the application. * `_cwd_` (string, optional) - The current working directory for the application. * `_show_cmd_` (int, optional) - The command-line show state for the window (e.g., `SW_SHOWNORMAL`). ### Availability Windows. ``` -------------------------------- ### Get distribution metadata Source: https://docs.python.org/3.12/library/importlib.metadata.html Retrieves the metadata for a specified distribution package. Raises PackageNotFoundError if the package is not installed. ```python >>> wheel_metadata = metadata('wheel') ``` -------------------------------- ### Client Socket Example with Custom Context Source: https://docs.python.org/3.12/library/ssl.html Demonstrates setting up a client socket with a custom SSL context for IPv4 connections. ```python hostname = 'www.python.org' ``` -------------------------------- ### Getting All Global Site-Packages Directories Source: https://docs.python.org/3.12/library/site.html Retrieves a list of all global site-packages directories configured for the current Python installation. ```python site.getsitepackages() ``` -------------------------------- ### date.isocalendar() Example Source: https://docs.python.org/3.12/library/datetime.html Demonstrates the usage of `isocalendar()` to get ISO calendar year, week, and weekday for specific dates. ```python >>> from datetime import date >>> date(2003, 12, 29).isocalendar() datetime.IsoCalendarDate(year=2004, week=1, weekday=1) >>> date(2004, 1, 4).isocalendar() datetime.IsoCalendarDate(year=2004, week=1, weekday=7) ``` -------------------------------- ### Set Up a Meta Path Finder and Path Entry Finder Source: https://docs.python.org/3.12/library/importlib.html This example shows how to register custom importers by appending a meta path finder and a path entry finder to sys.meta_path and sys.path_hooks, respectively. This allows import to utilize your custom importers for deep customization. ```python import importlib.machinery import sys # For illustrative purposes only. SpamMetaPathFinder = importlib.machinery.PathFinder SpamPathEntryFinder = importlib.machinery.FileFinder loader_details = (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES) # Setting up a meta path finder. # Make sure to put the finder in the proper location in the list in terms of # priority. sys.meta_path.append(SpamMetaPathFinder) # Setting up a path entry finder. # Make sure to put the path hook in the proper location in the list in terms # of priority. sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details)) ``` -------------------------------- ### Extending EnvBuilder for Virtual Environment Setup Source: https://docs.python.org/3.12/library/venv.html This script demonstrates subclassing `venv.EnvBuilder` to create a custom environment builder that installs setuptools and pip. It includes methods for post-setup package installation and progress reporting during script execution. ```python import os import os.path from subprocess import Popen, PIPE import sys from threading import Thread from urllib.parse import urlparse from urllib.request import urlretrieve import venv class ExtendedEnvBuilder(venv.EnvBuilder): """ This builder installs setuptools and pip so that you can pip or easy_install other packages into the created virtual environment. :param nodist: If true, setuptools and pip are not installed into the created virtual environment. :param nopip: If true, pip is not installed into the created virtual environment. :param progress: If setuptools or pip are installed, the progress of the installation can be monitored by passing a progress callable. If specified, it is called with two arguments: a string indicating some progress, and a context indicating where the string is coming from. The context argument can have one of three values: 'main', indicating that it is called from virtualize() itself, and 'stdout' and 'stderr', which are obtained by reading lines from the output streams of a subprocess which is used to install the app. If a callable is not specified, default progress information is output to sys.stderr. """ def __init__(self, *args, **kwargs): self.nodist = kwargs.pop('nodist', False) self.nopip = kwargs.pop('nopip', False) self.progress = kwargs.pop('progress', None) self.verbose = kwargs.pop('verbose', False) super().__init__(*args, **kwargs) def post_setup(self, context): """ Set up any packages which need to be pre-installed into the virtual environment being created. :param context: The information for the virtual environment creation request being processed. """ os.environ['VIRTUAL_ENV'] = context.env_dir if not self.nodist: self.install_setuptools(context) # Can't install pip without setuptools if not self.nopip and not self.nodist: self.install_pip(context) def reader(self, stream, context): """ Read lines from a subprocess' output stream and either pass to a progress callable (if specified) or write progress information to sys.stderr. """ progress = self.progress while True: s = stream.readline() if not s: break if progress is not None: progress(s, context) else: if not self.verbose: sys.stderr.write('.') else: sys.stderr.write(s.decode('utf-8')) sys.stderr.flush() stream.close() def install_script(self, context, name, url): _, _, path, _, _, _ = urlparse(url) fn = os.path.split(path)[-1] binpath = context.bin_path distpath = os.path.join(binpath, fn) # Download script into the virtual environment's binaries folder urlretrieve(url, distpath) progress = self.progress if self.verbose: term = '\n' else: term = '' if progress is not None: progress('Installing %s ...%s' % (name, term), 'main') else: sys.stderr.write('Installing %s ...%s' % (name, term)) sys.stderr.flush() # Install in the virtual environment args = [context.env_exe, fn] p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath) t1 = Thread(target=self.reader, args=(p.stdout, 'stdout')) t1.start() t2 = Thread(target=self.reader, args=(p.stderr, 'stderr')) t2.start() p.wait() t1.join() t2.join() if progress is not None: progress('done.', 'main') else: sys.stderr.write('done.\n') # Clean up - no longer needed os.unlink(distpath) 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: pass ``` -------------------------------- ### setUpClass and tearDownClass Implementation Source: https://docs.python.org/3.12/library/unittest.html Example of implementing setUpClass and tearDownClass as class methods for managing expensive resources like database connections. These methods are called once per class. ```python import unittest class Test(unittest.TestCase): @classmethod def setUpClass(cls): cls._connection = createExpensiveConnectionObject() @classmethod def tearDownClass(cls): cls._connection.destroy() ``` -------------------------------- ### UDPServer Example Source: https://docs.python.org/3.12/library/socketserver.html Demonstrates how to create and use a basic UDP server. It requires a request handler class and the server's address. ```Python import socketserver class MyUDPHandler(socketserver.BaseRequestHandler): def handle(self): data = self.request[0] socket = self.request[1] print(f"Received {data} from {self.client_address}") socket.sendto(data.upper(), self.client_address) if __name__ == "__main__": HOST, PORT = "localhost", 0 # Use port 0 to let the OS pick an available port # Create the server, binding to localhost on port 0 with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server: # Activate the server; this is usually done by the with statement. server.serve_forever() ``` -------------------------------- ### Getting Context with get_context() Source: https://docs.python.org/3.12/library/multiprocessing.html Illustrates using 'get_context()' to obtain a multiprocessing context object, allowing for the use of different start methods within the same program. This is recommended for libraries to avoid interfering with the user's chosen start method. ```python import multiprocessing as mp def foo(q): q.put('hello') if __name__ == '__main__': ctx = mp.get_context('spawn') q = ctx.Queue() p = ctx.Process(target=foo, args=(q,)) p.start() print(q.get()) p.join() ``` -------------------------------- ### Formatting Exception Only Source: https://docs.python.org/3.12/library/traceback.html This example shows how to use `traceback.format_exception_only` to get a list of strings representing just the exception message, without the traceback. ```python import traceback an_error = IndexError('tuple index out of range') traceback.format_exception_only(an_error) ``` -------------------------------- ### msilib.init_database Source: https://docs.python.org/3.12/library/msilib.html Initializes a new MSI database with a given schema and product information. ```APIDOC ## msilib.init_database ### Description Create and return a new database _name_ , initialize it with _schema_ , and set the properties _ProductName_ , _ProductCode_ , _ProductVersion_ , and _Manufacturer_. _schema_ must be a module object containing `tables` and `_Validation_records` attributes; typically, `msilib.schema` should be used. The database will contain just the schema and the validation records when this function returns. ### Parameters * **_name_** (string) - The name of the database to create. * **_schema_** (module) - A module object containing `tables` and `_Validation_records` attributes. * **_ProductName_** (string) - The product name. * **_ProductCode_** (string) - The product code. * **_ProductVersion_** (string) - The product version. * **_Manufacturer_** (string) - The manufacturer name. ### Returns Database object - The newly created and initialized database object. ``` -------------------------------- ### Certificate Chain Example Source: https://docs.python.org/3.12/library/ssl.html A sequence of certificates concatenated together, starting with the specific certificate and ending with a self-signed root certificate. ```text -----BEGIN CERTIFICATE----- ... (certificate for your server)... -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- ... (the certificate for the CA)... -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- ... (the root certificate for the CA's issuer)... -----END CERTIFICATE----- ``` -------------------------------- ### Setting STARTUPINFO Flags Source: https://docs.python.org/3.12/library/subprocess.html Demonstrates how to set dwFlags for STARTUPINFO to use standard handles and show window. ```python si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW ``` -------------------------------- ### tracemalloc.get_traceback_limit() Source: https://docs.python.org/3.12/library/tracemalloc.html Gets the maximum number of frames stored in the traceback of a trace. This limit is set by the `start()` function and requires tracing to be active. ```APIDOC ## tracemalloc.get_traceback_limit() ### Description Get the maximum number of frames stored in the traceback of a trace. The `tracemalloc` module must be tracing memory allocations to get the limit, otherwise an exception is raised. The limit is set by the `start()` function. ``` -------------------------------- ### Example Command Line for 'extend' Action Source: https://docs.python.org/3.12/library/optparse.html Demonstrates how multiple values can be passed to an 'extend' action via a comma-delimited string and separate option instances. ```bash --names=foo,bar --names blah --names ding,dong ``` -------------------------------- ### IDL Attribute Declarations Source: https://docs.python.org/3.12/library/xml.dom.html Example of IDL attribute declarations for string types. These map to 'get' and 'set' accessor functions in Python. ```idl readonly attribute string someValue; attribute string anotherValue; ``` -------------------------------- ### Application-Level Localization Setup Source: https://docs.python.org/3.12/library/gettext.html Install the `_()` function globally into the built-in namespace for application-wide use. This is typically done in the main driver file. ```python import gettext gettext.install('myapplication') ``` -------------------------------- ### TestCase with setUp and tearDown Source: https://docs.python.org/3.12/library/unittest.html Use `setUp()` to prepare test fixtures before each test method and `tearDown()` to clean up after each test method. These methods are automatically called by the testing framework. ```python import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() ``` -------------------------------- ### Equivalent commands for test discovery Source: https://docs.python.org/3.12/library/unittest.html These commands demonstrate equivalent ways to specify the start directory and pattern for test discovery. The first explicitly lists options, while the second uses positional arguments. ```bash python -m unittest discover -s project_directory -p "*_test.py" python -m unittest discover project_directory "*_test.py" ``` -------------------------------- ### Import Turtle Module Source: https://docs.python.org/3.12/library/turtle.html Import all objects from the turtle module to start using its functions. Ensure Tkinter is installed if you encounter a '_tkinter' error. ```python from turtle import * ``` -------------------------------- ### Example Command Line Usage Source: https://docs.python.org/3.12/library/optparse.html Illustrates how users can interact with a script that uses `optparse` by providing command-line arguments. This example shows a typical invocation with both a short and a long option. ```bash --file=outfile -q ``` -------------------------------- ### readline.set_completer_delims, readline.get_completer_delims Source: https://docs.python.org/3.12/library/readline.html Sets or gets the string of word delimiters used for completion. These characters define the boundaries for identifying the start of a word to be completed. ```APIDOC ## readline.set_completer_delims, readline.get_completer_delims ### Description Sets or gets the word delimiters for completion. These characters determine the start of the word to be considered for completion. These functions access the `rl_completer_word_break_characters` variable in the underlying library. ### Method `set_completer_delims(_string_) `get_completer_delims() ### Parameters #### For `set_completer_delims`: * **_string_** (str) - The string of characters to set as word delimiters. #### For `get_completer_delims`: None ### Response #### Success Response (200) * **delimiters** (str) - The string of word delimiters. ``` -------------------------------- ### Get Distribution Package Requirements Source: https://docs.python.org/3.12/library/importlib.metadata.html The `requires()` function retrieves the declared dependency specifiers for a distribution package. Raises `PackageNotFoundError` if the package is not installed. ```python >>> requires('wheel') ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"] ``` -------------------------------- ### Create a Symbolic Link Example Source: https://docs.python.org/3.12/library/pathlib.html Demonstrates creating a symbolic link and resolving its target. ```python >>> p = Path('mylink') >>> p.symlink_to('setup.py') >>> p.resolve() PosixPath('/home/antoine/pathlib/setup.py') >>> p.stat().st_size 956 >>> p.lstat().st_size 8 ``` -------------------------------- ### os.startfile Source: https://docs.python.org/3.12/library/os.html Starts a file with its associated application. Supports specifying operation, arguments, working directory, and window style. ```APIDOC ## os.startfile(_path_, _operation_='open', _arguments_=None, _cwd_=None, _show_cmd_=None) ### Description Launches an application to process a file or directory. The default working directory is inherited but can be overridden. The window style can also be controlled. ### Method `os.startfile` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the file or directory. - **operation** (string) - Optional - The operation to perform (e.g., 'open', 'print', 'edit'). Defaults to 'open'. - **arguments** (string) - Optional - Arguments to pass to the application. - **cwd** (string) - Optional - The default working directory. Should be an absolute path. - **show_cmd** (integer) - Optional - The window style for the application, as supported by Win32 `ShellExecute()`. ### Availability Windows. ### Changed in version 3.10 Added the _arguments_, _cwd_ and _show_cmd_ arguments, and the `os.startfile/2` audit event. ``` -------------------------------- ### Getting User Base Directory Path Source: https://docs.python.org/3.12/library/site.html Returns the path to the user base directory, respecting the PYTHONUSERBASE environment variable. This path is used for user-specific installations. ```python site.getuserbase() ``` -------------------------------- ### Getting Day Names in Current Locale Source: https://docs.python.org/3.12/library/calendar.html Retrieves a list of full weekday names in the current locale. The sequence starts with Monday as day number 0. ```python >>> import calendar >>> list(calendar.day_name) ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] ``` -------------------------------- ### Timing user-defined functions with setup import Source: https://docs.python.org/3.12/library/timeit.html Shows how to time a user-defined function by importing it into the timeit environment using the 'setup' parameter. ```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")) ``` -------------------------------- ### Start HTTP Server for Documentation Source: https://docs.python.org/3.12/library/pydoc.html Start an HTTP server on a specified port (e.g., 1234) to browse documentation via a web browser. The server will be accessible at `http://localhost:1234/`. ```shell python -m pydoc -p 1234 ``` -------------------------------- ### Run doctest with Verbose Output via Command Line Source: https://docs.python.org/3.12/library/doctest.html Use the -v flag with the command-line invocation to get a detailed report of all doctest examples tried. ```bash python -m doctest -v example.py ``` -------------------------------- ### Process Constructor and run() Method Example Source: https://docs.python.org/3.12/library/multiprocessing.html Demonstrates creating a Process object with a target function and arguments, and then calling its run() method. The target can be a callable like `print`, and arguments can be provided as a list or tuple. ```python >>> from multiprocessing import Process >>> p = Process(target=print, args=[1]) >>> p.run() 1 >>> p = Process(target=print, args=(1,)) >>> p.run() 1 ``` -------------------------------- ### Getting Abbreviated Day Names in Current Locale Source: https://docs.python.org/3.12/library/calendar.html Retrieves a list of abbreviated weekday names in the current locale. The sequence starts with Mon as day number 0. ```python >>> import calendar >>> list(calendar.day_abbr) ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] ``` -------------------------------- ### Start HTTP Server and Open Browser Source: https://docs.python.org/3.12/library/pydoc.html Start the HTTP documentation server and automatically open a web browser to the module index page. ```shell python -m pydoc -b ``` -------------------------------- ### Using a Multiprocessing Pool Source: https://docs.python.org/3.12/library/multiprocessing.html Demonstrates the basic usage of a multiprocessing Pool for asynchronous task execution and result retrieval. Includes examples of apply_async, get, map, and imap. ```python from multiprocessing import Pool import time def f(x): return x*x if __name__ == '__main__': with Pool(processes=4) as pool: # start 4 worker processes result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]" it = pool.imap(f, range(10)) print(next(it)) # prints "0" print(next(it)) # prints "1" print(it.next(timeout=1)) # prints "4" unless your computer is *very* slow result = pool.apply_async(time.sleep, (10,)) print(result.get(timeout=1)) # raises multiprocessing.TimeoutError ``` -------------------------------- ### Basic Format String Examples Source: https://docs.python.org/3.12/library/string.html Illustrates various ways to use format strings with positional and keyword arguments, including attribute and index lookups. ```python "First, thou shalt count to {0}" # References first positional argument ``` ```python "Bring me a {}" # Implicitly references the first positional argument ``` ```python "From {} to {}" # Same as "From {0} to {1}" ``` ```python "My quest is {name}" # References keyword argument 'name' ``` ```python "Weight in tons {0.weight}" # 'weight' attribute of first positional arg ``` ```python "Units destroyed: {players[0]}" # First element of keyword argument 'players'. ``` -------------------------------- ### Basic Process Creation with `Process` Source: https://docs.python.org/3.12/library/multiprocessing.html A trivial example of a multiprocess program. Processes are spawned by creating a `Process` object and calling its `start()` method. This follows the API of `threading.Thread`. ```python from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() ``` -------------------------------- ### Get Anchor of a Path Source: https://docs.python.org/3.12/library/pathlib.html Combines the drive and root components to form the anchor of a path. Shows examples for Windows and Posix path flavors, including UNC shares. ```python >>> PureWindowsPath('c:/Program Files/').anchor 'c:\' >>> PureWindowsPath('c:Program Files/').anchor 'c:' >>> PurePosixPath('/etc').anchor '/' >>> PureWindowsPath('//host/share').anchor '\\host\share\' ``` -------------------------------- ### Python count iterator example Source: https://docs.python.org/3.12/library/itertools.html Creates an iterator that returns evenly spaced values starting from a specified number. Can be used for generating sequences or adding sequence numbers. ```Python def count(start=0, step=1): # count(10) → 10 11 12 13 14 ... # count(2.5, 0.5) → 2.5 3.0 3.5 ... n = start while True: yield n n += step ``` -------------------------------- ### Display Test Help and Options Source: https://docs.python.org/3.12/library/test.html Show all available resources and command-line options for the `test` script. ```bash python -m test -h ``` -------------------------------- ### Basic HTML Parser Application Source: https://docs.python.org/3.12/library/html.parser.html This example demonstrates how to subclass HTMLParser to print encountered start tags, end tags, and data. It requires importing the HTMLParser class. ```python from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Encountered a start tag:", tag) def handle_endtag(self, tag): print("Encountered an end tag :", tag) def handle_data(self, data): print("Encountered some data :", data) parser = MyHTMLParser() parser.feed('Test' '

Parse me!

') ``` -------------------------------- ### Create and Run a WSGI Server Source: https://docs.python.org/3.12/library/wsgiref.html This snippet demonstrates how to create a WSGI server instance using make_server, serve a demo application, and handle requests indefinitely or 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() ```