### Starting Server with serve_forever Source: https://docs.python.org/3/library/asyncio-eventloop.html This example demonstrates how to start a server and keep it running indefinitely using `serve_forever()`. It includes a basic client connection handler. ```python async def client_connected(reader, writer): # Communicate with the client with # reader/writer streams. For example: await reader.readline() async def main(host, port): srv = await asyncio.start_server( client_connected, host, port) await srv.serve_forever() asyncio.run(main('127.0.0.1', 0)) ``` -------------------------------- ### Get All Installation Paths for a Scheme Source: https://docs.python.org/3/library/sysconfig.html Returns a dictionary of all installation paths for a given scheme. Paths can be expanded using provided variables. ```python sysconfig.get_paths([_scheme_[, _vars_[, _expand_]]]) ``` -------------------------------- ### Create and Start Threads with `threading.Thread` Source: https://docs.python.org/3/library/threading.html Demonstrates the basic usage of creating and starting threads using the `threading.Thread` class. This example simulates I/O-bound tasks using `time.sleep`. ```Python import threading import time def crawl(link, delay=3): print(f"crawl started for {link}") time.sleep(delay) # Blocking I/O (simulating a network request) print(f"crawl ended for {link}") links = [ "https://python.org", "https://docs.python.org", "https://peps.python.org", ] threads = [] for link in links: thread = threading.Thread(target=crawl, args=(link,)) threads.append(thread) thread.start() for thread in threads: thread.join() # Wait for all threads to complete print("All crawls finished.") ``` -------------------------------- ### Install Setuptools Script Source: https://docs.python.org/3/library/venv.html Installs setuptools in the virtual environment. Cleans up downloaded archives afterwards. ```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) ``` -------------------------------- ### Creating and Serving a Manager Source: https://docs.python.org/3/library/multiprocessing.html Instantiate a BaseManager, get its server, and start serving connections. Ensure the manager process is started before serving. ```python from multiprocessing.managers import BaseManager manager = BaseManager(address=('', 50000), authkey=b'abc') server = manager.get_server() server.serve_forever() ``` -------------------------------- ### Setting up a Custom Importer with importlib.machinery Source: https://docs.python.org/3/library/importlib.html This example shows the initial setup for registering custom importers in Python. It involves using `importlib.machinery` and `sys` to prepare for the creation of either a meta path finder or a path entry finder, which allows for deep customization of the import process. ```python import importlib.machinery import sys ``` -------------------------------- ### Install a package using pip Source: https://docs.python.org/3/library/importlib.metadata.html Demonstrates creating a virtual environment and installing the 'wheel' package using pip. ```bash $ python -m venv example $ source example/bin/activate (example) $ python -m pip install wheel ``` -------------------------------- ### Asynchronous Test Case Example Source: https://docs.python.org/3/library/unittest.html Demonstrates the order of execution for asynchronous setup, test execution, and cleanup methods within `IsolatedAsyncioTestCase`. This includes `setUp`, `asyncSetUp`, the test method, `asyncTearDown`, `tearDown`, and `addAsyncCleanup`. ```python from unittest import IsolatedAsyncioTestCase events = [] class Test(IsolatedAsyncioTestCase): def setUp(self): events.append("setUp") async def asyncSetUp(self): self._async_connection = await AsyncConnection() events.append("asyncSetUp") async def test_response(self): events.append("test_response") response = await self._async_connection.get("https://example.com") self.assertEqual(response.status_code, 200) self.addAsyncCleanup(self.on_cleanup) def tearDown(self): events.append("tearDown") async def asyncTearDown(self): await self._async_connection.close() events.append("asyncTearDown") async def on_cleanup(self): events.append("cleanup") if __name__ == "__main__": unittest.main() ``` -------------------------------- ### Example: Get Enabled Ciphers Source: https://docs.python.org/3/library/ssl.html Demonstrates setting ciphers using set_ciphers() and then retrieving the list of enabled ciphers with get_ciphers(). ```python >>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) >>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA') >>> ctx.get_ciphers() [{'aead': True, 'alg_bits': 256, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' \ 'Enc=AESGCM(256) Mac=AEAD', 'digest': None, 'id': 50380848, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES256-GCM-SHA384', 'protocol': 'TLSv1.2', 'strength_bits': 256, 'symmetric': 'aes-256-gcm'}, {'aead': True, 'alg_bits': 128, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' \ 'Enc=AESGCM(128) Mac=AEAD', 'digest': None, 'id': 50380847, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES128-GCM-SHA256', 'protocol': 'TLSv1.2', 'strength_bits': 128, 'symmetric': 'aes-128-gcm'}] ``` -------------------------------- ### unittest TestCase with setUp Source: https://docs.python.org/3/library/unittest.html Use the `setUp()` method to create a test fixture that is automatically called before each test method. This avoids repetitive setup code for multiple tests within the same test case. ```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') ``` -------------------------------- ### Server Example with Authentication Source: https://docs.python.org/3/library/multiprocessing.html This example demonstrates setting up a listener with an authentication key, accepting a connection, and sending data. It uses a context manager for both the listener and the connection. ```python from multiprocessing.connection import Listener from array import array address = ('localhost', 6000) # family is deduced to be 'AF_INET' with Listener(address, authkey=b'secret password') as listener: with listener.accept() as conn: print('connection accepted from', listener.last_accepted) conn.send([2.25, None, 'junk', float]) conn.send_bytes(b'hello') ``` -------------------------------- ### Multiprocessing Pool Example Source: https://docs.python.org/3/library/multiprocessing.html Basic setup for using a multiprocessing Pool. This snippet is a starting point for parallel task execution. ```python import multiprocessing import time import random import sys ``` -------------------------------- ### Get Current First Weekday Setting Source: https://docs.python.org/3/library/calendar.html Retrieves the current setting for which day of the week starts a week. No setup is required. ```python import calendar calendar.firstweekday() ``` -------------------------------- ### Example .pth file content Source: https://docs.python.org/3/library/site.html This example shows the content of a `.pth` file, which specifies directories to be added to `sys.path`. Lines starting with `#` are comments, and blank lines are ignored. Executable lines starting with `import` are also supported. ```python # foo package configuration foo bar bletch ``` -------------------------------- ### turtle.setup() Source: https://docs.python.org/3/library/turtle.html Sets the size and position of the main window. Arguments control width, height, and starting position from the screen edges. ```APIDOC ## turtle.setup(_width =_CFG['width']_, _height =_CFG['height']_, _startx =_CFG['leftright']_, _starty =_CFG['topbottom']_) ### 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) - Optional - if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen - **height** (integer or float) - Optional - if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen - **startx** (integer or None) - Optional - if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if `None`, center window horizontally - **starty** (integer or None) - Optional - if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if `None`, center window vertically ### Request Example ```python screen.setup (width=200, height=200, startx=0, starty=0) # sets window to 200x200 pixels, in upper left of screen screen.setup(width=.75, height=0.5, startx=None, starty=None) # sets window to 75% of screen by 50% of screen and centers ``` ``` -------------------------------- ### Example Server Code Source: https://docs.python.org/3/library/multiprocessing.html Demonstrates setting up a listener with authentication, accepting a connection, and sending data. ```APIDOC ## Example Server Code ### Description This example illustrates how to create a `Listener` with an authentication key, accept an incoming connection, and then send data and bytes to the connected client. ### Code ```python from multiprocessing.connection import Listener from array import array address = ('localhost', 6000) # family is deduced to be 'AF_INET' with Listener(address, authkey=b'secret password') as listener: with listener.accept() as conn: print('connection accepted from', listener.last_accepted) conn.send([2.25, None, 'junk', float]) conn.send_bytes(b'hello') ``` ``` -------------------------------- ### count() Example Source: https://docs.python.org/3/library/itertools.html Creates an iterator that returns evenly spaced values starting from 'start'. Useful for generating sequences of numbers. ```python from itertools import count # Get the first 5 elements starting from 10 with a step of 1 list(count(10))[:5] ``` -------------------------------- ### Extending EnvBuilder to Install Setuptools and Pip Source: https://docs.python.org/3/library/venv.html This script demonstrates how to subclass `venv.EnvBuilder` to automatically install setuptools and pip into a newly created virtual environment. It includes methods for handling installation progress and managing subprocess output. ```python import os import os.path from subprocess import Popen, PIPE import sys from threading import Thread from urllib.parse import urlsplit 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, _, _ = urlsplit(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. ``` -------------------------------- ### 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(_context_) ### Description Installs activation scripts appropriate to the platform into the virtual environment. ### Parameters * **_context_**: The context object for the virtual environment creation. ``` -------------------------------- ### Get Specific Installation Path Source: https://docs.python.org/3/library/sysconfig.html Retrieves a specific installation path by its name, optionally using a specified scheme, variables, and expansion. ```python sysconfig.get_path(_name_[, _scheme_[, _vars_[, _expand_]]]) ``` -------------------------------- ### DocTestParser 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 a single DocTest, a list of examples, or to parse a string into examples and text. ```APIDOC ## Class 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** - The string from which to extract doctest examples. - **globs** (dict) - Attributes for the new `DocTest` object. - **name** (string) - Name for the new `DocTest` object. - **filename** (string) - Filename for the new `DocTest` object. - **lineno** (int) - Line number for the new `DocTest` object. #### 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** - The string from which to extract doctest examples. - **name** (string) - 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** - The string to parse. - **name** (string) - Optional - A name identifying this string, used for error messages. Defaults to ''. ``` -------------------------------- ### Basic Subcommand Setup with argparse Source: https://docs.python.org/3/library/argparse.html Demonstrates how to set up a top-level parser with subparsers for 'a' and 'b' commands, each with their own arguments. Use this to create applications with distinct functionalities. ```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) ``` -------------------------------- ### Using patch.start() and patch.stop() in setUp/tearDown Source: https://docs.python.org/3/library/unittest.mock-examples.html Manage patches by calling patcher.start() in setUp and patcher.stop() in tearDown. This approach requires careful handling to ensure stop() is always called. ```python import unittest from unittest.mock import patch 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() ``` -------------------------------- ### Example Command Line Usage Source: https://docs.python.org/3/library/optparse.html Illustrates how users can invoke a script with defined optparse options, demonstrating a common command-line pattern. ```bash --file=outfile -q ``` -------------------------------- ### Get Distribution instance Source: https://docs.python.org/3/library/importlib.metadata.html Retrieves a Distribution instance for a named installed package. ```python >>> from importlib.metadata import distribution >>> dist = distribution('wheel') >>> type(dist) ``` -------------------------------- ### Server.start_serving() Source: https://docs.python.org/3/library/asyncio-eventloop.html Starts the server accepting connections. This method is idempotent. ```APIDOC ## Server.start_serving() ### Description Start accepting connections. This method is idempotent, so it can be called when the server is already serving. The `_start_serving` keyword-only parameter to `loop.create_server()` and `asyncio.start_server()` allows creating a Server object that is not accepting connections initially. In this case `Server.start_serving()`, or `Server.serve_forever()` can be used to make the Server start accepting connections. ### Method `_async _start_serving()` ### Added in version 3.7 ``` -------------------------------- ### test.support.import_helper.modules_setup Source: https://docs.python.org/3/library/test.html Returns a copy of `sys.modules`. ```APIDOC ## test.support.import_helper.modules_setup ### Description Return a copy of `sys.modules`. ### Usage ```python original_modules = test.support.import_helper.modules_setup() ``` ``` -------------------------------- ### 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. The limit is set by the start() function and requires tracemalloc to be tracing memory allocations. ```python tracemalloc.get_traceback_limit() ``` -------------------------------- ### 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(_context_) ### 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. ### Parameters * **_context_**: The context object for the virtual environment creation. ``` -------------------------------- ### Start Tracing Memory Allocations Source: https://docs.python.org/3/library/tracemalloc.html Starts tracing Python memory allocations by installing hooks. Optionally limits the number of frames stored in tracebacks. Use the PYTHONTRACEMALLOC environment variable or -X command-line option to start tracing at startup. ```python tracemalloc.start(_nframe : int = 1_) ``` -------------------------------- ### Using enumerate to get index and value Source: https://docs.python.org/3/library/functions.html Demonstrates how to use the enumerate function to iterate over a sequence and get both the index and the value of each item. The start parameter can be used to set the initial index. ```python >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] ``` -------------------------------- ### post_setup Source: https://docs.python.org/3/library/venv.html A placeholder method for third-party implementations to pre-install packages or perform other post-creation steps. ```APIDOC ## post_setup(_context_) ### Description A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps. ### Parameters * **_context_**: The context object for the virtual environment creation. ``` -------------------------------- ### Get Completer Function Source: https://docs.python.org/3/library/readline.html Retrieves the currently installed completer function. Returns None if no completer is set. ```python readline.get_completer() ``` -------------------------------- ### Basic HTTP Authentication Setup Source: https://docs.python.org/3/library/urllib.request.html Illustrates the initial import statement for setting up basic HTTP authentication. Further implementation details would follow this import. ```python import urllib.request ``` -------------------------------- ### 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 from importlib.metadata import metadata wheel_metadata = metadata('wheel') ``` -------------------------------- ### UDPServer Example Source: https://docs.python.org/3/library/socketserver.html This example shows how to set up a UDP server. Similar to `TCPServer`, it requires a custom request handler. ```Python import socketserver class MyUDPHandler(socketserver.BaseRequestHandler): def handle(self): data = self.request.recvfrom(1024)[0].strip() print(f"Received: {data.decode()}") self.request.sendto(data.upper(), self.client_address) if __name__ == "__main__": HOST, PORT = "localhost", 0 with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server: server.serve_forever() ``` -------------------------------- ### Create and Run Executable Archive Source: https://docs.python.org/3/library/zipapp.html Demonstrates creating an executable zip archive from a directory and then running it. The archive executes the 'main' function from the 'myapp' module. ```bash $ python -m zipapp myapp -m "myapp:main" $ python myapp.pyz ``` -------------------------------- ### copytree example with ignore_patterns Source: https://docs.python.org/3/library/shutil.html This example demonstrates how to use `copytree` with `ignore_patterns` to exclude specific files or directories during the copy operation. It copies a source directory to a destination, ignoring all `.pyc` files and any files or directories starting with `tmp`. ```APIDOC ## copytree with ignore_patterns ### Description Copies a directory tree, ignoring files matching specified patterns. ### Usage ```python from shutil import copytree, ignore_patterns copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*')) ``` ### Parameters - `source`: The source directory to copy. - `destination`: The destination directory. - `ignore`: A callable that takes a directory path and a list of names within that directory and returns a list of names to ignore. `ignore_patterns` is a helper function to create such a callable. ``` -------------------------------- ### Basic FTP Session Example Source: https://docs.python.org/3/library/ftplib.html Demonstrates a typical FTP session including connection, login, directory change, 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@ '230 Login successful.' >>> ftp.cwd('debian') # change into "debian" directory '250 Directory successfully changed.' >>> ftp.retrlines('LIST') # list directory contents -rw-rw-r-- 1 1176 1176 1063 Jun 15 10:18 README ... drwxr-sr-x 5 1176 1176 4096 Dec 19 2000 pool drwxr-sr-x 4 1176 1176 4096 Nov 17 2008 project drwxr-xr-x 3 1176 1176 4096 Oct 10 2012 tools '226 Directory send OK.' >>> with open('README', 'wb') as fp: >>> ftp.retrbinary('RETR README', fp.write) '226 Transfer complete.' >>> ftp.quit() '221 Goodbye.' ``` -------------------------------- ### tracemalloc.get_traceback_limit() Source: https://docs.python.org/3/library/tracemalloc.html Gets the maximum number of frames stored in the traceback for a memory allocation trace. The limit is configured by the start() function. ```APIDOC ## tracemalloc.get_traceback_limit() ### Description Get the maximum number of frames stored in the traceback of a trace. The `tracemalloc` module must be tracing memory allocations to get the limit, otherwise an exception is raised. The limit is set by the `start()` function. ``` -------------------------------- ### Start an HTTP server for documentation Source: https://docs.python.org/3/library/pydoc.html Start an HTTP server on a specified port to browse documentation in a web browser. Port `0` selects an arbitrary unused port. This server is intended for local development only. ```shell python -m pydoc -p 1234 ``` -------------------------------- ### Get Distribution Version Source: https://docs.python.org/3/library/importlib.metadata.html Retrieves the installed version string for a specified distribution package. Raises PackageNotFoundError if the package is not found. ```python from importlib.metadata import version version('wheel') ``` -------------------------------- ### Standard Formats Examples Source: https://docs.python.org/3/library/struct.html Demonstrates the use of standard format strings for packing and calculating sizes, highlighting differences between 64-bit and 32-bit architectures. ```python >>> calcsize('>> pack('>> calcsize('@llh') 18 >>> pack('@llh', 1, 2, 3) == pack('>> calcsize('>> calcsize('@llh0l') 24 >>> pack('@llh0l', 1, 2, 3) == pack('>> calcsize('>> calcsize('@llh0l') 12 >>> pack('@llh0l', 1, 2, 3) == pack('>> util.locate() PosixPath('/home/gustav/example/lib/site-packages/wheel/util.py') ``` -------------------------------- ### Usage example for fetching 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 ``` -------------------------------- ### Get package version using importlib.metadata Source: https://docs.python.org/3/library/importlib.metadata.html Retrieves the version string of an installed package ('wheel') using the version() function from importlib.metadata. ```python >>> from importlib.metadata import version >>> version('wheel') '0.32.3' ``` -------------------------------- ### Timeit CLI Option: Setup Statement Source: https://docs.python.org/3/library/timeit.html Provide a statement to be executed once initially before timing begins. The default is 'pass'. Multiple -s options can be used. ```bash -s S, --setup=S ``` -------------------------------- ### Setup Threading State Source: https://docs.python.org/3/library/test.html Returns the current thread count and a copy of any dangling threads. This is used to establish a baseline before starting new threads. ```python test.support.threading_helper.threading_setup() ``` -------------------------------- ### Running an HTTP Server Source: https://docs.python.org/3/library/http.server.html This example demonstrates how to create and run a basic HTTP server using the HTTPServer class. ```APIDOC ## Running an HTTP Server ### Description This function demonstrates how to set up and start an HTTP server. ### Parameters - `server_class`: The class to use for the server (defaults to `HTTPServer`). - `handler_class`: The request handler class to use (defaults to `BaseHTTPRequestHandler`). ### Code Example ```python def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler): server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.serve_forever() ``` ``` -------------------------------- ### Set Pen Size Source: https://docs.python.org/3/library/turtle.html Sets the thickness of the line drawn by the turtle. The example shows how to get the current pensize and then set it to a new value. ```python >>> turtle.pensize() 1 >>> turtle.pensize(10) # from here on lines of width 10 are drawn ``` -------------------------------- ### Get files for a distribution Source: https://docs.python.org/3/library/importlib.metadata.html Retrieves all files associated with an installed distribution package. Returns None if the distribution is found but file records are missing. ```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 ``` -------------------------------- ### ThreadingUDPServer Example Source: https://docs.python.org/3/library/socketserver.html Demonstrates how to create a ThreadingUDPServer by inheriting from ThreadingMixIn and UDPServer. The mix-in class should be listed first. ```python class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass ``` -------------------------------- ### curses.setupterm(_term=None_, _fd=-1_) Source: https://docs.python.org/3/library/curses.html Initializes the terminal using the TERM environment variable or a specified name and file descriptor. Raises `curses.error` on failure. ```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. Raise a `curses.error` if the terminal could not be found or its terminfo database entry could not be read. If the terminal has already been initialized, this function has no effect. ### Parameters #### Path Parameters - **_term_** (str) - Optional - The terminal name. Defaults to the value of the `TERM` environment variable. - **_fd_** (int) - Optional - The file descriptor for initialization sequences. Defaults to `sys.stdout`'s file descriptor. ### Method `curses.setupterm(_term=None_, _fd=-1_)` ``` -------------------------------- ### Certificate Chain Example Source: https://docs.python.org/3/library/ssl.html A certificate chain file concatenates multiple PEM-encoded certificates, starting with the specific certificate and progressing up to 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----- ``` -------------------------------- ### Basic XML-RPC Server Setup Source: https://docs.python.org/3/library/xmlrpc.server.html Sets up a basic XML-RPC server, registers functions like pow and a custom adder, and registers an instance with methods. Ensure the server is running before attempting to connect with a client. ```python from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestHandler class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2',) with SimpleXMLRPCServer(('localhost', 8000), requestHandler=RequestHandler) as server: server.register_introspection_functions() server.register_function(pow) def adder_function(x, y): return x + y server.register_function(adder_function, 'add') class MyFuncs: def mul(self, x, y): return x * y server.register_instance(MyFuncs()) server.serve_forever() ``` -------------------------------- ### Get Preferred Schemes Dictionary Source: https://docs.python.org/3/library/sysconfig.html Returns a dictionary of preferred scheme names for the current platform. This is intended for Python implementers and redistributors to manage package installations. ```python sysconfig._get_preferred_schemes() ``` -------------------------------- ### Basic Logging Example Source: https://docs.python.org/3/library/logging.html A simple, idiomatic example of how to use the logging module. It demonstrates basic configuration and message logging. ```python import logging logging.warning('This is a warning message') logging.error('This is an error message') logging.critical('This is a critical message') logging.info('This is an info message') logging.debug('This is a debug message') ``` -------------------------------- ### Get Outer Frames Source: https://docs.python.org/3/library/inspect.html Obtains a list of FrameInfo objects for a given frame and all its outer callers. The list starts with the current frame and ends with the outermost call. ```python inspect.getouterframes(_frame_ , _context =1_) ``` -------------------------------- ### Get source lines and starting line number for an object Source: https://docs.python.org/3/library/inspect.html Use `inspect.getsourcelines()` to obtain a list of source code lines and the starting line number for an object (module, class, method, function, etc.). Raises `OSError` if source code retrieval fails or `TypeError` for built-in objects. ```python inspect.getsourcelines(_object_) ``` -------------------------------- ### Hello World Asyncio Example Source: https://docs.python.org/3/library/asyncio.html A basic example demonstrating how to run an asynchronous function using asyncio.run(). This snippet prints messages with a delay. ```python import asyncio async def main(): print('Hello ...') await asyncio.sleep(1) print('... World!') asyncio.run(main()) ``` -------------------------------- ### Iterate and Print Files Using os.scandir Source: https://docs.python.org/3/library/os.html Use os.scandir() within a 'with' statement to iterate through directory entries. This example prints the names of files that do not start with a dot. ```python with os.scandir(path) as it: for entry in it: if not entry.name.startswith('.') and entry.is_file(): print(entry.name) ``` -------------------------------- ### Initialize ConfigParser with Defaults Source: https://docs.python.org/3/library/configparser.html Creates a ConfigParser instance with default values for 'bar' and 'baz'. Reads configuration from 'example.cfg'. ```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 HTML Parsing Example Source: https://docs.python.org/3/library/html.parser.html Demonstrates how to subclass HTMLParser to handle start tags, end tags, and data encountered during parsing. 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!

