### Customize Installation Directories via setup.py Source: https://docs.python.org/3.10/install/index.html Examples of overriding default installation paths such as scripts, libraries, and data directories using command-line arguments in setup.py. ```bash python setup.py install --home=~ --install-scripts=scripts python setup.py install --install-scripts=/usr/local/bin python setup.py install --install-lib=Site python setup.py install --home=~ \ --install-purelib=python/lib \ --install-platlib=python/lib.$PLAT \ --install-scripts=python/scripts \ --install-data=python/data python setup.py install --home=~/python \ --install-purelib=lib \ --install-platlib='lib.$PLAT' \ --install-scripts=scripts \ --install-data=data ``` -------------------------------- ### Managing Patches with setUp and tearDown in Python Source: https://docs.python.org/3.10/library/unittest.mock-examples.html Illustrates an alternative approach to managing patches in Python tests by using `patcher.start()` in `setUp` and `patcher.stop()` in `tearDown`. This method provides explicit control over the patch lifecycle, ensuring patches are applied and removed correctly around test execution. ```python from unittest.mock import patch import unittest # Assume mymodule.foo exists 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() # Example usage (not part of the class definition itself) # test_instance = MyTest('test_foo') # test_instance.run() ``` -------------------------------- ### Link Extension with Math Library using Setup File Source: https://docs.python.org/3.10/install/index.html This example demonstrates how to link a Python extension module ('foo') with the math library ('libm.a') by adding '-lm' to its definition in the 'Setup' file. This is a common practice when a specific library is required on a platform. ```text foo foomodule.c -lm ``` -------------------------------- ### Function: setup() Source: https://docs.python.org/3.10/distutils/apiref.html The primary function used in setup.py scripts to define package metadata, build requirements, and installation configuration. ```APIDOC ## POST distutils.core.setup ### Description The basic do-everything function that processes package metadata and build instructions for a Python distribution. ### Method FUNCTION CALL ### Parameters #### Request Body - **name** (string) - Required - The name of the package - **version** (string) - Required - The version number of the package - **description** (string) - Optional - A single line describing the package - **author** (string) - Optional - The name of the package author - **packages** (list) - Optional - A list of Python packages to manipulate - **ext_modules** (list) - Optional - A list of distutils.core.Extension instances - **install_requires** (list) - Optional - Dependencies for the package ### Request Example { "name": "my_package", "version": "1.0.0", "author": "John Doe", "packages": ["mypkg"] } ### Response #### Success Response (200) - **Distribution** (object) - Returns the Distribution instance created by the setup process. ``` -------------------------------- ### Query site-packages and user directories in Python Source: https://docs.python.org/3.10/whatsnew/3.2.html Provides examples of using the site module to retrieve installation paths programmatically and via the command line. ```python import site print(site.getsitepackages()) print(site.getuserbase()) print(site.getusersitepackages()) ``` ```bash python -m site --user-base python -m site --user-site ``` -------------------------------- ### Python Distutils: Setup for C Extension Modules Source: https://docs.python.org/3.10/whatsnew/2.0.html An example setup.py script for distributing Python software that includes C extension modules. It defines an `Extension` object specifying compilation details like include directories, source files, and preprocessor macros, then passes this to the `setup` function. ```python from distutils.core import setup, Extension expat_extension = Extension('xml.parsers.pyexpat', define_macros = [('XML_NS', None)], include_dirs = [ 'extensions/expat/xmltok', 'extensions/expat/xmlparse' ], sources = [ 'extensions/pyexpat.c', 'extensions/expat/xmltok/xmltok.c', 'extensions/expat/xmltok/xmlrole.c' ] ) setup (name = "PyXML", version = "0.5.4", ext_modules =[ expat_extension ] ) ``` -------------------------------- ### Example PATH Environment Variable Configuration (Windows) Source: https://docs.python.org/3.10/using/windows.html Provides an example of how a PATH environment variable might be configured on Windows to include a Python installation directory. This example assumes that the first two entries (C:\WINDOWS\system32;C:\WINDOWS;) already existed. Modifying the PATH allows the system to find executables like 'python.exe' and 'pip'. ```text C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.9 ``` -------------------------------- ### Multi-Process Logging Setup and Execution (Python) Source: https://docs.python.org/3.10/howto/logging-cookbook.html Demonstrates the setup and execution of a multi-process logging system. It initializes logging, creates and starts multiple worker processes, and then starts a listener process to handle logs from the workers. The script manages the lifecycle of these processes, ensuring proper shutdown. ```python import logging import logging.config from multiprocessing import Process, Queue, Event # Assume q, stop_event, worker_process, listener_process, and main are defined elsewhere # Assume config_initial is also defined # Log some initial events, just to show that logging in the parent works # normally. logging.config.dictConfig(config_initial) logger = logging.getLogger('setup') logger.info('About to create workers ...') workers = [] for i in range(5): wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(config_worker,)) # config_worker should be defined workers.append(wp) wp.start() logger.info('Started worker: %s', wp.name) logger.info('About to create listener ...') stop_event = Event() lp = Process(target=listener_process, name='listener', args=(q, stop_event, config_listener)) # config_listener should be defined lp.start() logger.info('Started listener') # We now hang around for the workers to finish their work. for wp in workers: wp.join() # Workers all done, listening can now stop. # Logging in the parent still works normally. logger.info('Telling listener to stop ...') stop_event.set() lp.join() logger.info('All done.') if __name__ == '__main__': main() # Assuming main function contains the above logic ``` -------------------------------- ### Perform Incremental Build and Install Source: https://docs.python.org/3.10/install/index.html Demonstrates how to split the standard installation process into two distinct steps: building the modules and then installing them. This is useful for environments where build and install permissions differ. ```bash python setup.py build python setup.py install ``` -------------------------------- ### Installing Scripts with distutils.core.setup() Source: https://docs.python.org/3.10/distutils/setupscript.html Demonstrates how to install executable Python scripts using the 'scripts' keyword argument in distutils.core.setup(). Distutils automatically adjusts the shebang line to point to the current interpreter. ```python setup(..., scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val'] ) ``` -------------------------------- ### Control Patching with Patcher start() and stop() (Python) Source: https://docs.python.org/3.10/library/unittest.mock.html Illustrates how to manually manage patches using the `start()` and `stop()` methods of a patcher object. This is useful for applying patches in `setUp` methods or for more complex patching scenarios. The `start()` method applies the patch and returns the mock if one is created, while `stop()` undoes the patch. ```python from unittest.mock import patch # Manual patching with start() and stop() patcher = patch('package.module.ClassName') # Assume 'package.module' and 'ClassName' exist for this example # original = module.ClassName # This would require importing package.module 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 # Example within a unittest.TestCase setUp and tearDown import unittest 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 pass # Example using addCleanup for automatic stop class MyTestWithCleanup(unittest.TestCase): def setUp(self): patcher = patch('package.module.Class') self.MockClass = patcher.start() self.addCleanup(patcher.stop) def test_something_else(self): # assert package.module.Class is self.MockClass pass # To run these tests, you would typically use unittest.main() # For demonstration, we just show the structure. ``` -------------------------------- ### tzinfo Example Class Setup (Python) Source: https://docs.python.org/3.10/library/datetime.html This Python code sets up basic `timedelta` constants and imports necessary classes from the `datetime` module. It serves as a foundation for defining custom `tzinfo` subclasses, such as one that captures the platform's local time. ```python from datetime import tzinfo, timedelta, datetime ZERO = timedelta(0) HOUR = timedelta(hours=1) SECOND = timedelta(seconds=1) # A class capturing the platform's idea of local time. # (May result in wrong values on historical times in # timezones where UTC offset and/or the DST rules had ``` -------------------------------- ### Verify CGI Script Installation with cgi.py Source: https://docs.python.org/3.10/library/cgi.html This example demonstrates how to test the installation of a CGI script by accessing a URL. It assumes the cgi.py module is installed as a CGI script and will output its environment and form content in HTML format. This helps diagnose server-side issues like incorrect script paths or installation problems. ```text http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home ``` -------------------------------- ### Create a Hello World GUI application with Tkinter Source: https://docs.python.org/3.10/library/tkinter.html A foundational example demonstrating how to initialize a root window, add widgets like frames, labels, and buttons, and start the event loop. It uses the ttk module for themed widgets and the grid geometry manager for layout. ```python from tkinter import * from tkinter import ttk root = Tk() frm = ttk.Frame(root, padding=10) frm.grid() ttk.Label(frm, text="Hello World!").grid(column=0, row=0) ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0) root.mainloop() ``` -------------------------------- ### Verify Python Version Installed via NuGet Source: https://docs.python.org/3.10/using/windows.html Provides examples of how to verify the installed Python version after using NuGet. It shows how to access the Python executable within the installed package's `tools` directory and check its version using the `-V` flag. ```bash # Without -ExcludeVersion > .\python.3.5.2\tools\python.exe -V Python 3.5.2 # With -ExcludeVersion > .\python\tools\python.exe -V Python 3.5.2 ``` -------------------------------- ### Implement setUp and tearDown fixtures Source: https://docs.python.org/3.10/library/unittest.html Shows how to use setUp to initialize test fixtures before each test method and tearDown to clean up resources afterwards. This ensures tests are isolated and state is reset. ```python import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() 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') ``` -------------------------------- ### Patchers: start() and stop() Source: https://docs.python.org/3.10/library/unittest.mock.html Manage the lifecycle of patches manually using start() and stop() methods. This is useful for applying patches in setUp methods or for more complex patching scenarios. ```APIDOC ## POST /patcher/{patch_id}/start ### Description Starts an active patcher, applying the patch to the target. ### Method POST ### Endpoint /patcher/{patch_id}/start ### Parameters #### Path Parameters - **patch_id** (string) - Required - The unique identifier of the patcher. ### Response #### Success Response (200) - **message** (string) - Confirmation that the patcher has started. ## POST /patcher/{patch_id}/stop ### Description Stops an active patcher, undoing the patch. ### Method POST ### Endpoint /patcher/{patch_id}/stop ### Parameters #### Path Parameters - **patch_id** (string) - Required - The unique identifier of the patcher. ### Response #### Success Response (200) - **message** (string) - Confirmation that the patcher has stopped. ``` -------------------------------- ### POP3 Client Example in Python Source: https://docs.python.org/3.10/library/poplib.html A minimal example demonstrating how to connect to a POP3 server, authenticate, retrieve, and print all messages from a mailbox. This example requires the 'poplib' and 'getpass' modules. ```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) ``` -------------------------------- ### Configure Installation Schemes via Distutils Config File Source: https://docs.python.org/3.10/install/index.html Demonstrates how to define persistent custom installation schemes using the [install] section in a Distutils configuration file. ```ini [install] install-base=$HOME install-purelib=python/lib install-platlib=python/lib.$PLAT install-scripts=python/scripts install-data=python/data [install] install-base=$HOME/python install-purelib=lib install-platlib=lib.$PLAT install-scripts=scripts install-data=data ``` -------------------------------- ### Basic Argparse Setup Source: https://docs.python.org/3.10/howto/argparse.html Demonstrates the minimal setup for an ArgumentParser object. It shows how to create a parser and parse arguments, including the automatic generation of a help message. ```python import argparse parser = argparse.ArgumentParser() parser.parse_args() ``` -------------------------------- ### Configure setup.py for multiple module distribution Source: https://docs.python.org/3.10/distutils/examples.html Shows how to extend the setup script to include multiple modules by passing a list of module names to the 'py_modules' parameter. This is suitable for projects containing several independent modules. ```python from distutils.core import setup setup(name='foobar', version='1.0', py_modules=['foo', 'bar'], ) ``` -------------------------------- ### Get Installation Prefixes (C) Source: https://docs.python.org/3.10/c-api/init.html Retrieves platform-independent (`Py_GetPrefix`) and platform-dependent (`Py_GetExecPrefix`) installation directory paths. These functions derive paths based on the program name and environment variables. They return strings pointing to static storage and should not be modified. They return `NULL` if called before `Py_Initialize()` since version 3.10. Primarily useful on Unix. ```c wchar_t *Py_GetPrefix() { // Implementation details... return L"/usr/local"; // Example prefix } wchar_t *Py_GetExecPrefix() { // Implementation details... return L"/usr/local"; // Example exec-prefix } ``` -------------------------------- ### Using addCleanup for Patch Management in Python Source: https://docs.python.org/3.10/library/unittest.mock-examples.html Demonstrates how to use `unittest.TestCase.addCleanup()` in Python to manage patch lifecycles, particularly when exceptions might occur in `setUp`. This ensures that `patcher.stop()` is called even if `setUp` fails, preventing potential issues with lingering patches. ```python from unittest.mock import patch import unittest # Assume mymodule.foo exists class MyTest(unittest.TestCase): def setUp(self): patcher = patch('mymodule.foo') self.addCleanup(patcher.stop) self.mock_foo = patcher.start() def test_foo(self): self.assertIs(mymodule.foo, self.mock_foo) # Example usage (not part of the class definition itself) # test_instance = MyTest('test_foo') # test_instance.run() ``` -------------------------------- ### Define package metadata in setup.py Source: https://docs.python.org/3.10/whatsnew/2.5.html Illustrates how to include dependency information and download URLs in the setup() function for Distutils, enabling better package management. ```python VERSION = '1.0' setup(name='PyPackage', version=VERSION, requires=['numarray', 'zlib (>=1.1.4)'], obsoletes=['OldPackage'], download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz' % VERSION), ) ``` -------------------------------- ### Start and Serve Connections with Asyncio Server Source: https://docs.python.org/3.10/library/asyncio-eventloop.html Shows how to initialize a server and run it indefinitely using the serve_forever coroutine. ```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)) ``` -------------------------------- ### Python: Define functions for testing mutable arguments Source: https://docs.python.org/3.10/library/unittest.mock-examples.html Defines two simple Python functions, `frob` and `grob`, where `grob` calls `frob` and then clears the mutable argument. This setup is used to demonstrate issues with mock assertions. ```python def frob(val): pass def grob(val): """First frob and then clear val""" frob(val) val.clear() ``` -------------------------------- ### Configure data_files in setup.py Source: https://docs.python.org/3.10/distutils/setupscript.html Demonstrates how to install additional files outside the package directory structure using the data_files argument. It accepts a sequence of (directory, files) tuples. ```python setup(..., data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']), ('config', ['cfg/data.cfg'])], ) ``` -------------------------------- ### Configure Extensions with ext_package Source: https://docs.python.org/3.10/distutils/setupscript.html Shows how to use the ext_package argument in the setup function to group multiple extensions under a common base package namespace. ```python from setuptools import setup, Extension setup(..., ext_package='pkg', ext_modules=[Extension('foo', ['foo.c']), Extension('subpkg.bar', ['bar.c'])], ) ``` -------------------------------- ### Define a Python module distribution using setup() Source: https://docs.python.org/3.10/distutils/setupscript.html Demonstrates the use of the setup() function to define package metadata and include multiple sub-packages. This script serves as the central configuration for building and distributing Python modules. ```python #!/usr/bin/env python from distutils.core import setup setup(name='Distutils', version='1.0', description='Python Distribution Utilities', author='Greg Ward', author_email='gward@python.net', url='https://www.python.org/sigs/distutils-sig/', packages=['distutils', 'distutils.command'], ) ``` -------------------------------- ### Mock asynchronous context managers Source: https://docs.python.org/3.10/library/unittest.mock-examples.html Illustrates how to mock asynchronous context managers by leveraging the __aenter__ and __aexit__ attributes, allowing for verification of awaitable calls. ```python import asyncio from unittest.mock import MagicMock class AsyncContextManager: async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): pass mock_instance = MagicMock(AsyncContextManager()) async def main(): async with mock_instance as result: pass asyncio.run(main()) mock_instance.__aenter__.assert_awaited_once() mock_instance.__aexit__.assert_awaited_once() ``` -------------------------------- ### Assert Calls in Any Order with assert_has_calls(any_order=True) Source: https://docs.python.org/3.10/library/unittest.mock-examples.html This example demonstrates the use of `assert_has_calls` with the `any_order=True` argument. This allows you to assert that a specific set of calls has been made, without regard to the order in which they occurred. It's helpful when the sequence of certain calls is not critical. ```python >>> from unittest.mock import MagicMock, call >>> m = MagicMock() >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50') (...) >>> calls = [call.fifty('50'), call(1), call.seven(7)] >>> m.assert_has_calls(calls, any_order=True) ``` -------------------------------- ### Function: run_setup() Source: https://docs.python.org/3.10/distutils/apiref.html Executes a setup script in a controlled environment and returns the resulting Distribution instance. ```APIDOC ## POST distutils.core.run_setup ### Description Runs a setup script and returns the Distribution instance, useful for inspecting metadata or configuration without fully executing the build. ### Parameters #### Request Body - **script_name** (string) - Required - Path to the setup script - **script_args** (list) - Optional - Arguments to pass to the script - **stop_after** (string) - Optional - Execution stage to stop at (init, config, commandline, run) ### Request Example { "script_name": "setup.py", "stop_after": "config" } ### Response #### Success Response (200) - **Distribution** (object) - The Distribution instance populated with metadata. ``` -------------------------------- ### Attach Mocks to Manager and Track Calls with attach_mock Source: https://docs.python.org/3.10/library/unittest.mock-examples.html This example shows how to use `attach_mock` to associate mocks created via `patch` with a manager mock. Once attached, calls to these mocks are recorded in the manager's `mock_calls` attribute, allowing for order verification even when mocks are dynamically created. ```python >>> from unittest.mock import MagicMock, patch >>> manager = MagicMock() >>> with patch('mymodule.Class1') as MockClass1: ... with patch('mymodule.Class2') as MockClass2: ... manager.attach_mock(MockClass1, 'MockClass1') ... manager.attach_mock(MockClass2, 'MockClass2') ... MockClass1().foo() ... MockClass2().bar() >>> manager.mock_calls [call.MockClass1(), call.MockClass1().foo(), call.MockClass2(), call.MockClass2().bar()] ``` -------------------------------- ### GET /doctest/directives Source: https://docs.python.org/3.10/library/doctest.html Configures execution behavior for individual doctest examples using inline directives. ```APIDOC ## GET /doctest/directives ### Description Modifies the behavior of a single doctest example using Python comments. Directives allow enabling (+) or disabling (-) specific option flags like NORMALIZE_WHITESPACE or ELLIPSIS. ### Method GET ### Endpoint /doctest/directives ### Parameters #### Query Parameters - **directive** (string) - Required - The directive string, e.g., "+NORMALIZE_WHITESPACE" or "-ELLIPSIS". ### Request Example # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS ### Response #### Success Response (200) - **status** (string) - Confirmation of the applied directive behavior. #### Response Example { "status": "success", "applied_flags": ["NORMALIZE_WHITESPACE", "ELLIPSIS"] } ``` -------------------------------- ### Install Python Modules with setup.py Source: https://docs.python.org/3.10/install/index.html Installs Python modules using the `setup.py` script. The `--install-base` option allows specifying a custom installation directory, affecting where pure modules are placed. ```bash python setup.py install --install-base=/tmp ``` -------------------------------- ### SimpleXMLRPCServer Example Source: https://docs.python.org/3.10/library/xmlrpc.server.html A complete Python example demonstrating how to set up a SimpleXMLRPCServer, register functions and instances, and handle requests. It includes both the server-side code and the corresponding client-side code to interact with the server. ```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() ``` ```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 ``` -------------------------------- ### Create and run a WSGI server using make_server Source: https://docs.python.org/3.10/library/wsgiref.html Demonstrates how to initialize a WSGI server on a specific host and port using the make_server function. It shows how to serve requests indefinitely using serve_forever or handle a single request using handle_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() ``` -------------------------------- ### INI File Structure Example Source: https://docs.python.org/3.10/library/configparser.html Provides an example of a typical INI file structure, demonstrating sections, key-value pairs, comments, multiline values, and indentation. ```ini [Simple Values] key=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values [All Values Are Strings] values like this: 1000000 or this: 3.14159265359 are they treated as numbers? : no integers, floats and booleans are held as: strings can use the API to get converted values directly: true [Multiline Values] chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day [No Values] key_without_value empty string value here = [You can use comments] # like this ; or this # By default only in an empty line. # Inline comments can be harmful because they prevent users # from using the delimiting characters as parts of values. # That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too? ``` -------------------------------- ### Create a basic WSGI server using wsgiref Source: https://docs.python.org/3.10/library/wsgiref.html Demonstrates how to initialize a WSGI application with testing defaults and serve it on a local port. It uses the make_server utility to handle incoming requests and return the environment dictionary. ```python from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_server def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) ret = [("%s: %s\n" % (key, value)).encode("utf-8") for key, value in environ.items()] return ret with make_server('', 8000, simple_app) as httpd: print("Serving on port 8000...") httpd.serve_forever() ``` -------------------------------- ### Configure setup.py for a single module distribution Source: https://docs.python.org/3.10/distutils/examples.html Demonstrates the minimal setup script required to distribute a single Python module named 'foo.py'. It uses the distutils.core.setup function to define the distribution name, version, and the list of modules to include. ```python from distutils.core import setup setup(name='foo', version='1.0', py_modules=['foo'], ) ``` -------------------------------- ### Download, Build, and Install Custom OpenSSL Source: https://docs.python.org/3.10/using/unix.html This sequence of commands downloads a specified version of OpenSSL from its official source, extracts it, configures it with custom installation paths, and then builds and installs it using the `install_sw` target to avoid overwriting existing configurations. ```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 ``` -------------------------------- ### Create SHA-224 Hash and Get Hex Digest (Python) Source: https://docs.python.org/3.10/library/hashlib.html A more condensed example showing how to create a SHA-224 hash object and immediately get its hexadecimal digest from a byte string. ```python import hashlib print(hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()) ``` -------------------------------- ### Comparing Mock Calls with Expected Calls in Python Source: https://docs.python.org/3.10/library/unittest.mock-examples.html Shows how to create a list of expected calls using the `call` helper and compare it against the `call_args_list` of a mock object to verify all interactions. ```python from unittest.mock import Mock, call mock = Mock(return_value=None) mock(1, 2, 3) mock(4, 5, 6) mock() expected = [call(1, 2, 3), call(4, 5, 6), call()] print(mock.call_args_list == expected) ``` -------------------------------- ### Configure Windows Process STARTUPINFO Source: https://docs.python.org/3.10/library/subprocess.html Demonstrates how to instantiate the STARTUPINFO class and configure dwFlags to enable standard handle redirection and window display settings for a subprocess. ```python import subprocess si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW ``` -------------------------------- ### Install Python using NuGet Package Manager Source: https://docs.python.org/3.10/using/windows.html Shows how to install the latest 64-bit and 32-bit versions of Python using the `nuget.exe` command-line tool. This method is suitable for build systems and environments where a system-wide Python installation is not desired. ```bash nuget.exe install python -ExcludeVersion -OutputDirectory . nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory . ``` -------------------------------- ### Cmd.preloop() Source: https://docs.python.org/3.10/library/cmd.html Hook method executed once when `cmdloop()` is called. Can be overridden for setup before the command loop starts. ```APIDOC ## Cmd.preloop() ### Description Hook method executed once when `cmdloop()` is called. This method is a stub in `Cmd`; it exists to be overridden by subclasses. ### Method `preloop()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example of overriding preloop in a subclass: # class MyCmd(Cmd): # def preloop(self): # print("Starting command loop...") ``` ### Response #### Success Response (200) No specific return value is expected, as this is a hook. #### Response Example ```json { "status": "Setup complete" } ``` ``` -------------------------------- ### GET /files Source: https://docs.python.org/3.10/library/importlib.metadata.html Retrieve the list of files installed by a distribution. ```APIDOC ## GET /files ### Description Returns all files installed by a distribution, including properties like size and hash. ### Method GET ### Parameters #### Query Parameters - **distribution** (string) - Required - The name of the package. ### Response #### Success Response (200) - **files** (array) - A list of PackagePath objects. #### Response Example [ { "path": "wheel/util.py", "size": 859, "hash": "sha256:bYkw5oMccfazVCoYQwKkkemoVyMAFoR34mmKBx8R1NI" } ] ``` -------------------------------- ### GET /entry_points Source: https://docs.python.org/3.10/library/importlib.metadata.html Retrieve and filter entry points for installed packages. ```APIDOC ## GET /entry_points ### Description Returns a collection of entry points for installed packages. Can be filtered by group or name. ### Method GET ### Parameters #### Query Parameters - **group** (string) - Optional - The entry point group to filter by (e.g., 'console_scripts'). - **name** (string) - Optional - The specific name of the entry point to retrieve. ### Response #### Success Response (200) - **EntryPoints** (object) - A sequence of EntryPoint objects. #### Response Example { "name": "wheel", "value": "wheel.cli:main", "group": "console_scripts" } ``` -------------------------------- ### Python Database Connection Context Manager Example Source: https://docs.python.org/3.10/whatsnew/2.6.html Demonstrates a Python class 'DatabaseConnection' implementing the context manager protocol. The __enter__ method starts a transaction and returns a cursor, while __exit__ handles committing the transaction on success or rolling back on exception. ```python class DatabaseConnection: # Database interface def cursor(self): """Returns a cursor object and starts a new transaction""" pass def commit(self): """Commits current transaction""" pass def rollback(self): """Rolls back current transaction""" pass def __enter__(self): # Code to start a new transaction cursor = self.cursor() return cursor def __exit__(self, type, value, tb): if tb is None: # No exception, so commit self.commit() else: # Exception occurred, so rollback. self.rollback() # return False ``` -------------------------------- ### Getting Start and End Indices of Regex Matches in Python Source: https://docs.python.org/3.10/library/re.html Demonstrates how to find the start and end indices of a matched substring within the original string using the start() and end() methods of a Match object. These indices can be specified for individual groups or the entire match. ```python import re m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") # For the entire match (group 0) start_index = m.start(0) end_index = m.end(0) print(f"Match: {m.string[start_index:end_index]}") # For a specific group (e.g., group 1) start_index_1 = m.start(1) end_index_1 = m.end(1) print(f"Group 1: {m.string[start_index_1:end_index_1]}") ``` -------------------------------- ### Check Package Metadata with setup.py check (Python) Source: https://docs.python.org/3.10/distutils/examples.html Demonstrates how to use the `check` command in `setup.py` to verify if package metadata meets minimum requirements. It shows initial warnings for missing 'version' and 'url', and how to include author information. ```python from distutils.core import setup setup(name='foobar') ``` ```bash $ python setup.py check running check warning: check: missing required meta-data: version, url warning: check: missing meta-data: either (author and author_email) or (maintainer and maintainer_email) should be supplied ``` ```python from distutils.core import setup desc = """ My description ============== This is the description of the ``foobar`` package. """ setup(name='foobar', version='1', author='tarek', author_email='tarek@ziade.org', url='http://example.com', long_description=desc) ``` ```bash $ python setup.py check --restructuredtext running check warning: check: Title underline too short. (line 2) warning: check: Could not finish the parsing. ``` -------------------------------- ### Launch pydoc web server in Python Source: https://docs.python.org/3.10/whatsnew/3.2.html Shows how to start the pydoc documentation server and automatically open it in a browser using the -b command-line flag. ```bash pydoc3.2 -b ``` -------------------------------- ### Using mock.patch.object as context manager with 'as' Source: https://docs.python.org/3.10/library/unittest.mock-examples.html Shows how to use `patch.object` as a context manager and capture the created mock object using the `as` keyword. This allows direct interaction with the mock, such as setting its return value or asserting calls. ```python from unittest.mock import patch class ProductionClass: def method(self): pass with patch.object(ProductionClass, 'method') as mock_method: mock_method.return_value = None real = ProductionClass() real.method(1, 2, 3) mock_method.assert_called_once_with(1, 2, 3) ``` -------------------------------- ### Python Interactive Interpreter Example: List Methods Source: https://docs.python.org/3.10/faq/general.html Demonstrates using Python's interactive interpreter to explore list methods. It shows how to get a list of available methods using `dir()` and how to get help on a specific method like `append()`, followed by its usage. ```python >>> L = [] >>> dir(L) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> [d for d in dir(L) if '__' not in d] ['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> help(L.append) Help on built-in function append: append(...) L.append(object) -> None -- append object to end >>> L.append(1) >>> L [1] ``` -------------------------------- ### Define and build C extension modules Source: https://docs.python.org/3.10/distutils/setupscript.html Explains how to use the Extension class to describe C-based Python extensions. It includes the necessary import from distutils.core and a sample setup() function call. ```python from distutils.core import setup, Extension setup(name='foo', version='1.0', ext_modules=[Extension('foo', ['foo.c'])], ) ``` -------------------------------- ### POST /os/startfile Source: https://docs.python.org/3.10/library/os.html Opens a file with its associated application on Windows systems. ```APIDOC ## POST /os/startfile ### Description Starts a file with its associated application, similar to double-clicking in Windows Explorer. ### Method POST ### Endpoint os.startfile(path, operation, arguments, cwd, show_cmd) ### Parameters #### Request Body - **path** (string) - Required - Path to the file - **operation** (string) - Optional - Command verb ('open', 'print', 'edit') - **arguments** (string) - Optional - Arguments to pass to the application - **cwd** (string) - Optional - Working directory - **show_cmd** (int) - Optional - Window style integer ### Request Example { "path": "document.txt", "operation": "open" } ### Response #### Success Response (200) - **void** - Returns immediately upon launch. ``` -------------------------------- ### Mock asynchronous iterators Source: https://docs.python.org/3.10/library/unittest.mock-examples.html Shows how to mock asynchronous iteration by setting the return_value of the __aiter__ attribute on a MagicMock or AsyncMock. ```python import asyncio from unittest.mock import MagicMock mock = MagicMock() mock.__aiter__.return_value = [1, 2, 3] async def main(): return [i async for i in mock] asyncio.run(main()) ``` -------------------------------- ### Format String Syntax Examples Source: https://docs.python.org/3.10/library/string.html Demonstrates basic usage of the str.format() method, including positional arguments, keyword arguments, and attribute/index access. ```python "First, thou shalt count to {0}".format(3) "Bring me a {}".format("shrubbery") "From {} to {}".format(1, 10) "My quest is {name}".format(name="Holy Grail") "Weight in tons {0.weight}".format(obj) "Units destroyed: {players[0]}".format(players=["Player1", "Player2"]) ``` -------------------------------- ### GET /sysconfig/vars Source: https://docs.python.org/3.10/library/sysconfig.html Retrieves configuration variables relevant to the current Python platform, such as installation paths and build flags. ```APIDOC ## GET /sysconfig/vars ### Description Retrieves a dictionary of all configuration variables or specific variables from the Python distribution's Makefile and pyconfig.h. ### Method GET ### Endpoint /sysconfig/vars ### Parameters #### Query Parameters - **args** (list) - Optional - A list of specific variable names to retrieve (e.g., 'LIBDIR', 'AR'). If omitted, returns all variables. ### Request Example GET /sysconfig/vars?args=LIBDIR,AR ### Response #### Success Response (200) - **data** (object/list) - The requested configuration variables or a dictionary of all variables. #### Response Example { "LIBDIR": "/usr/local/lib", "AR": "ar" } ``` -------------------------------- ### Main Application Entry Point Source: https://docs.python.org/3.10/howto/logging-cookbook.html Sets up the PyQt application and initializes the main window. This function is the entry point for the application, configuring the logging level and showing the main window before starting the Qt event loop. ```python def main(): QtCore.QThread.currentThread().setObjectName('MainThread') logging.getLogger().setLevel(logging.DEBUG) app = QtWidgets.QApplication(sys.argv) example = Window(app) example.show() sys.exit(app.exec_()) if __name__=='__main__': main() ``` -------------------------------- ### Get Current First Weekday in Python Calendar Source: https://docs.python.org/3.10/library/calendar.html Retrieves the current setting for the first day of the week. This value is used by other calendar functions to determine the start of each week. ```python import calendar current_start_day = calendar.firstweekday() ``` -------------------------------- ### Client Usage Example Source: https://docs.python.org/3.10/library/xmlrpc.client.html Provides a basic example of using ServerProxy to make a call to a remote XML-RPC server. ```APIDOC ## Client Usage Example ### Description This example demonstrates a simple client interaction with an XML-RPC server using `ServerProxy` and handling potential errors. ### Method GET (for the example call) ### Endpoint `/` (The endpoint of the `ServerProxy`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xmlrpc.client import ServerProxy, Error # Using a context manager for ServerProxy with ServerProxy("http://betty.userland.com") as proxy: print(proxy) try: # Example call to a remote method result = proxy.examples.getStateName(41) print(result) except Error as e: print(f"An XML-RPC error occurred: {e}") ``` ### Response #### Success Response (200) - **result** (any) - The result returned by the remote method call. #### Response Example ``` Alaska ``` ``` -------------------------------- ### Create and Initialize Sets in Python Source: https://docs.python.org/3.10/library/stdtypes.html Demonstrates various ways to instantiate set objects, including literal syntax, set comprehensions, and the set constructor. ```python # Literal syntax s1 = {'jack', 'sjoerd'} # Set comprehension s2 = {c for c in 'abracadabra' if c not in 'abc'} # Constructor usage s3 = set() s4 = set('foobar') s5 = set(['a', 'b', 'foo']) # Frozenset creation fs = frozenset([1, 2, 3]) ``` -------------------------------- ### Chaining Classmethod and Property Decorators Source: https://docs.python.org/3.10/howto/descriptor.html Example of using the classmethod decorator in conjunction with other descriptors like property to define class-level attributes. ```python class G: @classmethod @property def __doc__(cls): return f'A doc for {cls.__name__!r}' ``` -------------------------------- ### Python: Perform GET request and read response data Source: https://docs.python.org/3.10/library/http.client.html Demonstrates how to establish an HTTPS connection, send a GET request, retrieve the response status and reason, and read the entire response body or in chunks. It also shows an example of an invalid request resulting in a 404 error. ```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. # The following example demonstrates 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() ``` -------------------------------- ### Importing modules and attributes in Python Source: https://docs.python.org/3.10/reference/simple_stmts.html Examples demonstrating various ways to import modules, submodules, and specific attributes using the 'import' and 'from' syntax. ```python import foo # foo imported and bound locally import foo.bar.baz # foo, foo.bar, and foo.bar.baz imported, foo bound locally import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb from foo.bar import baz # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz from foo import attr # foo imported and foo.attr bound as attr ``` -------------------------------- ### Specifying Provided Packages in setup() Source: https://docs.python.org/3.10/distutils/setupscript.html Illustrates how to declare packages or modules that a distribution provides using the '_provides' keyword argument in distutils.core.setup(). This allows other distributions to specify dependencies on these provided packages. ```python setup(..., provides=['mypkg', 'anotherpkg (1.1)'] ) ```