### Adding a Library to Setup File Source: https://docs.python.org/3.2/install/index.html Example of how to add a library, such as 'libm.a', to a setup file line to ensure it's linked. ```text foo foomodule.c -lm ``` -------------------------------- ### Define Custom Installation Scheme (Example 1) Source: https://docs.python.org/3.2/_sources/install/index.txt Specify multiple installation directory options to define a complete custom installation scheme. This example sets base, purelib, platlib, scripts, and data directories relative to the home directory. ```python python setup.py install --home=~ \ --install-purelib=python/lib \ --install-platlib=python/lib.$PLAT \ --install-scripts=python/scripts --install-data=python/data ``` -------------------------------- ### Postinstallation Script Example Source: https://docs.python.org/3.2/_sources/distutils/builtdist.txt This example shows how to specify a post-installation script using the `--install-script` option. The script must also be listed in the `scripts` argument of the `setup` function. ```python python setup.py --install-script=my_script install ``` -------------------------------- ### Basic Expat Parser Setup with Handlers Source: https://docs.python.org/3.2/_sources/library/pyexpat.txt An example demonstrating the basic setup of an Expat parser and defining handler functions for start element events. This serves as a starting point for custom XML processing. ```Python import xml.parsers.expat # 3 handler functions def start_element(name, attrs): ``` -------------------------------- ### Multiprocessing Logging Setup and Execution Source: https://docs.python.org/3.2/howto/logging-cookbook.html Sets up and runs a multiprocessing logging example. It configures initial logging, creates worker processes that send logs to a queue, and starts a listener process to handle these logs. Finally, it waits for workers and the listener to complete. ```python 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,))) 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)) 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() ``` -------------------------------- ### Python Setup Script with Classifiers Source: https://docs.python.org/3.2/distutils/setupscript.html Example of a setup script demonstrating the use of classifiers to categorize a Python package. Ensure the 'classifiers' argument is correctly formatted as a list of strings. ```python setup(..., classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Python Software Foundation License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Communications :: Email', 'Topic :: Office/Business', 'Topic :: Software Development :: Bug Tracking', ], ) ``` -------------------------------- ### Distutils Setup with Package Metadata Source: https://docs.python.org/3.2/_sources/whatsnew/2.5.txt Example of using new Distutils setup() parameters like requires, obsoletes, and download_url for package metadata. This information is recorded in PKG-INFO when building a source distribution. ```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), ) ``` -------------------------------- ### Basic Logging Example Source: https://docs.python.org/3.2/_sources/library/multiprocessing.txt Demonstrates basic logging setup using log_to_stderr and setting the logger level to INFO. ```python import multiprocessing, logging logger = multiprocessing.log_to_stderr() logger.setLevel(logging.INFO) logger.warning('doomed') m = multiprocessing.Manager() # ... manager output ... del m ``` -------------------------------- ### Get Installation Paths Source: https://docs.python.org/3.2/_sources/library/sysconfig.txt Returns a dictionary of all installation paths for a given scheme. Paths can be expanded using variables. ```python import sysconfig paths = sysconfig.get_paths() print('Installation Paths:') for name, path in paths.items(): print(f' {name} = "{path}"') # Example with a specific scheme and no expansion posix_paths = sysconfig.get_paths(scheme='posix_prefix', expand=False) print('\nPosix Prefix Paths (not expanded):') for name, path in posix_paths.items(): print(f' {name} = "{path}"') # Example with custom variables custom_vars = {'USER': 'testuser'} custom_paths = sysconfig.get_paths(vars=custom_vars) print('\nPaths with custom variables:') for name, path in custom_paths.items(): print(f' {name} = "{path}"') ``` -------------------------------- ### Define Custom Installation Scheme (Example 2) Source: https://docs.python.org/3.2/_sources/install/index.txt An alternative way to define a custom installation scheme, setting the base directory and then relative paths for modules, scripts, and data. ```python python setup.py install --home=~/python \ --install-purelib=lib \ --install-platlib='lib.$PLAT' \ --install-scripts=scripts --install-data=data ``` -------------------------------- ### Process Management with Logging Source: https://docs.python.org/3.2/_sources/howto/logging-cookbook.txt Example of starting and managing listener and worker processes with logging. ```python stop_event = Event() lp = Process(target=listener_process, name='listener', args=(q, stop_event, config_listener)) 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() ``` -------------------------------- ### Basic HTTP Authentication Setup Source: https://docs.python.org/3.2/_sources/library/urllib.request.txt Configures basic HTTP authentication by creating an OpenerDirector with a custom authentication handler and installing it globally. ```python import urllib.request # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib.request.HTTPBasicAuthHandler() auth_handler.add_password(realm='PDQ Application', uri='https://mahler:8092/site-updates.py', user='klem', passwd='kadidd!ehopper') opener = urllib.request.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib.request.install_opener(opener) urllib.request.urlopen('http://www.example.com/login.html') ``` -------------------------------- ### Creating a WSGI Server Source: https://docs.python.org/3.2/library/wsgiref.html Demonstrates how to create and run a WSGI server using wsgiref.simple_server.make_server. This function handles server setup and starts serving requests indefinitely. ```python from wsgiref.simple_server import make_server # Assume demo_app is defined as above with make_server('', 8000, demo_app) as httpd: print("Serving on port 8000...") httpd.serve_forever() ``` -------------------------------- ### setUpClass and tearDownClass Implementation Source: https://docs.python.org/3.2/library/unittest.html Example of implementing class-level setup and teardown methods as class methods in a unittest.TestCase. These are used for expensive resource management. ```python import unittest class Test(unittest.TestCase): @classmethod def setUpClass(cls): cls._connection = createExpensiveConnectionObject() @classmethod def tearDownClass(cls): cls._connection.destroy() ``` -------------------------------- ### SimpleXMLRPCServer Example Source: https://docs.python.org/3.2/_sources/library/xmlrpc.server.txt Sets up a basic XML-RPC server, registers functions and an instance, and starts serving requests. Requires importing SimpleXMLRPCServer and SimpleXMLRPCRequestHandler. ```python from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestHandler # Restrict to a particular path. class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2',) # Create server server = SimpleXMLRPCServer(("localhost", 8000), requestHandler=RequestHandler) 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() ``` -------------------------------- ### Example Options for 'build_ext' Command Source: https://docs.python.org/3.2/_sources/distutils/configfile.txt Shows a sample output from 'python setup.py --help build_ext', detailing available options for building extensions. ```text Options for 'build_ext' command: --build-lib (-b) directory for compiled extension modules --build-temp (-t) directory for temporary files (build by-products) --inplace (-i) ignore build-lib and put compiled extensions into the source directory alongside your pure Python modules --include-dirs (-I) list of directories to search for header files --define (-D) C preprocessor macros to define --undef (-U) C preprocessor macros to undefine --swig-opts list of SWIG command line options [...] ``` -------------------------------- ### Remote Manager Server Setup Source: https://docs.python.org/3.2/_sources/library/multiprocessing.txt Example of setting up a manager server that exposes a shared queue to remote clients. It defines a custom manager, registers a callable to provide the queue, and starts the server. ```python from multiprocessing.managers import BaseManager import queue queue = queue.Queue() class QueueManager(BaseManager): pass QueueManager.register('get_queue', callable=lambda:queue) m = QueueManager(address=('', 50000), authkey=b'abracadabra') s = m.get_server() s.serve_forever() ``` -------------------------------- ### Getting Start and End Indices of a Match Source: https://docs.python.org/3.2/library/re.html Explains how to use start() and end() methods to get the start and end positions of a matched substring within the original string. Defaults to the entire match (group 0). ```python email = "tony@tiremove_thisger.net" m = re.search("remove_this", email) email[:m.start()] + email[m.end():] 'tony@tiger.net' ``` -------------------------------- ### setup.py for C extension modules Source: https://docs.python.org/3.2/_sources/whatsnew/2.0.txt This example demonstrates a setup.py script for a C extension module, including compiler definitions, include directories, and source files. It's suitable for complex extensions like those found in the PyXML package. ```python from distutils.core import setup, Extension expat_extension = Extension('xml.parsers.pyexpat', define_macros = [('XML_NS', None)], include_dirs = [ 'extensions/expat/xmltok', 'extensions/expat/xmlparse' ], sources = [ 'extensions/pyexpat.c', 'extensions/expat/xmltok/xmltok.c', 'extensions/expat/xmltok/xmlrole.c' ] ) setup (name = "PyXML", version = "0.5.4", ext_modules =[ expat_extension ] ) ``` -------------------------------- ### Get Help for Global Options Source: https://docs.python.org/3.2/_sources/install/index.txt Use the --help option without a command to view all global options available for setup.py. This provides an overview of general configurations. ```bash python setup.py --help ``` -------------------------------- ### Client Connection Setup Source: https://docs.python.org/3.2/_sources/library/multiprocessing.txt Demonstrates how to establish a connection to a listener using the Client function, with optional authentication. ```python Client(address[, family[, authenticate[, authkey]]]) ``` -------------------------------- ### Example .pth file content Source: https://docs.python.org/3.2/library/site.html This example shows the content of a .pth file, which specifies additional items to be added to sys.path. Blank lines and lines starting with '#' are ignored, while lines starting with 'import' are executed. ```python # foo package configuration foo bar bletch ``` -------------------------------- ### Example: Displaying Help for a Command Source: https://docs.python.org/3.2/distutils/configfile.html Shows how to use the --help option with a specific command (e.g., build_ext) to list its supported options. ```bash > python setup.py --help build_ext [...] Options for 'build_ext' command: --build-lib (-b) directory for compiled extension modules --build-temp (-t) directory for temporary files (build by-products) --inplace (-i) ignore build-lib and put compiled extensions into the source directory alongside your pure Python modules --include-dirs (-I) list of directories to search for header files --define (-D) C preprocessor macros to define --undef (-U) C preprocessor macros to undefine --swig-opts list of SWIG command line options [...] ``` -------------------------------- ### GET Request Example Source: https://docs.python.org/3.2/library/http.client.html Demonstrates how to make a GET request and read the response body, including reading in chunks. ```APIDOC ## GET /index.html ### Description Retrieves the content of the specified resource. ### Method GET ### Endpoint /index.html ### Request Example ```python import http.client conn = http.client.HTTPConnection("www.python.org") conn.request("GET", "/index.html") r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() # This will return entire content. # Example of reading in chunks conn.request("GET", "/index.html") r1 = conn.getresponse() while not r1.closed: print(r1.read(200)) # 200 bytes conn.close() ``` ### Response #### Success Response (200) - **status** (int) - The HTTP status code. - **reason** (string) - The HTTP reason phrase. - **body** (bytes) - The response body content. #### Response Example ``` 200 OK ``` ``` -------------------------------- ### Building and Installing in Separate Steps Source: https://docs.python.org/3.2/_sources/install/index.txt Break down the installation process into build and install steps for incremental work or customization. ```bash python setup.py build python setup.py install ``` -------------------------------- ### Install Python 2.5.1 on OpenBSD i386 Source: https://docs.python.org/3.2/_sources/using/unix.txt Example of installing a specific version of Python on an OpenBSD i386 system. ```sh pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz ``` -------------------------------- ### Install Scripts to Custom Directory (Relative Path) Source: https://docs.python.org/3.2/_sources/install/index.txt Use `--install-scripts` with a relative path to install scripts to a directory relative to the installation base. This example installs scripts into a 'scripts' subdirectory of the home directory. ```python python setup.py install --home=~ --install-scripts=scripts ``` -------------------------------- ### Basic setup.py for package metadata check Source: https://docs.python.org/3.2/distutils/examples.html A minimal setup.py script to demonstrate the 'check' command's functionality for verifying package metadata. This example is useful for identifying missing required fields like version and URL. ```python from distutils.core import setup setup(name='foobar') ``` -------------------------------- ### Basic distutils setup.py for an Extension Module Source: https://docs.python.org/3.2/_sources/extending/building.txt This is a minimal setup.py file to build a single C extension module named 'demo' from 'demo.c'. Ensure distutils is installed on the build machine. ```python from distutils.core import setup, Extension module1 = Extension('demo', sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [module1]) ``` -------------------------------- ### Get Specific Installation Path Source: https://docs.python.org/3.2/_sources/library/sysconfig.txt Retrieve an installation path corresponding to a given path name and scheme. Allows for dynamic determination of installation directories based on platform and configuration. ```python import sysconfig # Get the standard library path for the default scheme stdlib_path = sysconfig.get_path('stdlib') print(f'Standard library path: {stdlib_path}') # Get the script path for the 'nt' (Windows) scheme script_path_nt = sysconfig.get_path('scripts', scheme='nt') print(f'NT script path: {script_path_nt}') ``` -------------------------------- ### Listener Setup Source: https://docs.python.org/3.2/_sources/library/multiprocessing.txt Shows the basic setup for creating a listener that waits for incoming connections. ```python Listener([address[, family[, backlog[, authenticate[, authkey]]]]]) ``` -------------------------------- ### Starting the Python Interpreter on Windows Source: https://docs.python.org/3.2/_sources/faq/windows.txt Verify that the Python interpreter can be started from its installation directory. You will need to enter Ctrl+Z and Enter to exit. ```shell c:\Python33\python ``` -------------------------------- ### distutils.core.setup Source: https://docs.python.org/3.2/_sources/distutils/apiref.txt The setup function is the primary entry point for Distutils, handling the packaging and distribution process. It accepts a wide range of arguments to configure the package. ```APIDOC ## function setup(arguments) ### Description The basic do-everything function that does most everything you could ever ask for from a Distutils method. ### Parameters #### Arguments - **name** (string) - The name of the package. - **version** (string) - The version number of the package; see :mod:`distutils.version`. - **description** (string) - A single line describing the package. - **long_description** (string) - Longer description of the package. - **author** (string) - The name of the package author. - **author_email** (string) - The email address of the package author. - **maintainer** (string) - The name of the current maintainer, if different from the author. Note that if the maintainer is provided, distutils will use it as the author in :file:`PKG-INFO`. - **maintainer_email** (string) - The email address of the current maintainer, if different from the author. - **url** (string) - A URL for the package (homepage). ``` -------------------------------- ### Python http.client GET Request Example Source: https://docs.python.org/3.2/library/http.client.html Demonstrates a basic GET request to retrieve the content of a web page. Shows how to get the response status and reason, and read the entire response body. ```python import http.client conn = http.client.HTTPConnection("www.python.org") conn.request("GET", "/index.html") r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() # This will return entire content. ``` -------------------------------- ### Build Python Extension Module with Advanced Options Source: https://docs.python.org/3.2/extending/building.html This `setup.py` example demonstrates how to configure an extension module with preprocessor defines, include directories, libraries, and library directories. This is useful for extensions with complex dependencies. ```python from distutils.core import setup, Extension module1 = Extension('demo', define_macros = [('MAJOR_VERSION', '1'), ('MINOR_VERSION', '0')], include_dirs = ['/usr/local/include'], libraries = ['tcl83'], library_dirs = ['/usr/local/lib'], sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', author = 'Martin v. Loewis', author_email = 'martin@v.loewis.de', url = 'http://docs.python.org/extending/building', long_description = ''' This is really just a demo package. ''', ext_modules = [module1]) ``` -------------------------------- ### Get All Installation Paths for a Scheme Source: https://docs.python.org/3.2/library/sysconfig.html Retrieves a dictionary of all installation paths for a given scheme. Paths are expanded using configuration variables by default. ```python import sysconfig # Get all paths for the default scheme all_paths_default = sysconfig.get_paths() print("All paths (default scheme):") for name, path in all_paths_default.items(): print(f" {name}: {path}") # Get all paths for the 'posix_prefix' scheme all_paths_posix = sysconfig.get_paths(scheme='posix_prefix') print("\nAll paths (posix_prefix scheme):") for name, path in all_paths_posix.items(): print(f" {name}: {path}") # Get all paths for the 'nt' scheme without expanding variables all_paths_nt_no_expand = sysconfig.get_paths(scheme='nt', expand=False) print("\nAll paths (nt scheme, no expansion):") for name, path in all_paths_nt_no_expand.items(): print(f" {name}: {path}") ``` -------------------------------- ### distutils.core.run_setup Source: https://docs.python.org/3.2/distutils/apiref.html Executes a setup script in a controlled environment, returning the Distribution instance that manages the build process. ```APIDOC ## run_setup(script_name, script_args=None, stop_after='run') ### Description Run a setup script in a somewhat controlled environment, and return the distutils.dist.Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from script to setup()), or the contents of the config files or command-line. ### Method run_setup ### Parameters #### Arguments - **script_name** (string) - A file that will be read and run with exec(). sys.argv[0] will be replaced with script for the duration of the call. - **script_args** (list of strings, optional) - If supplied, sys.argv[1:] will be replaced by script_args for the duration of the call. - **stop_after** (string, optional) - Tells setup() when to stop processing. Possible values: 'init', 'config', 'commandline', 'run'. Defaults to 'run'. - 'init': Stop after the Distribution instance has been created and populated with the keyword arguments to setup() - 'config': Stop after config files have been parsed - 'commandline': Stop after the command-line have been parsed - 'run': Stop after all commands have been run (default) ``` -------------------------------- ### Basic Translation Example Source: https://docs.python.org/3.2/_sources/library/gettext.txt This example demonstrates how to mark a string for translation using the _() function, which is typically installed in Python's builtins namespace. ```python print(_('This string will be translated.')) ``` -------------------------------- ### Getting Match Indices Source: https://docs.python.org/3.2/_sources/library/re.txt Use start() and end() methods to retrieve the start and end indices of a matched group. Defaults to the entire match. ```python m = re.match(r"(\w+) (\w+)", "Isaac Newton") m.start(0) 0 m.end(0) 12 m.start(1) 0 m.end(1) 5 ``` -------------------------------- ### Basic unittest Example Source: https://docs.python.org/3.2/_sources/library/unittest.txt A fundamental example demonstrating how to create a test case by subclassing unittest.TestCase, defining test methods (prefixed with 'test_'), and using assertion methods like assertEqual, assertTrue, and assertRaises. Includes setUp for pre-test setup and demonstrates running tests with unittest.main(). ```python import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = list(range(10)) def test_shuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, list(range(10))) # should raise an exception for an immutable sequence self.assertRaises(TypeError, random.shuffle, (1,2,3)) def test_choice(self): element = random.choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): with self.assertRaises(ValueError): random.sample(self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) if __name__ == '__main__': unittest.main() ``` -------------------------------- ### Get a Specific Installation Path Source: https://docs.python.org/3.2/library/sysconfig.html Retrieves a specific installation path by name and optionally by scheme. Paths are expanded using configuration variables by default. ```python import sysconfig # Get the default stdlib path for the current platform stdlib_path = sysconfig.get_path('stdlib') print(f"Default stdlib path: {stdlib_path}") # Get the stdlib path for the 'nt' (Windows) scheme nt_stdlib_path = sysconfig.get_path('stdlib', scheme='nt') print(f"NT scheme stdlib path: {nt_stdlib_path}") # Get the stdlib path without expanding variables stdlib_path_no_expand = sysconfig.get_path('stdlib', expand=False) print(f"Stdlib path (no expansion): {stdlib_path_no_expand}") ``` -------------------------------- ### Advanced distutils setup.py with Compilation Flags Source: https://docs.python.org/3.2/_sources/extending/building.txt This setup.py file demonstrates how to specify preprocessor defines, include directories, libraries, and library directories for a more complex C extension module. This is useful for extensions that depend on external libraries or require specific build configurations. ```python from distutils.core import setup, Extension module1 = Extension('demo', define_macros = [('MAJOR_VERSION', '1'), ('MINOR_VERSION', '0')], include_dirs = ['/usr/local/include'], libraries = ['tcl83'], library_dirs = ['/usr/local/lib'], sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', author = 'Martin v. Loewis', author_email = 'martin@v.loewis.de', url = 'http://docs.python.org/extending/building', long_description = ''' This is really just a demo package. ''', ext_modules = [module1]) ``` -------------------------------- ### Get All Supported Scheme Names Source: https://docs.python.org/3.2/_sources/library/sysconfig.txt Retrieve a tuple containing all installation schemes currently supported by sysconfig. Useful for understanding platform-specific installation layouts. ```python import sysconfig schemes = sysconfig.get_scheme_names() print(schemes) ``` -------------------------------- ### Example Classifiers in setup.py Source: https://docs.python.org/3.2/_sources/distutils/setupscript.txt Demonstrates how to specify classifiers in a Python list within the setup.py file. These help categorize the package on PyPI. ```python setup( ..., classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Python Software Foundation License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Communications :: Email', 'Topic :: Office/Business', 'Topic :: Software Development :: Bug Tracking', ], ) ``` -------------------------------- ### Basic Authentication Setup Source: https://docs.python.org/3.2/_sources/howto/urllib2.txt Illustrates setting up basic HTTP authentication using HTTPBasicAuthHandler and HTTPPasswordMgrWithDefaultRealm to manage credentials for URL access. ```python # create a password manager password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() # Add the username and password. # If we knew the realm, we could use it instead of None. top_level_url = "http://example.com/foo/" ``` -------------------------------- ### readline.get_begidx Source: https://docs.python.org/3.2/library/readline.html Gets the starting index of the current readline tab-completion scope. ```APIDOC ## readline.get_begidx ### Description Get the beginning index of the readline tab-completion scope. ### Method `readline.get_begidx()` ``` -------------------------------- ### Install and Test cgi.py Module Source: https://docs.python.org/3.2/library/cgi.html Verify CGI script installation by running cgi.py directly. This displays environment and form data, confirming correct setup. ```shell http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home ``` -------------------------------- ### turtle.setup() Source: https://docs.python.org/3.2/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 This is a method call. ### Endpoint N/A (Method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **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 float 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 float 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) screen.setup(width=.75, height=0.5, startx=None, starty=None) ``` ### Response #### Success Response (200) None (window is configured) #### Response Example None ``` -------------------------------- ### Server Example with Listener and Authentication Source: https://docs.python.org/3.2/library/multiprocessing.html This server code demonstrates creating a listener with an authentication key, accepting a connection, sending various data types, and closing the connections. ```python from multiprocessing.connection import Listener from array import array address = ('localhost', 6000) # family is deduced to be 'AF_INET' listener = Listener(address, authkey=b'secret password') conn = listener.accept() print('connection accepted from', listener.last_accepted) conn.send([2.25, None, 'junk', float]) conn.send_bytes(b'hello') conn.send_bytes(array('i', [42, 1729])) conn.close() listener.close() ``` -------------------------------- ### Passing Data in GET Request Source: https://docs.python.org/3.2/howto/urllib2.html This example shows how to pass data in an HTTP GET request by encoding it directly into the URL. The full URL is constructed by appending the encoded data after a '?'. ```Python import urllib.request import urllib.parse data = {} data['name'] = 'Somebody Here' data['location'] = 'Northampton' data['language'] = 'Python' url_values = urllib.parse.urlencode(data) print(url_values) # The order may differ from below. url = 'http://www.example.com/example.cgi' full_url = url + '?' + url_values data = urllib.request.urlopen(full_url) ``` -------------------------------- ### Setup Script for a Single Extension Module Source: https://docs.python.org/3.2/_sources/distutils/setupscript.txt A complete setup script for a distribution containing only a single extension module named 'foo'. It imports necessary components and calls the setup function. ```python from distutils.core import setup, Extension setup(name='foo', version='1.0', ext_modules=[Extension('foo', ['foo.c'])], ) ``` -------------------------------- ### Unpacking and Installing on Windows Source: https://docs.python.org/3.2/_sources/install/index.txt Steps to unpack a module distribution archive and install it on Windows. ```bash cd c:\Temp\foo-1.0 python setup.py install ``` -------------------------------- ### Configuring 'build_ext' to Build In-Place Source: https://docs.python.org/3.2/_sources/distutils/configfile.txt Shows how to use setup.cfg to set the 'inplace' option for the 'build_ext' command, ensuring extensions are built in the source directory. ```ini [build_ext] inplace=1 ``` -------------------------------- ### Basic ArgumentParser Setup and Usage Source: https://docs.python.org/3.2/_sources/library/argparse.txt This example demonstrates how to create an ArgumentParser, add positional and optional arguments, and parse them. It shows how to handle integers and an optional --sum flag to either sum or find the maximum. ```python import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() print(args.accumulate(args.integers)) ``` -------------------------------- ### Basic ArgumentParser Setup Source: https://docs.python.org/3.2/_sources/howto/argparse.txt This snippet demonstrates the minimal setup for an ArgumentParser. It automatically provides a --help option and shows how unrecognized arguments result in an error. ```python import argparse parser = argparse.ArgumentParser() parser.parse_args() ``` ```sh $ python3 prog.py $ python3 prog.py --help usage: prog.py [-h] optional arguments: -h, --help show this help message and exit $ python3 prog.py --verbose usage: prog.py [-h] prog.py: error: unrecognized arguments: --verbose $ python3 prog.py foo usage: prog.py [-h] prog.py: error: unrecognized arguments: foo ``` -------------------------------- ### Get Start Attribute from Unicode Error Source: https://docs.python.org/3.2/_sources/c-api/exceptions.txt Retrieves the start attribute from a given Unicode error object (Decode, Encode, or Translate) and places it into the provided Py_ssize_t pointer. Returns 0 on success, -1 on failure. The start pointer must not be NULL. ```c int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) ``` -------------------------------- ### Create and Write Configuration File Source: https://docs.python.org/3.2/_sources/library/configparser.txt Demonstrates how to programmatically create a configuration parser object, populate it with sections and key-value pairs, and write it to a file. ```python import configparser config = configparser.ConfigParser() config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile: config.write(configfile) ``` -------------------------------- ### Minimal Setup Script for Single Module Source: https://docs.python.org/3.2/distutils/examples.html A basic setup script to describe a distribution with a single Python module. ```python from distutils.core import setup setup(name='foo', version='1.0', py_modules=['foo'], ) ``` -------------------------------- ### Integrate 2to3 with Distribute Source: https://docs.python.org/3.2/_sources/howto/pyporting.txt Enable 2to3 conversion during project installation using the 'use_2to3' flag in setup. ```python setup(use_2to3=True, # ... ) ``` -------------------------------- ### Handling Scripts with Distutils Source: https://docs.python.org/3.2/_sources/distutils/setupscript.txt Use the 'scripts' option in setup() to specify files that should be handled as scripts during installation. ```python setup(..., scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val'] ) ``` -------------------------------- ### Configuring bdist_rpm Command Options Source: https://docs.python.org/3.2/distutils/configfile.html Provides an example of setting multiple options for the 'bdist_rpm' command in setup.cfg, including 'release', 'packager', and 'doc_files'. The 'doc_files' option shows how to specify multiple files or directories. ```ini [bdist_rpm] release = 1 packager = Greg Ward doc_files = CHANGES.txt README.txt USAGE.txt doc/ examples/ ``` -------------------------------- ### Example Usage of bgcolor Function Source: https://docs.python.org/3.2/library/turtle.html Illustrates setting and getting the background color using the standalone bgcolor function. ```python bgcolor("orange") bgcolor() bgcolor(0.5,0,0.5) bgcolor() ``` -------------------------------- ### Creating and Starting a Process Source: https://docs.python.org/3.2/_sources/library/multiprocessing.txt Demonstrates how to create a Process object targeting a function with arguments and then start its execution. It also shows how to check if the process is alive. ```python >>> import multiprocessing, time, signal >>> p = multiprocessing.Process(target=time.sleep, args=(1000,)) >>> print(p, p.is_alive()) False >>> p.start() >>> print(p, p.is_alive()) True ``` -------------------------------- ### Test Case with setUp and tearDown Source: https://docs.python.org/3.2/_sources/library/unittest.txt Illustrates using setUp for test fixture initialization and tearDown for cleanup. These methods are automatically called by the framework. ```python import unittest class SimpleWidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() self.widget = None ``` -------------------------------- ### Turtle Shell Help Specific Command Example Source: https://docs.python.org/3.2/_sources/library/cmd.txt Shows how to get help for a specific command, like 'forward'. ```text (turtle) help forward Move the turtle forward by the specified distance: FORWARD 10 ``` -------------------------------- ### XML-RPC Server Setup Source: https://docs.python.org/3.2/library/xmlrpc.client.html Sets up a simple XML-RPC server with arithmetic functions and starts listening on port 8000. ```python from xmlrpc.server import SimpleXMLRPCServer def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y server = SimpleXMLRPCServer(("localhost", 8000)) print("Listening on port 8000...") server.register_multicall_functions() server.register_function(add, 'add') server.register_function(subtract, 'subtract') server.register_function(multiply, 'multiply') server.register_function(divide, 'divide') server.serve_forever() ``` -------------------------------- ### Basic Argparse Setup Source: https://docs.python.org/3.2/_sources/howto/argparse.txt Demonstrates a basic argparse setup with a positional argument and an optional flag. ```python import argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity") args = parser.parse_args() answer = args.square**2 # bugfix: replace == with >= if args.verbosity >= 2: print("the square of {} equals {}".format(args.square, answer)) elif args.verbosity >= 1: print("{}^2 == {}".format(args.square, answer)) else: print(answer) ``` -------------------------------- ### Python itertools.chain.from_iterable Example Source: https://docs.python.org/3.2/library/itertools.html An alternate constructor for chain that gets chained inputs from a single iterable argument, evaluated lazily. ```python @classmethod def from_iterable(iterables): # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F for it in iterables: for element in it: yield element ``` -------------------------------- ### PyUnicodeDecodeError_GetStart / PyUnicodeEncodeError_GetStart / PyUnicodeTranslateError_GetStart Source: https://docs.python.org/3.2/c-api/exceptions.html Gets the start attribute of a Unicode exception object. Returns 0 on success, -1 on failure. ```APIDOC ## PyUnicodeDecodeError_GetStart / PyUnicodeEncodeError_GetStart / PyUnicodeTranslateError_GetStart ### Description Get the _start_ attribute of the given exception object and place it into _*start_. _start_ must not be _NULL_. Return `0` on success, `-1` on failure. ### Signatures ```c int PyUnicodeDecodeError_GetStart(PyObject *_exc_, Py_ssize_t *_start_) int PyUnicodeEncodeError_GetStart(PyObject *_exc_, Py_ssize_t *_start_) int PyUnicodeTranslateError_GetStart(PyObject *_exc_, Py_ssize_t *_start_) ``` ``` -------------------------------- ### Distutils setup.py with Classifiers Source: https://docs.python.org/3.2/whatsnew/2.3.html An example setup.py file demonstrating the use of the 'classifiers' keyword argument for package metadata, compatible with older Distutils versions. ```python from distutils import core kw = {"name": "Quixote", "version": "0.5.1", "description": "A highly Pythonic Web application framework", # ... } if (hasattr(core, 'setup_keywords') and 'classifiers' in core.setup_keywords): kw['classifiers'] = \ ['Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: Developers'], core.setup(**kw) ``` -------------------------------- ### Certificate Chain Example Source: https://docs.python.org/3.2/library/ssl.html A sequence of certificates concatenated together, starting with the specific certificate for a principal 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----- ``` -------------------------------- ### Command-line Interface Example Source: https://docs.python.org/3.2/_sources/library/webbrowser.txt Demonstrates using the webbrowser module from the command line to open a URL in a new tab. ```bash python -m webbrowser -t "http://www.python.org" ``` -------------------------------- ### Listener Process Configuration Source: https://docs.python.org/3.2/howto/logging-cookbook.html Configures the root logger for the listener process to use a RotatingFileHandler. This setup is applied when the listener process starts. ```python # You'll need these imports in your own code import logging import logging.handlers import multiprocessing # Next two import lines for this demo only from random import choice, random import time # # Because you'll want to define the logging configurations for listener and workers, the # listener and worker process functions take a configurer parameter which is a callable # for configuring logging for that process. These functions are also passed the queue, # which they use for communication. # # In practice, you can configure the listener however you want, but note that in this # simple example, the listener does not apply level or filter logic to received records. # In practice, you would probably want to do this logic in the worker processes, to avoid # sending events which would be filtered out between processes. # # The size of the rotated files is made small so you can see the results easily. ``` ```python def listener_configurer(): root = logging.getLogger() h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10) f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s') h.setFormatter(f) root.addHandler(h) ``` -------------------------------- ### distutils.core.Distribution Source: https://docs.python.org/3.2/distutils/apiref.html The Distribution class represents how to build, install, and package a Python software package. The `setup()` function creates an instance of this class. ```APIDOC ## class distutils.core.Distribution ### Description A `Distribution` describes how to build, install and package up a Python software package. See the `setup()` function for a list of keyword arguments accepted by the Distribution constructor. `setup()` creates a Distribution instance. ``` -------------------------------- ### Basic Process Creation and Execution Source: https://docs.python.org/3.2/_sources/library/multiprocessing.txt Demonstrates the fundamental way to create a new process, assign a target function, start it, and wait for its completion. ```python from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() ``` -------------------------------- ### Unpacking and Installing on Unix/Linux Source: https://docs.python.org/3.2/_sources/install/index.txt Steps to unpack a module distribution archive and install it on a Unix-like system. ```bash gunzip -c foo-1.0.tar.gz | tar xf - cd foo-1.0 python setup.py install ```