') ``` -------------------------------- ### Matching hidden files with glob Source: https://docs.python.org/3/library/glob.html Shows how `glob.glob()` by default does not match files starting with a dot (`.`). Examples demonstrate matching regular files and then specifically hidden files. ```python import glob print(glob.glob('*.gif')) print(glob.glob('.c*')) ``` -------------------------------- ### Dictionary Creation Examples Source: https://docs.python.org/3/library/stdtypes.html Illustrates various ways to create dictionaries that are equal in content, including using keyword arguments, literal syntax, the `zip` function, and different ordering of items. ```python >>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> f = dict({'one': 1, 'three': 3}, two=2) >>> a == b == c == d == e == f True ``` -------------------------------- ### Basic Format String Examples Source: https://docs.python.org/3/library/string.html Illustrates how to reference positional and keyword arguments, attributes, and elements within format strings. ```python "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'. ``` -------------------------------- ### Find Adverbs and Their Positions Source: https://docs.python.org/3/library/re.html Use re.finditer to get Match objects for all adverbs, providing their start and end positions along with the matched text. This allows for more detailed analysis than findall(). ```python >>> text = "He was carefully disguised but captured quickly by police." >>> for m in re.finditer(r"\w+ly\b", text): ... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) 07-16: carefully 40-47: quickly ``` -------------------------------- ### Basic RobotFileParser Usage Example Source: https://docs.python.org/3/library/urllib.robotparser.html Demonstrates setting a URL, reading the robots.txt file, and checking crawl delay, request rate, and fetch permissions for a user agent. ```python import urllib.robotparser rp = urllib.robotparser.RobotFileParser() rp.set_url("http://www.pythontest.net/robots.txt") rp.read() rrate = rp.request_rate("*") rrate.requests rrate.seconds rp.crawl_delay("*") rp.can_fetch("*", "http://www.pythontest.net/") rp.can_fetch("*", "http://www.pythontest.net/no-robots-here/") ``` -------------------------------- ### Getting All Non-Overlapping Matching Blocks Source: https://docs.python.org/3/library/difflib.html Returns a list of triples describing all non-overlapping matching subsequences between two sequences. Each triple indicates the start index and length of a match in both sequences. ```python >>> s = SequenceMatcher(None, "abxcd", "abcd") >>> s.get_matching_blocks() [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] ``` -------------------------------- ### Example: GetWindowRect with Output Parameters Source: https://docs.python.org/3/library/ctypes.html Demonstrates wrapping the win32 `GetWindowRect` function to handle output parameters. ```APIDOC ## Example: GetWindowRect with Output Parameters ### Description This example demonstrates wrapping the win32 `GetWindowRect` function, which retrieves window dimensions into a supplied `RECT` structure, to handle output parameters. ### Code ```python from ctypes import POINTER, WINFUNCTYPE, windll, WinError from ctypes.wintypes import BOOL, HWND, RECT prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT)) paramflags = (1, "hwnd"), (2, "lprect") GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags) # The GetWindowRect function now returns a RECT instance when called. ``` ``` -------------------------------- ### Example of using Timer for scheduled execution Source: https://docs.python.org/3/library/threading.html This snippet demonstrates how to schedule a function to run after a specified delay using the Timer class. Ensure the Timer is started with `t.start()` to initiate the countdown. ```python def hello(): print("hello, world") t = Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printed ``` -------------------------------- ### Get Preferred Scheme Name Source: https://docs.python.org/3/library/sysconfig.html Retrieves a preferred scheme name for a given installation layout key ('prefix', 'home', or 'user'). The returned scheme name can be used with other sysconfig functions. ```python sysconfig.get_preferred_scheme(_key_) ``` -------------------------------- ### Create and Run a 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 keep it running indefinitely or 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() ``` -------------------------------- ### tracemalloc.start(_nframe : int = 1_) Source: https://docs.python.org/3/library/tracemalloc.html Starts tracing Python memory allocations by installing hooks. It limits collected tracebacks to _nframe_ frames, defaulting to 1. Storing more frames increases overhead. ```APIDOC ## tracemalloc.start(_nframe : int = 1_) ### Description Start tracing Python memory allocations: install hooks on Python memory allocators. Collected tracebacks of traces will be limited to _nframe_ frames. By default, a trace of a memory block only stores the most recent frame: the limit is `1`. _nframe_ must be greater or equal to `1`. You can still read the original number of total frames that composed the traceback by looking at the `Traceback.total_nframe` attribute. Storing more than `1` frame is only useful to compute statistics grouped by `'traceback'` or to compute cumulative statistics: see the `Snapshot.compare_to()` and `Snapshot.statistics()` methods. Storing more frames increases the memory and CPU overhead of the `tracemalloc` module. Use the `get_tracemalloc_memory()` function to measure how much memory is used by the `tracemalloc` module. The `PYTHONTRACEMALLOC` environment variable (`PYTHONTRACEMALLOC=NFRAME`) and the `-X` `tracemalloc=NFRAME` command line option can be used to start tracing at startup. See also `stop()`, `is_tracing()` and `get_traceback_limit()` functions. ```