### Python tzinfo Example Class Setup Source: https://docs.python.org/es/3/library/datetime This snippet shows the initial setup for a `tzinfo` subclass example, defining common `timedelta` objects and importing necessary classes from the `datetime` module. ```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 ``` -------------------------------- ### Automated Installer Command Line Example Source: https://docs.python.org/es/3/using/mac This shell snippet demonstrates how to use the macOS `installer` command-line utility to automate the installation of a specific Python release package, including selecting the free-threaded interpreter option. ```shell RELEASE="python-3.130b2-macos11.pkg" ``` -------------------------------- ### Get Matching Blocks - Detailed Example Source: https://docs.python.org/es/3/library/difflib Illustrates retrieving matching blocks with detailed output, showing the starting indices in both sequences and the length of the match. ```python >>> s = SequenceMatcher(lambda x: x == " ", ... "private Thread currentThread;", ... "private volatile Thread currentThread;") >>> for block in s.get_matching_blocks(): ... print("a[%d] and b[%d] match for %d elements" % block) a[0] and b[0] match for 8 elements a[8] and b[17] match for 21 elements a[29] and b[38] match for 0 elements ``` -------------------------------- ### Get Opcodes - Detailed Example Source: https://docs.python.org/es/3/library/difflib Shows how to use get_opcodes() to visualize the differences and similarities between two sequences, detailing operations like 'equal', 'insert', and 'replace'. ```python >>> s = SequenceMatcher(lambda x: x == " ", ... "private Thread currentThread;", ... "private volatile Thread currentThread;") >>> for opcode in s.get_opcodes(): ... print("%6s a[%d:%d] b[%d:%d]" % opcode) equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:29] b[17:38] ``` -------------------------------- ### Get Examples - Python Doctest DocTestParser Source: https://docs.python.org/es/3/genindex-G Retrieves examples from a DocTestParser object in the doctest module. ```Python doctest.DocTestParser.get_examples() ``` -------------------------------- ### Basic Python Logging Setup Source: https://docs.python.org/es/3/library/logging This example demonstrates idiomatic usage of the Python logging module. It shows how to set up basic logging configuration, create a module-level logger, and log messages. The `logging.basicConfig` function configures the root logger, and `getLogger(__name__)` creates a logger specific to the current module. ```Python import logging import mylib logger = logging.getLogger(__name__) def main(): logging.basicConfig(filename='myapp.log', level=logging.INFO) logger.info('Started') mylib.do_something() logger.info('Finished') if __name__ == '__main__': main() ``` ```Python import logging logger = logging.getLogger(__name__) def do_something(): logger.info('Doing something') ``` -------------------------------- ### Bash CLI Logging Examples Source: https://docs.python.org/es/3/howto/logging-cookbook These bash commands demonstrate the output of a Python CLI application configured with different logging levels. They show how the application responds to start, stop, and restart commands with varying numbers of services. ```Bash $ python app.py start foo INFO start Started the 'foo' service. $ python app.py stop foo bar INFO stop Stopped the 'foo' and 'bar' services. $ python app.py restart foo bar baz INFO restart Restarted the 'foo', 'bar' and 'baz' services. ``` ```Bash $ python app.py --log-level DEBUG start foo DEBUG start About to start foo INFO start Started the 'foo' service. $ python app.py --log-level DEBUG stop foo bar DEBUG stop About to stop 'foo' and 'bar' INFO stop Stopped the 'foo' and 'bar' services. $ python app.py --log-level DEBUG restart foo bar baz DEBUG restart About to restart 'foo', 'bar' and 'baz' INFO restart Restarted the 'foo', 'bar' and 'baz' services. ``` ```Bash $ python app.py --log-level WARNING start foo $ python app.py --log-level WARNING stop foo bar $ python app.py --log-level WARNING restart foo bar baz ``` -------------------------------- ### Get iOS Runtime Information in Python Source: https://docs.python.org/es/3/using/ios This example demonstrates how to retrieve detailed runtime information about the iOS environment using the `platform` module. It specifically shows how to get the iOS version, device model, and whether the app is running on a simulator. ```python import platform print(platform.ios_ver()) print(platform.system()) ``` -------------------------------- ### site.py: foo.pth Example Source: https://docs.python.org/es/3/library/site This example demonstrates the content of a `foo.pth` file, which is used by the `site` module to add directories to the Python module search path. Lines starting with '#' are comments, and regular lines specify paths or modules to be added. ```Python # foo package configuration foo bar bletch ``` -------------------------------- ### Install Debug Packages (Ubuntu) Source: https://docs.python.org/es/3/howto/gdb_helpers This example shows how to install GDB and the Python debug package on Ubuntu using the `apt` package manager. This is necessary for debugging Python with GDB on Ubuntu systems. ```bash sudo apt install gdb python3-dbg ``` -------------------------------- ### Python ssl.SSLSocket methods Source: https://docs.python.org/es/3/genindex-V Shows examples of methods available on `ssl.SSLSocket` objects, including `verify_client_post_handshake` for post-handshake client certificate verification and `version` to get the negotiated TLS version. ```Python import ssl # Assuming 'sock' is an SSLSocket object # sock.verify_client_post_handshake() # print(sock.version()) pass ``` -------------------------------- ### Extend EnvBuilder to Install Setuptools and Pip Source: https://docs.python.org/es/3/library/venv This Python code defines a class `ExtendedEnvBuilder` that inherits from `venv.EnvBuilder`. It overrides the `post_setup` method to install setuptools and pip after the virtual environment is created. The class includes methods for handling download progress and executing installation scripts. ```Python import os import os.path from subprocess import Popen, PIPE import sys from threading import Thread from urllib.parse import urlparse from urllib.request import urlretrieve import venv class ExtendedEnvBuilder(venv.EnvBuilder): """ This builder installs setuptools and pip so that you can pip or easy_install other packages into the created virtual environment. :param nodist: If true, setuptools and pip are not installed into the created virtual environment. :param nopip: If true, pip is not installed into the created virtual environment. :param progress: If setuptools or pip are installed, the progress of the installation can be monitored by passing a progress callable. If specified, it is called with two arguments: a string indicating some progress, and a context indicating where the string is coming from. The context argument can have one of three values: 'main', indicating that it is called from virtualize() itself, and 'stdout' and 'stderr', which are obtained by reading lines from the output streams of a subprocess which is used to install the app. If a callable is not specified, default progress information is output to sys.stderr. """ def __init__(self, *args, **kwargs): self.nodist = kwargs.pop('nodist', False) self.nopip = kwargs.pop('nopip', False) self.progress = kwargs.pop('progress', None) self.verbose = kwargs.pop('verbose', False) super().__init__(*args, **kwargs) def post_setup(self, context): """ Set up any packages which need to be pre-installed into the virtual environment being created. :param context: The information for the virtual environment creation request being processed. """ os.environ['VIRTUAL_ENV'] = context.env_dir if not self.nodist: self.install_setuptools(context) # Can't install pip without setuptools if not self.nopip and not self.nodist: self.install_pip(context) def reader(self, stream, context): """ Read lines from a subprocess' output stream and either pass to a progress callable (if specified) or write progress information to sys.stderr. """ progress = self.progress while True: s = stream.readline() if not s: break if progress is not None: progress(s, context) else: if not self.verbose: sys.stderr.write('.') else: sys.stderr.write(s.decode('utf-8')) sys.stderr.flush() stream.close() def install_script(self, context, name, url): _, _, path, _, _, _ = urlparse(url) fn = os.path.split(path)[-1] binpath = context.bin_path distpath = os.path.join(binpath, fn) # Download script into the virtual environment's binaries folder urlretrieve(url, distpath) progress = self.progress if self.verbose: term = '\n' else: term = '' if progress is not None: progress('Installing %s ...%s' % (name, term), 'main') else: sys.stderr.write('Installing %s ...%s' % (name, term)) sys.stderr.flush() # Install in the virtual environment args = [context.env_exe, fn] p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath) t1 = Thread(target=self.reader, args=(p.stdout, 'stdout')) t1.start() t2 = Thread(target=self.reader, args=(p.stderr, 'stderr')) t2.start() p.wait() t1.join() t2.join() if progress is not None: progress('done.', 'main') else: sys.stderr.write('done.\n') # Clean up - no longer needed os.unlink(distpath) def install_setuptools(self, context): """ Install setuptools in the virtual environment. :param context: The information for the virtual environment creation request being processed. """ url = "https://bootstrap.pypa.io/ez_setup.py" self.install_script(context, 'setuptools', url) # clear up the setuptools archive which gets downloaded pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz') files = filter(pred, os.listdir(context.bin_path)) for f in files: pass # Placeholder for actual file cleanup logic ``` -------------------------------- ### Python OS and Path Operations Source: https://docs.python.org/es/3/genindex-S This snippet covers functions and methods for interacting with the operating system and file paths in Python. It includes starting files, getting file status information, and path manipulation. ```Python import os import pathlib # Example usage (conceptual): # os.startfile('path/to/file.txt') # Opens a file with its associated application # Get file status stat_info = os.stat('some_file.txt') print(f"File size: {stat_info.st_size}") # Path object operations path_obj = pathlib.Path('another_file.txt') path_stat = path_obj.stat() print(f"Path modification time: {path_stat.st_mtime}") # os.stat_result is a tuple-like object containing file status information ``` -------------------------------- ### Python Multiprocessing Logging Setup Source: https://docs.python.org/es/3/howto/logging-cookbook Sets up a multiprocessing queue and starts a listener process and multiple worker processes. Workers send log messages to the queue, and the listener processes them. A `None` is put into the queue to signal the listener to terminate. ```Python import multiprocessing def listener_process(queue, configurer): # Listener logic here pass def worker_process(queue, configurer): # Worker logic here pass def main(): queue = multiprocessing.Queue(-1) listener = multiprocessing.Process(target=listener_process, args=(queue, listener_configurer)) listener.start() workers = [] for i in range(10): worker = multiprocessing.Process(target=worker_process, args=(queue, worker_configurer)) workers.append(worker) worker.start() for w in workers: w.join() queue.put_nowait(None) listener.join() if __name__ == '__main__': main() ``` -------------------------------- ### Install Debug Symbols and Packages (Fedora) Source: https://docs.python.org/es/3/howto/gdb_helpers This example demonstrates how to install GDB and the Python debug symbols on Fedora using the `dnf` package manager. This is a prerequisite for debugging Python with GDB on this distribution. ```bash sudo dnf install gdb sudo dnf debuginfo-install python3 ``` -------------------------------- ### Install Python Certificates Source: https://docs.python.org/es/3/using/mac This command is executed after the main Python installation to download and install SSL root certificates required for Python's secure communication. It opens a temporary terminal window and verifies successful installation. ```Shell open "/Applications/Python 3.13/Install Certificates.command" ``` -------------------------------- ### Apply Custom Installer Choices to Python Installation Source: https://docs.python.org/es/3/using/mac Installs the Python package using the downloaded installer, applying the custom 'choicechanges.plist' file to the target root directory. This command requires administrator privileges. ```shell sudo installer -pkg ./${RELEASE} -applyChoiceChangesXML ./choicechanges.plist -target / ``` -------------------------------- ### Get Opcodes - SequenceMatcher Source: https://docs.python.org/es/3/library/difflib Explains and demonstrates get_opcodes() which returns a list of tuples describing how to transform one sequence into another. Each tuple contains a tag ('replace', 'delete', 'insert', 'equal') and indices for both sequences. ```python >>> a = "qabxcd" >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format( ... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2])) delete a[0:1] --> b[0:0] 'q' --> '' equal a[1:3] --> b[0:2] 'ab' --> 'ab' replace a[3:4] --> b[2:3] 'x' --> 'y' equal a[4:6] --> b[3:5] 'cd' --> 'cd' insert a[6:6] --> b[5:6] '' --> 'f' ``` -------------------------------- ### Python `dbm` Database Operations Example Source: https://docs.python.org/es/3/library/dbm This Python code snippet demonstrates how to use the `dbm.open()` function to create and interact with a database. It shows how to store key-value pairs, retrieve values using `get()`, and handle data storage, including implicit conversion of string keys/values to bytes. The example utilizes a `with` statement for automatic database closing. ```Python import dbm # Open database, creating it if necessary. with dbm.open('cache', 'c') as db: # Record some values db[b'hello'] = b'there' db['www.python.org'] = 'Python Website' db['www.cnn.com'] = 'Cable News Network' # Note that the keys are considered bytes now. assert db[b'www.python.org'] == b'Python Website' # Notice how the value is now in bytes. assert db['www.cnn.com'] == b'Cable News Network' # Often-used methods of the dict interface work too. print(db.get('python.org', b'not present')) # Storing a non-string key or value will raise an exception ( # most likely a TypeError). db['www.yahoo.com'] = 4 # db is automatically closed when leaving the with statement. ``` -------------------------------- ### Python Logging Example Usage Source: https://docs.python.org/es/3/howto/logging-cookbook Demonstrates how to get loggers and log messages at different levels (debug, info, warning, error). This code snippet shows the client-side logging that would be sent to the TCP server. ```python logger1 = logging.getLogger('myapp.area1') logger2 = logging.getLogger('myapp.area2') logger1.debug('Quick zephyrs blow, vexing daft Jim.') logger1.info('How quickly daft jumping zebras vex.') logger2.warning('Jail zesty vixen who grabbed pay from quack.') logger2.error('The five boxing wizards jump quickly.') ``` -------------------------------- ### Python Main Execution with Multiprocessing Logging Source: https://docs.python.org/es/3/howto/logging-cookbook Demonstrates the main execution flow for multiprocessing logging. It initializes logging, creates worker processes, starts a listener process, and manages their lifecycle. Logging is used to track the setup and completion of processes. ```python import logging import logging.config from multiprocessing import Process, Queue, Event def worker_process(config): logging.config.dictConfig(config) logger = logging.getLogger('worker') logger.info('Worker started') def listener_process(queue, stop_event, config): logging.config.dictConfig(config) logger = logging.getLogger('listener') logger.info('Listener started') while not stop_event.is_set(): try: record = queue.get() if record is None: break logger.handle(record) except Exception as e: logger.error(f'Error in listener: {e}') logger.info('Listener stopped') def main(): q = Queue(-1) config_initial = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'DEBUG' } }, 'root': { 'handlers': ['console'], 'level': 'DEBUG' } } config_worker = { 'version': 1, 'disable_existing_loggers': True, 'handlers': { 'queue': { 'class': 'logging.handlers.QueueHandler', 'queue': q } }, 'root': { 'handlers': ['queue'], 'level': 'DEBUG' } } config_listener = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'detailed': { 'class': 'logging.Formatter', 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' }, 'simple': { 'class': 'logging.Formatter', 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'level': 'INFO' }, 'file': { 'class': 'logging.FileHandler', 'filename': 'mplog.log', 'mode': 'w', 'formatter': 'detailed' }, 'foofile': { 'class': 'logging.FileHandler', 'filename': 'mplog-foo.log', 'mode': 'w', 'formatter': 'detailed' }, 'errors': { 'class': 'logging.FileHandler', 'filename': 'mplog-errors.log', 'mode': 'w', 'formatter': 'detailed', 'level': 'ERROR' } }, 'loggers': { 'foo': { 'handlers': ['foofile'] } }, 'root': { 'handlers': ['console', 'file', 'errors'], 'level': 'DEBUG' } } 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,)) # Pass config_worker to worker_process 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)) # Pass config_listener to listener_process lp.start() logger.info('Started listener') for wp in workers: wp.join() logger.info('Telling listener to stop ...') stop_event.set() lp.join() logger.info('All done.') if __name__ == '__main__': main() ``` -------------------------------- ### Python ensurepip Module Command-Line Options Source: https://docs.python.org/es/3/genindex-O Lists command-line options for the 'ensurepip' module, used to bootstrap pip into a Python environment. Options control default pip installation, alternative installation paths, and user-specific installations. ```bash # ensurepip Module Options python -m ensurepip --default-pip --user ``` -------------------------------- ### Initialize Python with Configuration Source: https://docs.python.org/es/3/c-api/init This snippet demonstrates how to initialize the Python interpreter using a PyConfig structure, setting command-line arguments, and then running the main interpreter loop. It encapsulates the standard Python startup process. ```C PyConfig config; PyConfig_InitPythonConfig(&config); PyConfig_SetArgv(&config, argc, argv); Py_InitializeFromConfig(&config); PyConfig_Clear(&config); Py_RunMain(); ``` -------------------------------- ### Get Matching Blocks - SequenceMatcher Source: https://docs.python.org/es/3/library/difflib Demonstrates how to retrieve matching blocks between two sequences using get_matching_blocks(). It returns tuples indicating the start and length of matching segments. ```python >>> s.get_matching_blocks() [Match(a=0, b=0, size=0), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] ``` -------------------------------- ### Create Simple WSGI App and Server Source: https://docs.python.org/es/3/library/wsgiref Demonstrates how to create a basic WSGI application that displays environment variables and serves it using `wsgiref.simple_server`. It sets up default testing values for the environment and responds with plain text. ```Python from wsgiref.simple_server import make_server # environment dictionary after being updated by setup_testing_defaults 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() ``` -------------------------------- ### Start an HTTP server and open a browser Source: https://docs.python.org/es/3/library/pydoc This command starts the HTTP documentation server and automatically opens a web browser to a module index page for easy navigation. ```bash python -m pydoc -b ``` -------------------------------- ### Unittest Test Case Setup (unittest module) Source: https://docs.python.org/es/3/genindex-S Methods like setUp() and setUpClass() in unittest.TestCase are used to set up the test environment before individual tests or test classes are run. ```Python setUp() setUpClass() setUpModule() ``` -------------------------------- ### Python Class Inheritance Hierarchy Example Source: https://docs.python.org/es/3/howto/mro Demonstrates a complex multiple inheritance scenario in Python, illustrating the relationships between classes and the potential for MRO conflicts. This example uses new-style classes starting from the 'object' base class. ```Python >>> O = object >>> class X(O): pass >>> class Y(O): pass >>> class A(X,Y): pass >>> class B(Y,X): pass ``` -------------------------------- ### WSGI Environment Setup (wsgiref module) Source: https://docs.python.org/es/3/genindex-S Functions in wsgiref.handlers and wsgiref.util for setting up the WSGI environment and testing defaults. ```Python setup_environ() setup_testing_defaults() ``` -------------------------------- ### Python itertools.count Example Source: https://docs.python.org/es/3/library/itertools Generates an iterator that returns evenly spaced values starting from a specified number. It can be used with map() or zip(). The example shows generating consecutive integers and floating-point numbers. ```Python def count(start=0, step=1): # count(10) → 10 11 12 13 14 ... # count(2.5, 0.5) → 2.5 3.0 3.5 ... n = start while True: yield n n += step ``` -------------------------------- ### Start an HTTP server for documentation Source: https://docs.python.org/es/3/library/pydoc This command starts an HTTP server on the specified port, allowing you to browse module documentation through a web browser. Port 0 selects an arbitrary unused port. ```bash python -m pydoc -p ``` -------------------------------- ### Prepare Environment with Bash Script Source: https://docs.python.org/es/3/howto/logging-cookbook This Bash script prepares the environment for testing the socket logging listener. It creates necessary directories for logs and virtual environments, and installs required Python packages like Bottle, Gunicorn, and Supervisor. ```Bash bash prepare.sh ``` -------------------------------- ### Get module filename Source: https://docs.python.org/es/3/library/importlib Retrieves the filename associated with a module. This function is available starting from Python 3.4. ```Python importlib.machinery.get_filename(_fullname_) ``` -------------------------------- ### Create ArgumentParser Instance Source: https://docs.python.org/es/3/library/argparse This snippet demonstrates how to create an instance of `argparse.ArgumentParser`. It shows how to set the program name, a description of what the program does, and an epilog text that appears at the bottom of the help message. ```Python parser = argparse.ArgumentParser( prog='ProgramName', description='What the program does', epilog='Text at the bottom of help') ``` -------------------------------- ### Python's post_setup() Method for Virtual Environment Builder Source: https://docs.python.org/es/3/genindex-P The post_setup() method in venv.EnvBuilder is called after a virtual environment has been created. It can be overridden to perform custom setup tasks within the new environment. ```python post_setup() (método de venv.EnvBuilder) ``` -------------------------------- ### Get Relative Path Source: https://docs.python.org/es/3/genindex-R Returns a relative filepath from the start path to the end path. This function is part of the 'os.path' module. ```Python os.path.relpath(path[, start]) ``` -------------------------------- ### Python Documentation Licensing Source: https://docs.python.org/es/3/license Starting with Python 3.8.6, code examples, recipes, and other content within the Python documentation are dual-licensed. This dual licensing allows for flexibility in how the content can be used and distributed. ```Python Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Version 2 and the Zero-Clause BSD license. ``` -------------------------------- ### Doctest and Inspect Filename Attributes Source: https://docs.python.org/es/3/genindex-F The 'filename' attribute is used in doctest to associate test examples with their source file and in the inspect module to get information about frames and tracebacks, including the filename. ```Python import doctest import inspect # Doctest example (conceptual): # test = doctest.DocTest(None, {}, 'example.txt', None, 0, None) # print(test.filename) # Inspect example (conceptual): # frame_info = inspect.currentframe() # if frame_info: # print(frame_info.f_code.co_filename) ``` -------------------------------- ### Python optparse Example for Command Line Options Source: https://docs.python.org/es/3/library/getopt Shows how to use the optparse module for a more declarative approach to command-line option parsing. This example defines options like '--output' and a verbose flag. ```Python import optparse if __name__ == '__main__': parser = optparse.OptionParser() parser.add_option('-o', '--output') parser.add_option('-v', dest='verbose', action='store_true') opts, args = parser.parse_args() process(args, output=opts.output, verbose=opts.verbose) ``` -------------------------------- ### Python ftplib FTP Class Initialization Source: https://docs.python.org/es/3/library/ftplib Demonstrates the initialization of the `ftplib.FTP` class, including parameters for host, user, password, account, timeout, source address, and encoding. It also shows an example of using the class with a `with` statement for automatic connection management. ```Python from ftplib import FTP # Example of initializing FTP with connection details # ftp = FTP(host='ftp.example.com', user='user', passwd='password') # Example using the 'with' statement with FTP("ftp1.at.proftpd.org") as ftp: ftp.login() ftp.dir() ``` -------------------------------- ### Turtle position and screen clearing Source: https://docs.python.org/es/3/library/turtle Provides commands to return the turtle to its starting position (`home()`), get its current coordinates (`pos()`), and clear the drawing screen (`clearscreen()`) for new drawings. ```Python home() ``` ```Python pos() ``` ```Python clearscreen() ``` -------------------------------- ### Start an HTTP server with a specific hostname Source: https://docs.python.org/es/3/library/pydoc This command starts an HTTP server listening on the specified hostname, which is useful for accessing the documentation from other machines or within containers. ```bash python -m pydoc -n ``` -------------------------------- ### Get a slice of a tuple (C API) Source: https://docs.python.org/es/3/c-api/tuple The `PyTuple_GetSlice` function extracts a portion of a tuple based on start and end indices, returning a new tuple. It returns `NULL` on failure. ```C PyObject *PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high); ``` -------------------------------- ### Python Calling a Regular Function Source: https://docs.python.org/es/3/howto/a-conceptual-overview-of-asyncio Demonstrates how to call a regular Python function ('hello_printer') and shows the expected output. This illustrates the synchronous execution of a standard function. ```Python >>> hello_printer() Hi, I am a lowly, simple printer, though I have all I need in life -- fresh paper and my dearly beloved octopus partner in crime. ``` -------------------------------- ### Virtual Environment Setup (venv module) Source: https://docs.python.org/es/3/genindex-S The EnvBuilder class in the 'venv' module provides methods like setup_environ() and setup_scripts() for configuring virtual environments. ```Python setup_environ() setup_scripts() ``` -------------------------------- ### Python ioctl Example Source: https://docs.python.org/es/3/library/fcntl Demonstrates using fcntl.ioctl to get and set the process group ID associated with a terminal. It shows how to unpack the result and use a mutable buffer for operations. ```Python import array, fcntl, struct, termios, os os.getpgrp() struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, " "))[0] buf = array.array('h', [0]) fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1) buf ``` -------------------------------- ### Running Python XML-RPC Server from Command Line Source: https://docs.python.org/es/3/library/xmlrpc Provides the command to run the built-in XML-RPC server module directly from the command line, useful for quick testing or simple server deployments. ```Shell python -m xmlrpc.server ``` -------------------------------- ### Python Helper for First Sunday on or After Date Source: https://docs.python.org/es/3/library/datetime A utility function to calculate the first Sunday on or after a given date. This is useful for determining DST start and end dates which are often defined by specific Sundays in a month. ```python def first_sunday_on_or_after(dt): days_to_go = 6 - dt.weekday() if days_to_go: dt += timedelta(days_to_go) return dt ``` -------------------------------- ### Running Python XML-RPC Client from Command Line Source: https://docs.python.org/es/3/library/xmlrpc Provides the command to run the built-in XML-RPC client module directly from the command line, useful for quick testing or simple client interactions. ```Shell python -m xmlrpc.client ``` -------------------------------- ### venv Command Usage and Options Source: https://docs.python.org/es/3/library/venv Displays the help message for the 'venv' command, outlining all available options for creating and configuring Python virtual environments. This includes options for system site packages, symlinks, clearing, upgrading, and managing pip. ```bash usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps] [--without-scm-ignore-files] ENV_DIR [ENV_DIR ...] ``` -------------------------------- ### Python String Slicing Examples Source: https://docs.python.org/es/3/tutorial/introduction Demonstrates basic string slicing in Python, including extracting characters from the beginning, end, and specific ranges. It highlights that the start index is inclusive and the end index is exclusive. ```Python >>> word[:2] # character from the beginning to position 2 (excluded) 'Py' >>> word[4:] # characters from position 4 (included) to the end 'on' >>> word[-2:] # characters from the second-last (included) to the end 'on' ``` -------------------------------- ### Python US DST Rules (Historical) Source: https://docs.python.org/es/3/library/datetime Defines historical Daylight Saving Time start and end dates for the US, based on regulations from different periods. This includes rules for 2007 onwards, 1987-2006, and 1967-1986. ```python # US DST Rules # # This is a simplified (i.e., wrong for a few cases) set of rules for US # DST start and end times. For a complete and up-to-date set of DST rules # and timezone definitions, visit the Olson Database (or try pytz): # http://www.twinsun.com/tz/tz-link.htm # https://sourceforge.net/projects/pytz/ (might not be up-to-date) # # In the US, since 2007, DST starts at 2am (standard time) on the second # Sunday in March, which is the first Sunday on or after Mar 8. DSTSTART_2007 = datetime(1, 3, 8, 2) # and ends at 2am (DST time) on the first Sunday of Nov. DSTEND_2007 = datetime(1, 11, 1, 2) # From 1987 to 2006, DST used to start at 2am (standard time) on the first # Sunday in April and to end at 2am (DST time) on the last # Sunday of October, which is the first Sunday on or after Oct 25. DSTSTART_1987_2006 = datetime(1, 4, 1, 2) DSTEND_1987_2006 = datetime(1, 10, 25, 2) # From 1967 to 1986, DST used to start at 2am (standard time) on the last # Sunday in April (the one on or after April 24) and to end at 2am (DST time) # on the last Sunday of October, which is the first Sunday ``` -------------------------------- ### Python timer file descriptor example Source: https://docs.python.org/es/3/howto/timerfd Demonstrates using a timer file descriptor to execute a function twice a second. It covers creating the descriptor, setting the timer, reading events, and closing the descriptor. ```Python # Practical scripts should use really use a non-blocking timer, # we use a blocking timer here for simplicity. import os, time # Create the timer file descriptor fd = os.timerfd_create(time.CLOCK_REALTIME) # Start the timer in 1 second, with an interval of half a second os.timerfd_settime(fd, initial=1, interval=0.5) try: # Process timer events four times. for _ in range(4): # read() will block until the timer expires _ = os.read(fd, 8) print("Timer expired") finally: # Remember to close the timer file descriptor! os.close(fd) ``` -------------------------------- ### Python Import Example Source: https://docs.python.org/es/3/library/importlib Demonstrates an example of importing a module (`_whiz`) from a specific path (`foo.bar`) in Python. This import statement is used to illustrate the framework distribution mechanism described in the documentation. ```Python from foo.bar import _whiz ``` -------------------------------- ### Get OpenSSL Library Version String (Python) Source: https://docs.python.org/es/3/library/ssl Retrieves the version string of the OpenSSL library loaded by the interpreter. Example: 'OpenSSL 1.0.2k 26 Jan 2017'. Added in version 3.2. ```Python ssl.OPENSSL_VERSION ``` -------------------------------- ### Python Main Function for Simulating Web Applications Source: https://docs.python.org/es/3/howto/logging-cookbook The `main` function in this Python script sets up and simulates multiple web applications. It uses `argparse` to handle command-line arguments, specifically the number of requests to simulate. It creates instances of the `WebApp` class, sets up a common log handler, and then spawns threads to process simulated requests concurrently. Finally, it waits for all threads to complete and prints the number of requests processed by each application. ```Python import os import argparse import threading from random import choice # Assuming WebApp, ctx_request, ctx_appname, logger, formatter, root, REQUESTS are defined elsewhere # from your_module import WebApp, ctx_request, ctx_appname, logger, formatter, root, REQUESTS def main(): fn = os.path.splitext(os.path.basename(__file__))[0] adhf = argparse.ArgumentDefaultsHelpFormatter ap = argparse.ArgumentParser(formatter_class=adhf, prog=fn, description='Simulate a couple of web ' 'applications handling some ' 'requests, showing how request ' 'context can be used to ' 'populate logs') aa = ap.add_argument aa('--count', '-c', type=int, default=100, help='How many requests to simulate') options = ap.parse_args() # Create the dummy webapps and put them in a list which we can use to select # from randomly app1 = WebApp('app1') app2 = WebApp('app2') apps = [app1, app2] threads = [] # Add a common handler which will capture all events handler = logging.FileHandler('app.log', 'w') handler.setFormatter(formatter) root.addHandler(handler) # Generate calls to process requests for i in range(options.count): try: # Pick an app at random and a request for it to process app = choice(apps) request = choice(REQUESTS) # Process the request in its own thread t = threading.Thread(target=app.process_request, args=(request,)) threads.append(t) t.start() except KeyboardInterrupt: break # Wait for the threads to terminate for t in threads: t.join() for app in apps: print('%s processed %s requests' % (app.name, app.num_requests)) if __name__ == '__main__': main() ``` -------------------------------- ### Get Raw OpenSSL Library Version Number (Python) Source: https://docs.python.org/es/3/library/ssl Provides the raw version number of the OpenSSL library as a single integer. Example: 268443839, which can be represented in hex as '0x100020bf'. Added in version 3.2. ```Python ssl.OPENSSL_VERSION_NUMBER ``` -------------------------------- ### Connecting and Sending Data with poplib in Python Source: https://docs.python.org/es/3/library/audit_events Details the `poplib.connect` and `poplib.putline` methods for interacting with POP3 servers. `connect` establishes a connection, and `putline` sends data over the connection. ```Python import poplib # Example for connecting (replace with actual server details) # try: # server = poplib.POP3_SSL('your_pop3_server.com') # server.user('your_username') # server.pass_('your_password') # print("Connected successfully") # # # Example for putline (sending a command) # # server.putline(b'LIST') # # server.getreply() # # server.quit() # except poplib.error_proto as e: # print(f"POP3 error: {e}") ``` -------------------------------- ### Get OpenSSL Library Version Information Tuple (Python) Source: https://docs.python.org/es/3/library/ssl Returns a tuple of five integers representing the version information of the OpenSSL library. Example: (1, 0, 2, 11, 15). Added in version 3.2. ```Python ssl.OPENSSL_VERSION_INFO ``` -------------------------------- ### Python itertools.islice Example Source: https://docs.python.org/es/3/library/itertools Demonstrates how to use `itertools.islice` to create an iterator that returns selected elements from an iterable. It mimics sequence slicing but does not support negative values. The function handles start, stop, and step parameters to control which elements are yielded. ```Python def islice(iterable, *args): # islice('ABCDEFG', 2) → A B # islice('ABCDEFG', 2, 4) → C D # islice('ABCDEFG', 2, None) → C D E F G # islice('ABCDEFG', 0, None, 2) → A C E G s = slice(*args) start = 0 if s.start is None else s.start stop = s.stop step = 1 if s.step is None else s.step if start < 0 or (stop is not None and stop < 0) or step <= 0: raise ValueError indices = count() if stop is None else range(max(start, stop)) next_i = start for i, element in zip(indices, iterable): if i == next_i: yield element next_i += step ``` -------------------------------- ### Python Webapplib Logging Example Source: https://docs.python.org/es/3/howto/logging-cookbook This snippet demonstrates basic logging within a Python library, simulating an event and introducing a small delay to allow other threads to execute. It uses the standard `logging` and `time` modules. ```Python import logging import time logger = logging.getLogger(__name__) def useful(): # Just a representative event logged from the library logger.debug('Hello from webapplib!') # Just sleep for a bit so other threads get to run time.sleep(0.01) ``` -------------------------------- ### Bash Script for Framework Signing and Python Module Installation Source: https://docs.python.org/es/3/using/ios This bash script snippet is part of a build process. It creates a back reference to the .so file location in the framework, installs Python standard library extension modules by finding and copying .so files, cleans up a dylib template, and signs frameworks using the codesign command with specified identity and flags. ```bash # Create a back reference to the .so file location in the framework echo "${RELATIVE_EXT%.so}.fwork" > "$CODESIGNING_FOLDER_PATH/$FRAMEWORK_FOLDER/$FULL_MODULE_NAME.origin" PYTHON_VER=$(ls -1 "$CODESIGNING_FOLDER_PATH/python/lib") echo "Install Python $PYTHON_VER standard library extension modules..." find "$CODESIGNING_FOLDER_PATH/python/lib/$PYTHON_VER/lib-dynload" -name "*.so" | while read FULL_EXT; install_dylib python/lib/$PYTHON_VER/lib-dynload/ "$FULL_EXT" done # Clean up dylib template rm -f "$CODESIGNING_FOLDER_PATH/dylib-Info-template.plist" echo "Signing frameworks as $EXPANDED_CODE_SIGN_IDENTITY_NAME ($EXPANDED_CODE_SIGN_IDENTITY)..." find "$CODESIGNING_FOLDER_PATH/Frameworks" -name "*.framework" -exec /usr/bin/codesign --force --sign "$EXPANDED_CODE_SIGN_IDENTITY" ${OTHER_CODE_SIGN_FLAGS:-} -o runtime --timestamp=none --preserve-metadata=identifier,entitlements,flags --generate-entitlement-der "{}" \; ```