id
int64
0
2.72k
content
stringlengths
5
4.1k
language
stringclasses
4 values
embedding
unknown
300
levels writing to sys stderr to say what level it s about to log at and then actually logging a message at that level You can pass a parameter to foo which if true will log at ERROR and CRITICAL levels otherwise it only logs at DEBUG INFO and WARNING levels The script just arranges to decorate foo with a decorator which will do the conditional logging that s required The decorator takes a logger as a parameter and attaches a memory handler for the duration of the call to the decorated function The decorator can be additionally parameterised using a target handler a level at which flushing should occur and a capacity for the buffer number of records buffered These default to a StreamHandler which writes to sys stderr logging ERROR and 100 respectively Here s the script import logging from logging handlers import MemoryHandler import sys logger logging getLogger __name__ logger addHandler logging NullHandler def log_if_errors logger target_handler None flush_level None capacity None if target_handler is None target_handler logging StreamHandler if flush_level is None flush_level logging ERROR if capacity is None capacity 100 handler MemoryHandler capacity flushLevel flush_level target target_handler def decorator fn def wrapper args kwargs logger addHandler handler try return fn args kwargs except Exception logger exception call failed raise finally super MemoryHandler handler flush logger removeHandler handler return wrapper return decorator def write_line s sys stderr write s n s def foo fail False write_line about to log at DEBUG logger debug Actually logged at DEBUG write_line about to log at INFO logger info Actually logged at INFO write_line about to log at WARNING logger warning Actually logged at WARNING if fail write_line about to log at ERROR logger error Actually logged at ERROR write_line about to log at CRITICAL logger critical Actually logged at CRITICAL return fail decorated_foo log_if_errors logger foo if __name__ __main__ logger setLevel logging DEBUG write_line Calling undecorated foo with False assert not foo False write_line Calling undecorated foo with True assert foo True write_line Calling decorated foo with False assert not decorated_foo False write_line Calling decorated foo with True assert decorated_foo True When this script is run the following output should be observed Calling undecorated foo with False about to log at DEBUG about to log at INFO about to log at WARNING Calling undecorated foo with True about to log at DEBUG about to log at INFO about to log at WARNING about to log at ERROR about to log at CRITICAL Calling decorated foo with False about to log at DEBUG about to log at INFO about to log at WARNING Calling decorated foo with True about to log at DEBUG about to log at INFO about to log at WARNING about to log at ERROR Actually logged at DEBUG Actually logged at INFO Actually logged at WARNING Actually logged at ERROR about to log at CRITICAL Actually logged at CRITICAL As you can see actual logging output only occurs when an event is logged whose severity is ERROR or greater but in that case any previous events at lower severities are also logged You can of course use the conventional means of decoration log_if_errors logger def foo fail False Sending logging messages to email with buffering To illustrate how you can send log messages via email so that a set number of messages are sent per email you can subclass BufferingHandler In the following example which you can adapt to suit your specific needs a simple test harness is provided which allows you to run the script with command line arguments specifying what you typically need to send things via SMTP Run the downloaded script with the h argument to see the required and optional arguments import logging import logging handlers import smtplib class BufferingSMTPHandler logging handlers BufferingHandler def __init__ self mailhost port username password fromaddr toaddrs subject capacity logging handlers BufferingHandler __init__ self capacity self mailhost mailhost self mailport port self username username self password password se
en
null
301
lf fromaddr fromaddr if isinstance toaddrs str toaddrs toaddrs self toaddrs toaddrs self subject subject self setFormatter logging Formatter asctime s levelname 5s message s def flush self if len self buffer 0 try smtp smtplib SMTP self mailhost self mailport smtp starttls smtp login self username self password msg From s r nTo s r nSubject s r n r n self fromaddr join self toaddrs self subject for record in self buffer s self format record msg msg s r n smtp sendmail self fromaddr self toaddrs msg smtp quit except Exception if logging raiseExceptions raise self buffer if __name__ __main__ import argparse ap argparse ArgumentParser aa ap add_argument aa host metavar HOST help SMTP server aa port p type int default 587 help SMTP port aa user metavar USER help SMTP username aa password metavar PASSWORD help SMTP password aa to metavar TO help Addressee for emails aa sender metavar SENDER help Sender email address aa subject s default Test Logging email from Python logging module buffering help Subject of email options ap parse_args logger logging getLogger logger setLevel logging DEBUG h BufferingSMTPHandler options host options port options user options password options sender options to options subject 10 logger addHandler h for i in range 102 logger info Info index d i h flush h close If you run this script and your SMTP server is correctly set up you should find that it sends eleven emails to the addressee you specify The first ten emails will each have ten log messages and the eleventh will have two messages That makes up 102 messages as specified in the script Formatting times using UTC GMT via configuration Sometimes you want to format times using UTC which can be done using a class such as UTCFormatter shown below import logging import time class UTCFormatter logging Formatter converter time gmtime and you can then use the UTCFormatter in your code instead of Formatter If you want to do that via configuration you can use the dictConfig API with an approach illustrated by the following complete example import logging import logging config import time class UTCFormatter logging Formatter converter time gmtime LOGGING version 1 disable_existing_loggers False formatters utc UTCFormatter format asctime s message s local format asctime s message s handlers console1 class logging StreamHandler formatter utc console2 class logging StreamHandler formatter local root handlers console1 console2 if __name__ __main__ logging config dictConfig LOGGING logging warning The local time is s time asctime When this script is run it should print something like 2015 10 17 12 53 29 501 The local time is Sat Oct 17 13 53 29 2015 2015 10 17 13 53 29 501 The local time is Sat Oct 17 13 53 29 2015 showing how the time is formatted both as local time and UTC one for each handler Using a context manager for selective logging There are times when it would be useful to temporarily change the logging configuration and revert it back after doing something For this a context manager is the most obvious way of saving and restoring the logging context Here is a simple example of such a context manager which allows you to optionally change the logging level and add a logging handler purely in the scope of the context manager import logging import sys class LoggingContext def __init__ self logger level None handler None close True self logger logger self level level self handler handler self close close def __enter__ self if self level is not None self old_level self logger level self logger setLevel self level if self handler self logger addHandler self handler def __exit__ self et ev tb if self level is not None self logger setLevel self old_level if self handler self logger removeHandler self handler if self handler and self close self handler close implicit return of None don t swallow exceptions If you specify a level value the logger s level is set to that value in the scope of the with block covered by the context manager If you specify a handler it is added to the logger on entry to the block and removed on exit from the block You can also ask
en
null
302
the manager to close the handler for you on block exit you could do this if you don t need the handler any more To illustrate how it works we can add the following block of code to the above if __name__ __main__ logger logging getLogger foo logger addHandler logging StreamHandler logger setLevel logging INFO logger info 1 This should appear just once on stderr logger debug 2 This should not appear with LoggingContext logger level logging DEBUG logger debug 3 This should appear once on stderr logger debug 4 This should not appear h logging StreamHandler sys stdout with LoggingContext logger level logging DEBUG handler h close True logger debug 5 This should appear twice once on stderr and once on stdout logger info 6 This should appear just once on stderr logger debug 7 This should not appear We initially set the logger s level to INFO so message 1 appears and message 2 doesn t We then change the level to DEBUG temporarily in the following with block and so message 3 appears After the block exits the logger s level is restored to INFO and so message 4 doesn t appear In the next with block we set the level to DEBUG again but also add a handler writing to sys stdout Thus message 5 appears twice on the console once via stderr and once via stdout After the with statement s completion the status is as it was before so message 6 appears like message 1 whereas message 7 doesn t just like message 2 If we run the resulting script the result is as follows python logctx py 1 This should appear just once on stderr 3 This should appear once on stderr 5 This should appear twice once on stderr and once on stdout 5 This should appear twice once on stderr and once on stdout 6 This should appear just once on stderr If we run it again but pipe stderr to dev null we see the following which is the only message written to stdout python logctx py 2 dev null 5 This should appear twice once on stderr and once on stdout Once again but piping stdout to dev null we get python logctx py dev null 1 This should appear just once on stderr 3 This should appear once on stderr 5 This should appear twice once on stderr and once on stdout 6 This should appear just once on stderr In this case the message 5 printed to stdout doesn t appear as expected Of course the approach described here can be generalised for example to attach logging filters temporarily Note that the above code works in Python 2 as well as Python 3 A CLI application starter template Here s an example which shows how you can Use a logging level based on command line arguments Dispatch to multiple subcommands in separate files all logging at the same level in a consistent way Make use of simple minimal configuration Suppose we have a command line application whose job is to stop start or restart some services This could be organised for the purposes of illustration as a file app py that is the main script for the application with individual commands implemented in start py stop py and restart py Suppose further that we want to control the verbosity of the application via a command line argument defaulting to logging INFO Here s one way that app py could be written import argparse import importlib import logging import os import sys def main args None scriptname os path basename __file__ parser argparse ArgumentParser scriptname levels DEBUG INFO WARNING ERROR CRITICAL parser add_argument log level default INFO choices levels subparsers parser add_subparsers dest command help Available commands start_cmd subparsers add_parser start help Start a service start_cmd add_argument name metavar NAME help Name of service to start stop_cmd subparsers add_parser stop help Stop one or more services stop_cmd add_argument names metavar NAME nargs help Name of service to stop restart_cmd subparsers add_parser restart help Restart one or more services restart_cmd add_argument names metavar NAME nargs help Name of service to restart options parser parse_args the code to dispatch commands could all be in this file For the purposes of illustration only we implement each command in a separate module try mod impo
en
null
303
rtlib import_module options command cmd getattr mod command except ImportError AttributeError print Unable to find the code for command s options command return 1 Could get fancy here and load configuration from file or dictionary logging basicConfig level options log_level format levelname s name s message s cmd options if __name__ __main__ sys exit main And the start stop and restart commands can be implemented in separate modules like so for starting start py import logging logger logging getLogger __name__ def command options logger debug About to start s options name actually do the command processing here logger info Started the s service options name and thus for stopping stop py import logging logger logging getLogger __name__ def command options n len options names if n 1 plural services s options names 0 else plural s services join s name for name in options names i services rfind services services i and services i 2 logger debug About to stop s services actually do the command processing here logger info Stopped the s service s services plural and similarly for restarting restart py import logging logger logging getLogger __name__ def command options n len options names if n 1 plural services s options names 0 else plural s services join s name for name in options names i services rfind services services i and services i 2 logger debug About to restart s services actually do the command processing here logger info Restarted the s service s services plural If we run this application with the default log level we get output like this 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 The first word is the logging level and the second word is the module or package name of the place where the event was logged If we change the logging level then we can change the information sent to the log For example if we want more information 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 And if we want less 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 In this case the commands don t print anything to the console since nothing at WARNING level or above is logged by them A Qt GUI for logging A question that comes up from time to time is about how to log to a GUI application The Qt framework is a popular cross platform UI framework with Python bindings using PySide2 or PyQt5 libraries The following example shows how to log to a Qt GUI This introduces a simple QtHandler class which takes a callable which should be a slot in the main thread that does GUI updates A worker thread is also created to show how you can log to the GUI from both the UI itself via a button for manual logging as well as a worker thread doing work in the background here just logging messages at random levels with random short delays in between The worker thread is implemented using Qt s QThread class rather than the threading module as there are circumstances where one has to use QThread which offers better integration with other Qt components The code should work with recent releases of either PySide6 PyQt6 PySide2 or PyQt5 You should be able to adapt the approach to earlier versions of Qt Please refer to the comments in the code snippet for more detailed information import datetime import logging import random import sys import time Deal with minor differences between different Qt packages try from PySide6 import QtCore QtGui QtWidgets Signal QtCore Signal Slot QtCore Slot except ImportError try from PyQt6 import QtCore QtGui QtWidgets Signal QtCore pyqtSignal Slot QtCore pyqtSlo
en
null
304
t except ImportError try from PySide2 import QtCore QtGui QtWidgets Signal QtCore Signal Slot QtCore Slot except ImportError from PyQt5 import QtCore QtGui QtWidgets Signal QtCore pyqtSignal Slot QtCore pyqtSlot logger logging getLogger __name__ Signals need to be contained in a QObject or subclass in order to be correctly initialized class Signaller QtCore QObject signal Signal str logging LogRecord Output to a Qt GUI is only supposed to happen on the main thread So this handler is designed to take a slot function which is set up to run in the main thread In this example the function takes a string argument which is a formatted log message and the log record which generated it The formatted string is just a convenience you could format a string for output any way you like in the slot function itself You specify the slot function to do whatever GUI updates you want The handler doesn t know or care about specific UI elements class QtHandler logging Handler def __init__ self slotfunc args kwargs super __init__ args kwargs self signaller Signaller self signaller signal connect slotfunc def emit self record s self format record self signaller signal emit s record This example uses QThreads which means that the threads at the Python level are named something like Dummy 1 The function below gets the Qt name of the current thread def ctname return QtCore QThread currentThread objectName Used to generate random levels for logging LEVELS logging DEBUG logging INFO logging WARNING logging ERROR logging CRITICAL This worker class represents work that is done in a thread separate to the main thread The way the thread is kicked off to do work is via a button press that connects to a slot in the worker Because the default threadName value in the LogRecord isn t much use we add a qThreadName which contains the QThread name as computed above and pass that value in an extra dictionary which is used to update the LogRecord with the QThread name This example worker just outputs messages sequentially interspersed with random delays of the order of a few seconds class Worker QtCore QObject Slot def start self extra qThreadName ctname logger debug Started work extra extra i 1 Let the thread run until interrupted This allows reasonably clean thread termination while not QtCore QThread currentThread isInterruptionRequested delay 0 5 random random 2 time sleep delay try if random random 0 1 raise ValueError Exception raised d i else level random choice LEVELS logger log level Message after delay of 3 1f d delay i extra extra except ValueError as e logger exception Failed s e extra extra i 1 Implement a simple UI for this cookbook example This contains A read only text edit window which holds formatted log messages A button to start work and log stuff in a separate thread A button to log something from the main thread A button to clear the log window class Window QtWidgets QWidget COLORS logging DEBUG black logging INFO blue logging WARNING orange logging ERROR red logging CRITICAL purple def __init__ self app super __init__ self app app self textedit te QtWidgets QPlainTextEdit self Set whatever the default monospace font is for the platform f QtGui QFont nosuchfont if hasattr f Monospace f setStyleHint f Monospace else f setStyleHint f StyleHint Monospace for Qt6 te setFont f te setReadOnly True PB QtWidgets QPushButton self work_button PB Start background work self self log_button PB Log a message at a random level self self clear_button PB Clear log window self self handler h QtHandler self update_status Remember to use qThreadName rather than threadName in the format string fs asctime s qThreadName 12s levelname 8s message s formatter logging Formatter fs h setFormatter formatter logger addHandler h Set up to terminate the QThread when we exit app aboutToQuit connect self force_quit Lay out all the widgets layout QtWidgets QVBoxLayout self layout addWidget te layout addWidget self work_button layout addWidget self log_button layout addWidget self clear_button self setFixedSize 900 400 Connect the non worker slots and signals self log_button
en
null
305
clicked connect self manual_update self clear_button clicked connect self clear_display Start a new worker thread and connect the slots for the worker self start_thread self work_button clicked connect self worker start Once started the button should be disabled self work_button clicked connect lambda self work_button setEnabled False def start_thread self self worker Worker self worker_thread QtCore QThread self worker setObjectName Worker self worker_thread setObjectName WorkerThread for qThreadName self worker moveToThread self worker_thread This will start an event loop in the worker thread self worker_thread start def kill_thread self Just tell the worker to stop then tell it to quit and wait for that to happen self worker_thread requestInterruption if self worker_thread isRunning self worker_thread quit self worker_thread wait else print worker has already exited def force_quit self For use when the window is closed if self worker_thread isRunning self kill_thread The functions below update the UI and run in the main thread because that s where the slots are set up Slot str logging LogRecord def update_status self status record color self COLORS get record levelno black s pre font color s s font pre color status self textedit appendHtml s Slot def manual_update self This function uses the formatted message passed in but also uses information from the record to format the message in an appropriate color according to its severity level level random choice LEVELS extra qThreadName ctname logger log level Manually logged extra extra Slot def clear_display self self textedit clear def main QtCore QThread currentThread setObjectName MainThread logging getLogger setLevel logging DEBUG app QtWidgets QApplication sys argv example Window app example show if hasattr app exec rc app exec else rc app exec_ sys exit rc if __name__ __main__ main Logging to syslog with RFC5424 support Although RFC 5424 dates from 2009 most syslog servers are configured by default to use the older RFC 3164 which hails from 2001 When logging was added to Python in 2003 it supported the earlier and only existing protocol at the time Since RFC5424 came out as there has not been widespread deployment of it in syslog servers the SysLogHandler functionality has not been updated RFC 5424 contains some useful features such as support for structured data and if you need to be able to log to a syslog server with support for it you can do so with a subclassed handler which looks something like this import datetime import logging handlers import re import socket import time class SysLogHandler5424 logging handlers SysLogHandler tz_offset re compile r d 2 d 2 escaped re compile r def __init__ self args kwargs self msgid kwargs pop msgid None self appname kwargs pop appname None super __init__ args kwargs def format self record version 1 asctime datetime datetime fromtimestamp record created isoformat m self tz_offset match time strftime z has_offset False if m and time timezone hrs mins m groups if int hrs or int mins has_offset True if not has_offset asctime Z else asctime f hrs mins try hostname socket gethostname except Exception hostname appname self appname or procid record process msgid msg super format record sdata if hasattr record structured_data sd record structured_data This should be a dict where the keys are SD ID and the value is a dict mapping PARAM NAME to PARAM VALUE refer to the RFC for what these mean There s no error checking here it s purely for illustration and you can adapt this code for use in production environments parts def replacer m g m groups return g 0 for sdid dv in sd items part f sdid for k v in dv items s str v s self escaped sub replacer s part f k s part parts append part sdata join parts return f version asctime hostname appname procid msgid sdata msg You ll need to be familiar with RFC 5424 to fully understand the above code and it may be that you have slightly different needs e g for how you pass structural data to the log Nevertheless the above should be adaptable to your speciric needs With the above handler you d pass
en
null
306
structured data using something like this sd foo 12345 bar baz baz bozz fizz r buzz foo 54321 rab baz zab bozz zzif r buzz extra structured_data sd i 1 logger debug Message d i extra extra How to treat a logger like an output stream Sometimes you need to interface to a third party API which expects a file like object to write to but you want to direct the API s output to a logger You can do this using a class which wraps a logger with a file like API Here s a short script illustrating such a class import logging class LoggerWriter def __init__ self logger level self logger logger self level level def write self message if message n avoid printing bare newlines if you like self logger log self level message def flush self doesn t actually do anything but might be expected of a file like object so optional depending on your situation pass def close self doesn t actually do anything but might be expected of a file like object so optional depending on your situation You might want to set a flag so that later calls to write raise an exception pass def main logging basicConfig level logging DEBUG logger logging getLogger demo info_fp LoggerWriter logger logging INFO debug_fp LoggerWriter logger logging DEBUG print An INFO message file info_fp print A DEBUG message file debug_fp if __name__ __main__ main When this script is run it prints INFO demo An INFO message DEBUG demo A DEBUG message You could also use LoggerWriter to redirect sys stdout and sys stderr by doing something like this import sys sys stdout LoggerWriter logger logging INFO sys stderr LoggerWriter logger logging WARNING You should do this after configuring logging for your needs In the above example the basicConfig call does this using the sys stderr value before it is overwritten by a LoggerWriter instance Then you d get this kind of result print Foo INFO demo Foo print Bar file sys stderr WARNING demo Bar Of course the examples above show output according to the format used by basicConfig but you can use a different formatter when you configure logging Note that with the above scheme you are somewhat at the mercy of buffering and the sequence of write calls which you are intercepting For example with the definition of LoggerWriter above if you have the snippet sys stderr LoggerWriter logger logging WARNING 1 0 then running the script results in WARNING demo Traceback most recent call last WARNING demo File home runner cookbook loggerwriter test py line 53 in module WARNING demo WARNING demo main WARNING demo File home runner cookbook loggerwriter test py line 49 in main WARNING demo WARNING demo 1 0 WARNING demo ZeroDivisionError WARNING demo WARNING demo division by zero As you can see this output isn t ideal That s because the underlying code which writes to sys stderr makes multiple writes each of which results in a separate logged line for example the last three lines above To get around this problem you need to buffer things and only output log lines when newlines are seen Let s use a slghtly better implementation of LoggerWriter class BufferingLoggerWriter LoggerWriter def __init__ self logger level super __init__ logger level self buffer def write self message if n not in message self buffer message else parts message split n if self buffer s self buffer parts pop 0 self logger log self level s self buffer parts pop for part in parts self logger log self level part This just buffers up stuff until a newline is seen and then logs complete lines With this approach you get better output WARNING demo Traceback most recent call last WARNING demo File home runner cookbook loggerwriter main py line 55 in module WARNING demo main WARNING demo File home runner cookbook loggerwriter main py line 52 in main WARNING demo 1 0 WARNING demo ZeroDivisionError division by zero Patterns to avoid Although the preceding sections have described ways of doing things you might need to do or deal with it is worth mentioning some usage patterns which are unhelpful and which should therefore be avoided in most cases The following sections are in no particular order Opening the
en
null
307
same log file multiple times On Windows you will generally not be able to open the same file multiple times as this will lead to a file is in use by another process error However on POSIX platforms you ll not get any errors if you open the same file multiple times This could be done accidentally for example by Adding a file handler more than once which references the same file e g by a copy paste forget to change error Opening two files that look different as they have different names but are the same because one is a symbolic link to the other Forking a process following which both parent and child have a reference to the same file This might be through use of the multiprocessing module for example Opening a file multiple times might appear to work most of the time but can lead to a number of problems in practice Logging output can be garbled because multiple threads or processes try to write to the same file Although logging guards against concurrent use of the same handler instance by multiple threads there is no such protection if concurrent writes are attempted by two different threads using two different handler instances which happen to point to the same file An attempt to delete a file e g during file rotation silently fails because there is another reference pointing to it This can lead to confusion and wasted debugging time log entries end up in unexpected places or are lost altogether Or a file that was supposed to be moved remains in place and grows in size unexpectedly despite size based rotation being supposedly in place Use the techniques outlined in Logging to a single file from multiple processes to circumvent such issues Using loggers as attributes in a class or passing them as parameters While there might be unusual cases where you ll need to do this in general there is no point because loggers are singletons Code can always access a given logger instance by name using logging getLogger name so passing instances around and holding them as instance attributes is pointless Note that in other languages such as Java and C loggers are often static class attributes However this pattern doesn t make sense in Python where the module and not the class is the unit of software decomposition Adding handlers other than NullHandler to a logger in a library Configuring logging by adding handlers formatters and filters is the responsibility of the application developer not the library developer If you are maintaining a library ensure that you don t add handlers to any of your loggers other than a NullHandler instance Creating a lot of loggers Loggers are singletons that are never freed during a script execution and so creating lots of loggers will use up memory which can t then be freed Rather than create a logger per e g file processed or network connection made use the existing mechanisms for passing contextual information into your logs and restrict the loggers created to those describing areas within your application generally modules but occasionally slightly more fine grained than that Other resources See also Module logging API reference for the logging module Module logging config Configuration API for the logging module Module logging handlers Useful handlers included with the logging module Basic Tutorial Advanced Tutorial
en
null
308
pyclbr Python module browser support Source code Lib pyclbr py The pyclbr module provides limited information about the functions classes and methods defined in a Python coded module The information is sufficient to implement a module browser The information is extracted from the Python source code rather than by importing the module so this module is safe to use with untrusted code This restriction makes it impossible to use this module with modules not implemented in Python including all standard and optional extension modules pyclbr readmodule module path None Return a dictionary mapping module level class names to class descriptors If possible descriptors for imported base classes are included Parameter module is a string with the name of the module to read it may be the name of a module within a package If given path is a sequence of directory paths prepended to sys path which is used to locate the module source code This function is the original interface and is only kept for back compatibility It returns a filtered version of the following pyclbr readmodule_ex module path None Return a dictionary based tree containing a function or class descriptors for each function and class defined in the module with a def or class statement The returned dictionary maps module level function and class names to their descriptors Nested objects are entered into the children dictionary of their parent As with readmodule module names the module to be read and path is prepended to sys path If the module being read is a package the returned dictionary has a key __path__ whose value is a list containing the package search path New in version 3 7 Descriptors for nested definitions They are accessed through the new children attribute Each has a new parent attribute The descriptors returned by these functions are instances of Function and Class classes Users are not expected to create instances of these classes Function Objects class pyclbr Function Class Function instances describe functions defined by def statements They have the following attributes file Name of the file in which the function is defined module The name of the module defining the function described name The name of the function lineno The line number in the file where the definition starts parent For top level functions None For nested functions the parent New in version 3 7 children A dictionary mapping names to descriptors for nested functions and classes New in version 3 7 is_async True for functions that are defined with the async prefix False otherwise New in version 3 10 Class Objects class pyclbr Class Class Class instances describe classes defined by class statements They have the same attributes as Functions and two more file Name of the file in which the class is defined module The name of the module defining the class described name The name of the class lineno The line number in the file where the definition starts parent For top level classes None For nested classes the parent New in version 3 7 children A dictionary mapping names to descriptors for nested functions and classes New in version 3 7 super A list of Class objects which describe the immediate base classes of the class being described Classes which are named as superclasses but which are not discoverable by readmodule_ex are listed as a string with the class name instead of as Class objects methods A dictionary mapping method names to line numbers This can be derived from the newer children dictionary but remains for back compatibility
en
null
309
Bytes Objects These functions raise TypeError when expecting a bytes parameter and called with a non bytes parameter type PyBytesObject This subtype of PyObject represents a Python bytes object PyTypeObject PyBytes_Type Part of the Stable ABI This instance of PyTypeObject represents the Python bytes type it is the same object as bytes in the Python layer int PyBytes_Check PyObject o Return true if the object o is a bytes object or an instance of a subtype of the bytes type This function always succeeds int PyBytes_CheckExact PyObject o Return true if the object o is a bytes object but not an instance of a subtype of the bytes type This function always succeeds PyObject PyBytes_FromString const char v Return value New reference Part of the Stable ABI Return a new bytes object with a copy of the string v as value on success and NULL on failure The parameter v must not be NULL it will not be checked PyObject PyBytes_FromStringAndSize const char v Py_ssize_t len Return value New reference Part of the Stable ABI Return a new bytes object with a copy of the string v as value and length len on success and NULL on failure If v is NULL the contents of the bytes object are uninitialized PyObject PyBytes_FromFormat const char format Return value New reference Part of the Stable ABI Take a C printf style format string and a variable number of arguments calculate the size of the resulting Python bytes object and return a bytes object with the values formatted into it The variable arguments must be C types and must correspond exactly to the format characters in the format string The following format characters are allowed Format Characters Type Comment n a The literal character c int A single byte represented as a C int d int Equivalent to printf d 1 u unsigned int Equivalent to printf u 1 ld long Equivalent to printf ld 1 lu unsigned long Equivalent to printf lu 1 zd Py_ssize_t Equivalent to printf zd 1 zu size_t Equivalent to printf zu 1 i int Equivalent to printf i 1 x int Equivalent to printf x 1 s const char A null terminated C character array p const void The hex representation of a C pointer Mostly equivalent to printf p except that it is guaranteed to start with the literal 0x regardless of what the platform s printf yields An unrecognized format character causes all the rest of the format string to be copied as is to the result object and any extra arguments discarded 1 For integer specifiers d u ld lu zd zu i x the 0 conversion flag has effect even when a precision is given PyObject PyBytes_FromFormatV const char format va_list vargs Return value New reference Part of the Stable ABI Identical to PyBytes_FromFormat except that it takes exactly two arguments PyObject PyBytes_FromObject PyObject o Return value New reference Part of the Stable ABI Return the bytes representation of object o that implements the buffer protocol Py_ssize_t PyBytes_Size PyObject o Part of the Stable ABI Return the length of the bytes in bytes object o Py_ssize_t PyBytes_GET_SIZE PyObject o Similar to PyBytes_Size but without error checking char PyBytes_AsString PyObject o Part of the Stable ABI Return a pointer to the contents of o The pointer refers to the internal buffer of o which consists of len o 1 bytes The last byte in the buffer is always null regardless of whether there are any other null bytes The data must not be modified in any way unless the object was just created using PyBytes_FromStringAndSize NULL size It must not be deallocated If o is not a bytes object at all PyBytes_AsString returns NULL and raises TypeError char PyBytes_AS_STRING PyObject string Similar to PyBytes_AsString but without error checking int PyBytes_AsStringAndSize PyObject obj char buffer Py_ssize_t length Part of the Stable ABI Return the null terminated contents of the object obj through the output variables buffer and length Returns 0 on success If length is NULL the bytes object may not contain embedded null bytes if it does the function returns 1 and a ValueError is raised The buffer refers to an internal buffer of obj which includes an additional null byte at
en
null
310
the end not counted in length The data must not be modified in any way unless the object was just created using PyBytes_FromStringAndSize NULL size It must not be deallocated If obj is not a bytes object at all PyBytes_AsStringAndSize returns 1 and raises TypeError Changed in version 3 5 Previously TypeError was raised when embedded null bytes were encountered in the bytes object void PyBytes_Concat PyObject bytes PyObject newpart Part of the Stable ABI Create a new bytes object in bytes containing the contents of newpart appended to bytes the caller will own the new reference The reference to the old value of bytes will be stolen If the new object cannot be created the old reference to bytes will still be discarded and the value of bytes will be set to NULL the appropriate exception will be set void PyBytes_ConcatAndDel PyObject bytes PyObject newpart Part of the Stable ABI Create a new bytes object in bytes containing the contents of newpart appended to bytes This version releases the strong reference to newpart i e decrements its reference count int _PyBytes_Resize PyObject bytes Py_ssize_t newsize A way to resize a bytes object even though it is immutable Only use this to build up a brand new bytes object don t use this if the bytes may already be known in other parts of the code It is an error to call this function if the refcount on the input bytes object is not one Pass the address of an existing bytes object as an lvalue it may be written into and the new size desired On success bytes holds the resized bytes object and 0 is returned the address in bytes may differ from its input value If the reallocation fails the original bytes object at bytes is deallocated bytes is set to NULL MemoryError is set and 1 is returned
en
null
311
3 An Informal Introduction to Python In the following examples input and output are distinguished by the presence or absence of prompts and to repeat the example you must type everything after the prompt when the prompt appears lines that do not begin with a prompt are output from the interpreter Note that a secondary prompt on a line by itself in an example means you must type a blank line this is used to end a multi line command Many of the examples in this manual even those entered at the interactive prompt include comments Comments in Python start with the hash character and extend to the end of the physical line A comment may appear at the start of a line or following whitespace or code but not within a string literal A hash character within a string literal is just a hash character Since comments are to clarify code and are not interpreted by Python they may be omitted when typing in examples Some examples this is the first comment spam 1 and this is the second comment and now a third text This is not a comment because it s inside quotes 3 1 Using Python as a Calculator Let s try some simple Python commands Start the interpreter and wait for the primary prompt It shouldn t take long 3 1 1 Numbers The interpreter acts as a simple calculator you can type an expression at it and it will write the value Expression syntax is straightforward the operators and can be used to perform arithmetic parentheses can be used for grouping For example 2 2 4 50 5 6 20 50 5 6 4 5 0 8 5 division always returns a floating point number 1 6 The integer numbers e g 2 4 20 have type int the ones with a fractional part e g 5 0 1 6 have type float We will see more about numeric types later in the tutorial Division always returns a float To do floor division and get an integer result you can use the operator to calculate the remainder you can use 17 3 classic division returns a float 5 666666666666667 17 3 floor division discards the fractional part 5 17 3 the operator returns the remainder of the division 2 5 3 2 floored quotient divisor remainder 17 With Python it is possible to use the operator to calculate powers 1 5 2 5 squared 25 2 7 2 to the power of 7 128 The equal sign is used to assign a value to a variable Afterwards no result is displayed before the next interactive prompt width 20 height 5 9 width height 900 If a variable is not defined assigned a value trying to use it will give you an error n try to access an undefined variable Traceback most recent call last File stdin line 1 in module NameError name n is not defined There is full support for floating point operators with mixed type operands convert the integer operand to floating point 4 3 75 1 14 0 In interactive mode the last printed expression is assigned to the variable _ This means that when you are using Python as a desk calculator it is somewhat easier to continue calculations for example tax 12 5 100 price 100 50 price tax 12 5625 price _ 113 0625 round _ 2 113 06 This variable should be treated as read only by the user Don t explicitly assign a value to it you would create an independent local variable with the same name masking the built in variable with its magic behavior In addition to int and float Python supports other types of numbers such as Decimal and Fraction Python also has built in support for complex numbers and uses the j or J suffix to indicate the imaginary part e g 3 5j 3 1 2 Text Python can manipulate text represented by type str so called strings as well as numbers This includes characters words rabbit names Paris sentences Got your back etc Yay They can be enclosed in single quotes or double quotes with the same result 2 spam eggs single quotes spam eggs Paris rabbit got your back Yay double quotes Paris rabbit got your back Yay 1975 digits and numerals enclosed in quotes are also strings 1975 To quote a quote we need to escape it by preceding it with Alternatively we can use the other type of quotation marks doesn t use to escape the single quote doesn t doesn t or use double quotes instead doesn t Yes they said Yes they said Yes they said Yes th
en
null
312
ey said Isn t they said Isn t they said In the Python shell the string definition and output string can look different The print function produces a more readable output by omitting the enclosing quotes and by printing escaped and special characters s First line nSecond line n means newline s without print special characters are included in the string First line nSecond line print s with print special characters are interpreted so n produces new line First line Second line If you don t want characters prefaced by to be interpreted as special characters you can use raw strings by adding an r before the first quote print C some name here n means newline C some ame print r C some name note the r before the quote C some name There is one subtle aspect to raw strings a raw string may not end in an odd number of characters see the FAQ entry for more information and workarounds String literals can span multiple lines One way is using triple quotes or End of lines are automatically included in the string but it s possible to prevent this by adding a at the end of the line The following example print Usage thingy OPTIONS h Display this usage message H hostname Hostname to connect to produces the following output note that the initial newline is not included Usage thingy OPTIONS h Display this usage message H hostname Hostname to connect to Strings can be concatenated glued together with the operator and repeated with 3 times un followed by ium 3 un ium unununium Two or more string literals i e the ones enclosed between quotes next to each other are automatically concatenated Py thon Python This feature is particularly useful when you want to break long strings text Put several strings within parentheses to have them joined together text Put several strings within parentheses to have them joined together This only works with two literals though not with variables or expressions prefix Py prefix thon can t concatenate a variable and a string literal File stdin line 1 prefix thon SyntaxError invalid syntax un 3 ium File stdin line 1 un 3 ium SyntaxError invalid syntax If you want to concatenate variables or a variable and a literal use prefix thon Python Strings can be indexed subscripted with the first character having index 0 There is no separate character type a character is simply a string of size one word Python word 0 character in position 0 P word 5 character in position 5 n Indices may also be negative numbers to start counting from the right word 1 last character n word 2 second last character o word 6 P Note that since 0 is the same as 0 negative indices start from 1 In addition to indexing slicing is also supported While indexing is used to obtain individual characters slicing allows you to obtain a substring word 0 2 characters from position 0 included to 2 excluded Py word 2 5 characters from position 2 included to 5 excluded tho Slice indices have useful defaults an omitted first index defaults to zero an omitted second index defaults to the size of the string being sliced 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 Note how the start is always included and the end always excluded This makes sure that s i s i is always equal to s word 2 word 2 Python word 4 word 4 Python One way to remember how slices work is to think of the indices as pointing between characters with the left edge of the first character numbered 0 Then the right edge of the last character of a string of n characters has index n for example P y t h o n 0 1 2 3 4 5 6 6 5 4 3 2 1 The first row of numbers gives the position of the indices 0 6 in the string the second row gives the corresponding negative indices The slice from i to j consists of all characters between the edges labeled i and j respectively For non negative indices the length of a slice is the difference of the indices if both are within bounds For example the length of word 1 3 is 2 Attempting to use an index that is too large will result in an error word
en
null
313
42 the word only has 6 characters Traceback most recent call last File stdin line 1 in module IndexError string index out of range However out of range slice indexes are handled gracefully when used for slicing word 4 42 on word 42 Python strings cannot be changed they are immutable Therefore assigning to an indexed position in the string results in an error word 0 J Traceback most recent call last File stdin line 1 in module TypeError str object does not support item assignment word 2 py Traceback most recent call last File stdin line 1 in module TypeError str object does not support item assignment If you need a different string you should create a new one J word 1 Jython word 2 py Pypy The built in function len returns the length of a string s supercalifragilisticexpialidocious len s 34 See also Text Sequence Type str Strings are examples of sequence types and support the common operations supported by such types String Methods Strings support a large number of methods for basic transformations and searching f strings String literals that have embedded expressions Format String Syntax Information about string formatting with str format printf style String Formatting The old formatting operations invoked when strings are the left operand of the operator are described in more detail here 3 1 3 Lists Python knows a number of compound data types used to group together other values The most versatile is the list which can be written as a list of comma separated values items between square brackets Lists might contain items of different types but usually the items all have the same type squares 1 4 9 16 25 squares 1 4 9 16 25 Like strings and all other built in sequence types lists can be indexed and sliced squares 0 indexing returns the item 1 squares 1 25 squares 3 slicing returns a new list 9 16 25 Lists also support operations like concatenation squares 36 49 64 81 100 1 4 9 16 25 36 49 64 81 100 Unlike strings which are immutable lists are a mutable type i e it is possible to change their content cubes 1 8 27 65 125 something s wrong here 4 3 the cube of 4 is 64 not 65 64 cubes 3 64 replace the wrong value cubes 1 8 27 64 125 You can also add new items at the end of the list by using the list append method we will see more about methods later cubes append 216 add the cube of 6 cubes append 7 3 and the cube of 7 cubes 1 8 27 64 125 216 343 Simple assignment in Python never copies data When you assign a list to a variable the variable refers to the existing list Any changes you make to the list through one variable will be seen through all other variables that refer to it rgb Red Green Blue rgba rgb id rgb id rgba they reference the same object True rgba append Alph rgb Red Green Blue Alph All slice operations return a new list containing the requested elements This means that the following slice returns a shallow copy of the list correct_rgba rgba correct_rgba 1 Alpha correct_rgba Red Green Blue Alpha rgba Red Green Blue Alph Assignment to slices is also possible and this can even change the size of the list or clear it entirely letters a b c d e f g letters a b c d e f g replace some values letters 2 5 C D E letters a b C D E f g now remove them letters 2 5 letters a b f g clear the list by replacing all the elements with an empty list letters letters The built in function len also applies to lists letters a b c d len letters 4 It is possible to nest lists create lists containing other lists for example a a b c n 1 2 3 x a n x a b c 1 2 3 x 0 a b c x 0 1 b 3 2 First Steps Towards Programming Of course we can use Python for more complicated tasks than adding two and two together For instance we can write an initial sub sequence of the Fibonacci series as follows Fibonacci series the sum of two elements defines the next a b 0 1 while a 10 print a a b b a b 0 1 1 2 3 5 8 This example introduces several new features The first line contains a multiple assignment the variables a and b simultaneously get the new values 0 and 1 On the last line this is used again demonstrating that the expressions on the right hand side are a
en
null
314
ll evaluated first before any of the assignments take place The right hand side expressions are evaluated from the left to the right The while loop executes as long as the condition here a 10 remains true In Python like in C any non zero integer value is true zero is false The condition may also be a string or list value in fact any sequence anything with a non zero length is true empty sequences are false The test used in the example is a simple comparison The standard comparison operators are written the same as in C less than greater than equal to less than or equal to greater than or equal to and not equal to The body of the loop is indented indentation is Python s way of grouping statements At the interactive prompt you have to type a tab or space s for each indented line In practice you will prepare more complicated input for Python with a text editor all decent text editors have an auto indent facility When a compound statement is entered interactively it must be followed by a blank line to indicate completion since the parser cannot guess when you have typed the last line Note that each line within a basic block must be indented by the same amount The print function writes the value of the argument s it is given It differs from just writing the expression you want to write as we did earlier in the calculator examples in the way it handles multiple arguments floating point quantities and strings Strings are printed without quotes and a space is inserted between items so you can format things nicely like this i 256 256 print The value of i is i The value of i is 65536 The keyword argument end can be used to avoid the newline after the output or end the output with a different string a b 0 1 while a 1000 print a end a b b a b 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 Footnotes 1 Since has higher precedence than 3 2 will be interpreted as 3 2 and thus result in 9 To avoid this and get 9 you can use 3 2 2 Unlike other languages special characters such as n have the same meaning with both single and double quotes The only difference between the two is that within single quotes you don t need to escape but you have to escape and vice versa
en
null
315
Subprocesses Source code Lib asyncio subprocess py Lib asyncio base_subprocess py This section describes high level async await asyncio APIs to create and manage subprocesses Here s an example of how asyncio can run a shell command and obtain its result import asyncio async def run cmd proc await asyncio create_subprocess_shell cmd stdout asyncio subprocess PIPE stderr asyncio subprocess PIPE stdout stderr await proc communicate print f cmd r exited with proc returncode if stdout print f stdout n stdout decode if stderr print f stderr n stderr decode asyncio run run ls zzz will print ls zzz exited with 1 stderr ls zzz No such file or directory Because all asyncio subprocess functions are asynchronous and asyncio provides many tools to work with such functions it is easy to execute and monitor multiple subprocesses in parallel It is indeed trivial to modify the above example to run several commands simultaneously async def main await asyncio gather run ls zzz run sleep 1 echo hello asyncio run main See also the Examples subsection Creating Subprocesses coroutine asyncio create_subprocess_exec program args stdin None stdout None stderr None limit None kwds Create a subprocess The limit argument sets the buffer limit for StreamReader wrappers for Process stdout and Process stderr if subprocess PIPE is passed to stdout and stderr arguments Return a Process instance See the documentation of loop subprocess_exec for other parameters Changed in version 3 10 Removed the loop parameter coroutine asyncio create_subprocess_shell cmd stdin None stdout None stderr None limit None kwds Run the cmd shell command The limit argument sets the buffer limit for StreamReader wrappers for Process stdout and Process stderr if subprocess PIPE is passed to stdout and stderr arguments Return a Process instance See the documentation of loop subprocess_shell for other parameters Important It is the application s responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid shell injection vulnerabilities The shlex quote function can be used to properly escape whitespace and special shell characters in strings that are going to be used to construct shell commands Changed in version 3 10 Removed the loop parameter Note Subprocesses are available for Windows if a ProactorEventLoop is used See Subprocess Support on Windows for details See also asyncio also has the following low level APIs to work with subprocesses loop subprocess_exec loop subprocess_shell loop connect_read_pipe loop connect_write_pipe as well as the Subprocess Transports and Subprocess Protocols Constants asyncio subprocess PIPE Can be passed to the stdin stdout or stderr parameters If PIPE is passed to stdin argument the Process stdin attribute will point to a StreamWriter instance If PIPE is passed to stdout or stderr arguments the Process stdout and Process stderr attributes will point to StreamReader instances asyncio subprocess STDOUT Special value that can be used as the stderr argument and indicates that standard error should be redirected into standard output asyncio subprocess DEVNULL Special value that can be used as the stdin stdout or stderr argument to process creation functions It indicates that the special file os devnull will be used for the corresponding subprocess stream Interacting with Subprocesses Both create_subprocess_exec and create_subprocess_shell functions return instances of the Process class Process is a high level wrapper that allows communicating with subprocesses and watching for their completion class asyncio subprocess Process An object that wraps OS processes created by the create_subprocess_exec and create_subprocess_shell functions This class is designed to have a similar API to the subprocess Popen class but there are some notable differences unlike Popen Process instances do not have an equivalent to the poll method the communicate and wait methods don t have a timeout parameter use the wait_for function the Process wait method is asynchronous whereas subprocess Popen wait method is implemented as a blockin
en
null
316
g busy loop the universal_newlines parameter is not supported This class is not thread safe See also the Subprocess and Threads section coroutine wait Wait for the child process to terminate Set and return the returncode attribute Note This method can deadlock when using stdout PIPE or stderr PIPE and the child process generates so much output that it blocks waiting for the OS pipe buffer to accept more data Use the communicate method when using pipes to avoid this condition coroutine communicate input None Interact with process 1 send data to stdin if input is not None 2 closes stdin 3 read data from stdout and stderr until EOF is reached 4 wait for process to terminate The optional input argument is the data bytes object that will be sent to the child process Return a tuple stdout_data stderr_data If either BrokenPipeError or ConnectionResetError exception is raised when writing input into stdin the exception is ignored This condition occurs when the process exits before all data are written into stdin If it is desired to send data to the process stdin the process needs to be created with stdin PIPE Similarly to get anything other than None in the result tuple the process has to be created with stdout PIPE and or stderr PIPE arguments Note that the data read is buffered in memory so do not use this method if the data size is large or unlimited Changed in version 3 12 stdin gets closed when input None too send_signal signal Sends the signal signal to the child process Note On Windows SIGTERM is an alias for terminate CTRL_C_EVENT and CTRL_BREAK_EVENT can be sent to processes started with a creationflags parameter which includes CREATE_NEW_PROCESS_GROUP terminate Stop the child process On POSIX systems this method sends SIGTERM to the child process On Windows the Win32 API function TerminateProcess is called to stop the child process kill Kill the child process On POSIX systems this method sends SIGKILL to the child process On Windows this method is an alias for terminate stdin Standard input stream StreamWriter or None if the process was created with stdin None stdout Standard output stream StreamReader or None if the process was created with stdout None stderr Standard error stream StreamReader or None if the process was created with stderr None Warning Use the communicate method rather than process stdin write await process stdout read or await process stderr read This avoids deadlocks due to streams pausing reading or writing and blocking the child process pid Process identification number PID Note that for processes created by the create_subprocess_shell function this attribute is the PID of the spawned shell returncode Return code of the process when it exits A None value indicates that the process has not terminated yet A negative value N indicates that the child was terminated by signal N POSIX only Subprocess and Threads Standard asyncio event loop supports running subprocesses from different threads by default On Windows subprocesses are provided by ProactorEventLoop only default SelectorEventLoop has no subprocess support On UNIX child watchers are used for subprocess finish waiting see Process Watchers for more info Changed in version 3 8 UNIX switched to use ThreadedChildWatcher for spawning subprocesses from different threads without any limitation Spawning a subprocess with inactive current child watcher raises RuntimeError Note that alternative event loop implementations might have own limitations please refer to their documentation See also The Concurrency and multithreading in asyncio section Examples An example using the Process class to control a subprocess and the StreamReader class to read from its standard output The subprocess is created by the create_subprocess_exec function import asyncio import sys async def get_date code import datetime print datetime datetime now Create the subprocess redirect the standard output into a pipe proc await asyncio create_subprocess_exec sys executable c code stdout asyncio subprocess PIPE Read one line of output data await proc stdout readline line data decode as
en
null
317
cii rstrip Wait for the subprocess exit await proc wait return line date asyncio run get_date print f Current date date See also the same example written using low level APIs
en
null
318
chunk Read IFF chunked data Source code Lib chunk py Deprecated since version 3 11 will be removed in version 3 13 The chunk module is deprecated see PEP 594 for details This module provides an interface for reading files that use EA IFF 85 chunks 1 This format is used in at least the Audio Interchange File Format AIFF AIFF C and the Real Media File Format RMFF The WAVE audio file format is closely related and can also be read using this module A chunk has the following structure Offset Length Contents 0 4 Chunk ID 4 4 Size of chunk in big endian byte order not including the header 8 n Data bytes where n is the size given in the preceding field 8 n 0 or 1 Pad byte needed if n is odd and chunk alignment is used The ID is a 4 byte string which identifies the type of chunk The size field a 32 bit value encoded using big endian byte order gives the size of the chunk data not including the 8 byte header Usually an IFF type file consists of one or more chunks The proposed usage of the Chunk class defined here is to instantiate an instance at the start of each chunk and read from the instance until it reaches the end after which a new instance can be instantiated At the end of the file creating a new instance will fail with an EOFError exception class chunk Chunk file align True bigendian True inclheader False Class which represents a chunk The file argument is expected to be a file like object An instance of this class is specifically allowed The only method that is needed is read If the methods seek and tell are present and don t raise an exception they are also used If these methods are present and raise an exception they are expected to not have altered the object If the optional argument align is true chunks are assumed to be aligned on 2 byte boundaries If align is false no alignment is assumed The default value is true If the optional argument bigendian is false the chunk size is assumed to be in little endian order This is needed for WAVE audio files The default value is true If the optional argument inclheader is true the size given in the chunk header includes the size of the header The default value is false A Chunk object supports the following methods getname Returns the name ID of the chunk This is the first 4 bytes of the chunk getsize Returns the size of the chunk close Close and skip to the end of the chunk This does not close the underlying file The remaining methods will raise OSError if called after the close method has been called Before Python 3 3 they used to raise IOError now an alias of OSError isatty Returns False seek pos whence 0 Set the chunk s current position The whence argument is optional and defaults to 0 absolute file positioning other values are 1 seek relative to the current position and 2 seek relative to the file s end There is no return value If the underlying file does not allow seek only forward seeks are allowed tell Return the current position into the chunk read size 1 Read at most size bytes from the chunk less if the read hits the end of the chunk before obtaining size bytes If the size argument is negative or omitted read all data until the end of the chunk An empty bytes object is returned when the end of the chunk is encountered immediately skip Skip to the end of the chunk All further calls to read for the chunk will return b If you are not interested in the contents of the chunk this method should be called so that the file points to the start of the next chunk Footnotes 1 EA IFF 85 Standard for Interchange Format Files Jerry Morrison Electronic Arts January 1985
en
null
319
ensurepip Bootstrapping the pip installer New in version 3 4 Source code Lib ensurepip The ensurepip package provides support for bootstrapping the pip installer into an existing Python installation or virtual environment This bootstrapping approach reflects the fact that pip is an independent project with its own release cycle and the latest available stable version is bundled with maintenance and feature releases of the CPython reference interpreter In most cases end users of Python shouldn t need to invoke this module directly as pip should be bootstrapped by default but it may be needed if installing pip was skipped when installing Python or when creating a virtual environment or after explicitly uninstalling pip Note This module does not access the internet All of the components needed to bootstrap pip are included as internal parts of the package See also Installing Python Modules The end user guide for installing Python packages PEP 453 Explicit bootstrapping of pip in Python installations The original rationale and specification for this module Availability not Emscripten not WASI This module does not work or is not available on WebAssembly platforms wasm32 emscripten and wasm32 wasi See WebAssembly platforms for more information Command line interface The command line interface is invoked using the interpreter s m switch The simplest possible invocation is python m ensurepip This invocation will install pip if it is not already installed but otherwise does nothing To ensure the installed version of pip is at least as recent as the one available in ensurepip pass the upgrade option python m ensurepip upgrade By default pip is installed into the current virtual environment if one is active or into the system site packages if there is no active virtual environment The installation location can be controlled through two additional command line options root dir Installs pip relative to the given root directory rather than the root of the currently active virtual environment if any or the default root for the current Python installation user Installs pip into the user site packages directory rather than globally for the current Python installation this option is not permitted inside an active virtual environment By default the scripts pipX and pipX Y will be installed where X Y stands for the version of Python used to invoke ensurepip The scripts installed can be controlled through two additional command line options altinstall if an alternate installation is requested the pipX script will not be installed default pip if a default pip installation is requested the pip script will be installed in addition to the two regular scripts Providing both of the script selection options will trigger an exception Module API ensurepip exposes two functions for programmatic use ensurepip version Returns a string specifying the available version of pip that will be installed when bootstrapping an environment ensurepip bootstrap root None upgrade False user False altinstall False default_pip False verbosity 0 Bootstraps pip into the current or designated environment root specifies an alternative root directory to install relative to If root is None then installation uses the default install location for the current environment upgrade indicates whether or not to upgrade an existing installation of an earlier version of pip to the available version user indicates whether to use the user scheme rather than installing globally By default the scripts pipX and pipX Y will be installed where X Y stands for the current version of Python If altinstall is set then pipX will not be installed If default_pip is set then pip will be installed in addition to the two regular scripts Setting both altinstall and default_pip will trigger ValueError verbosity controls the level of output to sys stdout from the bootstrapping operation Raises an auditing event ensurepip bootstrap with argument root Note The bootstrapping process has side effects on both sys path and os environ Invoking the command line interface in a subprocess instead allows these side
en
null
320
effects to be avoided Note The bootstrapping process may install additional modules required by pip but other software should not assume those dependencies will always be present by default as the dependencies may be removed in a future version of pip
en
null
321
posix The most common POSIX system calls This module provides access to operating system functionality that is standardized by the C Standard and the POSIX standard a thinly disguised Unix interface Availability Unix Do not import this module directly Instead import the module os which provides a portable version of this interface On Unix the os module provides a superset of the posix interface On non Unix operating systems the posix module is not available but a subset is always available through the os interface Once os is imported there is no performance penalty in using it instead of posix In addition os provides some additional functionality such as automatically calling putenv when an entry in os environ is changed Errors are reported as exceptions the usual exceptions are given for type errors while errors reported by the system calls raise OSError Large File Support Several operating systems including AIX and Solaris provide support for files that are larger than 2 GiB from a C programming model where int and long are 32 bit values This is typically accomplished by defining the relevant size and offset types as 64 bit values Such files are sometimes referred to as large files Large file support is enabled in Python when the size of an off_t is larger than a long and the long long is at least as large as an off_t It may be necessary to configure and compile Python with certain compiler flags to enable this mode For example with Solaris 2 6 and 2 7 you need to do something like CFLAGS getconf LFS_CFLAGS OPT g O2 CFLAGS configure On large file capable Linux systems this might work CFLAGS D_LARGEFILE64_SOURCE D_FILE_OFFSET_BITS 64 OPT g O2 CFLAGS configure Notable Module Contents In addition to many functions described in the os module documentation posix defines the following data item posix environ A dictionary representing the string environment at the time the interpreter was started Keys and values are bytes on Unix and str on Windows For example environ b HOME environ HOME on Windows is the pathname of your home directory equivalent to getenv HOME in C Modifying this dictionary does not affect the string environment passed on by execv popen or system if you need to change the environment pass environ to execve or add variable assignments and export statements to the command string for system or popen Changed in version 3 2 On Unix keys and values are bytes Note The os module provides an alternate implementation of environ which updates the environment on modification Note also that updating os environ will render this dictionary obsolete Use of the os module version of this is recommended over direct access to the posix module
en
null
322
5 Using Python on a Mac Author Bob Savage bobsavage mac com Python on a Mac running macOS is in principle very similar to Python on any other Unix platform but there are a number of additional features such as the integrated development environment IDE and the Package Manager that are worth pointing out 5 1 Getting and Installing Python macOS used to come with Python 2 7 pre installed between versions 10 8 and 12 3 You are invited to install the most recent version of Python 3 from the Python website A current universal2 binary build of Python which runs natively on the Mac s new Apple Silicon and legacy Intel processors is available there What you get after installing is a number of things A Python 3 12 folder in your Applications folder In here you find IDLE the development environment that is a standard part of official Python distributions and Python Launcher which handles double clicking Python scripts from the Finder A framework Library Frameworks Python framework which includes the Python executable and libraries The installer adds this location to your shell path To uninstall Python you can remove these three things A symlink to the Python executable is placed in usr local bin Note On macOS 10 8 12 3 the Apple provided build of Python is installed in System Library Frameworks Python framework and usr bin python respectively You should never modify or delete these as they are Apple controlled and are used by Apple or third party software Remember that if you choose to install a newer Python version from python org you will have two different but functional Python installations on your computer so it will be important that your paths and usages are consistent with what you want to do IDLE includes a Help menu that allows you to access Python documentation If you are completely new to Python you should start reading the tutorial introduction in that document If you are familiar with Python on other Unix platforms you should read the section on running Python scripts from the Unix shell 5 1 1 How to run a Python script Your best way to get started with Python on macOS is through the IDLE integrated development environment see section The IDE and use the Help menu when the IDE is running If you want to run Python scripts from the Terminal window command line or from the Finder you first need an editor to create your script macOS comes with a number of standard Unix command line editors vim nano among them If you want a more Mac like editor BBEdit from Bare Bones Software see https www barebones com products bbedit index html are good choices as is TextMate see https macromates com Other editors include MacVim https macvim org and Aquamacs https aquamacs org To run your script from the Terminal window you must make sure that usr local bin is in your shell search path To run your script from the Finder you have two options Drag it to Python Launcher Select Python Launcher as the default application to open your script or any py script through the finder Info window and double click it Python Launcher has various preferences to control how your script is launched Option dragging allows you to change these for one invocation or use its Preferences menu to change things globally 5 1 2 Running scripts with a GUI With older versions of Python there is one macOS quirk that you need to be aware of programs that talk to the Aqua window manager in other words anything that has a GUI need to be run in a special way Use pythonw instead of python to start such scripts With Python 3 9 you can use either python or pythonw 5 1 3 Configuration Python on macOS honors all standard Unix environment variables such as PYTHONPATH but setting these variables for programs started from the Finder is non standard as the Finder does not read your profile or cshrc at startup You need to create a file MacOSX environment plist See Apple s Technical Q A QA1067 for details For more information on installation Python packages see section Installing Additional Python Packages 5 2 The IDE Python ships with the standard IDLE development environment A good
en
null
323
introduction to using IDLE can be found at https www hashcollision org hkn python idle_intro index html 5 3 Installing Additional Python Packages This section has moved to the Python Packaging User Guide 5 4 GUI Programming There are several options for building GUI applications on the Mac with Python PyObjC is a Python binding to Apple s Objective C Cocoa framework which is the foundation of most modern Mac development Information on PyObjC is available from https pypi org project pyobjc The standard Python GUI toolkit is tkinter based on the cross platform Tk toolkit https www tcl tk An Aqua native version of Tk is bundled with macOS by Apple and the latest version can be downloaded and installed from https www activestate com it can also be built from source wxPython is another popular cross platform GUI toolkit that runs natively on macOS Packages and documentation are available from https www wxpython org PyQt is another popular cross platform GUI toolkit that runs natively on macOS More information can be found at https riverbankcomputing com software pyqt intro PySide is another cross platform Qt based toolkit More information at https www qt io qt for python 5 5 Distributing Python Applications The standard tool for deploying standalone Python applications on the Mac is py2app More information on installing and using py2app can be found at https pypi org project py2app 5 6 Other Resources The Pythonmac SIG mailing list is an excellent support resource for Python users and developers on the Mac https www python org community sigs current pythonmac sig Another useful resource is the MacPython wiki https wiki python org moin MacPython
en
null
324
curses Terminal handling for character cell displays Source code Lib curses The curses module provides an interface to the curses library the de facto standard for portable advanced terminal handling While curses is most widely used in the Unix environment versions are available for Windows DOS and possibly other systems as well This extension module is designed to match the API of ncurses an open source curses library hosted on Linux and the BSD variants of Unix Note Whenever the documentation mentions a character it can be specified as an integer a one character Unicode string or a one byte byte string Whenever the documentation mentions a character string it can be specified as a Unicode string or a byte string See also Module curses ascii Utilities for working with ASCII characters regardless of your locale settings Module curses panel A panel stack extension that adds depth to curses windows Module curses textpad Editable text widget for curses supporting Emacs like bindings Curses Programming with Python Tutorial material on using curses with Python by Andrew Kuchling and Eric Raymond Functions The module curses defines the following exception exception curses error Exception raised when a curses library function returns an error Note Whenever x or y arguments to a function or a method are optional they default to the current cursor location Whenever attr is optional it defaults to A_NORMAL The module curses defines the following functions curses baudrate Return the output speed of the terminal in bits per second On software terminal emulators it will have a fixed high value Included for historical reasons in former times it was used to write output loops for time delays and occasionally to change interfaces depending on the line speed curses beep Emit a short attention sound curses can_change_color Return True or False depending on whether the programmer can change the colors displayed by the terminal curses cbreak Enter cbreak mode In cbreak mode sometimes called rare mode normal tty line buffering is turned off and characters are available to be read one by one However unlike raw mode special characters interrupt quit suspend and flow control retain their effects on the tty driver and calling program Calling first raw then cbreak leaves the terminal in cbreak mode curses color_content color_number Return the intensity of the red green and blue RGB components in the color color_number which must be between 0 and COLORS 1 Return a 3 tuple containing the R G B values for the given color which will be between 0 no component and 1000 maximum amount of component curses color_pair pair_number Return the attribute value for displaying text in the specified color pair Only the first 256 color pairs are supported This attribute value can be combined with A_STANDOUT A_REVERSE and the other A_ attributes pair_number is the counterpart to this function curses curs_set visibility Set the cursor state visibility can be set to 0 1 or 2 for invisible normal or very visible If the terminal supports the visibility requested return the previous cursor state otherwise raise an exception On many terminals the visible mode is an underline cursor and the very visible mode is a block cursor curses def_prog_mode Save the current terminal mode as the program mode the mode when the running program is using curses Its counterpart is the shell mode for when the program is not in curses Subsequent calls to reset_prog_mode will restore this mode curses def_shell_mode Save the current terminal mode as the shell mode the mode when the running program is not using curses Its counterpart is the program mode when the program is using curses capabilities Subsequent calls to reset_shell_mode will restore this mode curses delay_output ms Insert an ms millisecond pause in output curses doupdate Update the physical screen The curses library keeps two data structures one representing the current physical screen contents and a virtual screen representing the desired next state The doupdate ground updates the physical screen to match the virtual screen The
en
null
325
virtual screen may be updated by a noutrefresh call after write operations such as addstr have been performed on a window The normal refresh call is simply noutrefresh followed by doupdate if you have to update multiple windows you can speed performance and perhaps reduce screen flicker by issuing noutrefresh calls on all windows followed by a single doupdate curses echo Enter echo mode In echo mode each character input is echoed to the screen as it is entered curses endwin De initialize the library and return terminal to normal status curses erasechar Return the user s current erase character as a one byte bytes object Under Unix operating systems this is a property of the controlling tty of the curses program and is not set by the curses library itself curses filter The filter routine if used must be called before initscr is called The effect is that during those calls LINES is set to 1 the capabilities clear cup cud cud1 cuu1 cuu vpa are disabled and the home string is set to the value of cr The effect is that the cursor is confined to the current line and so are screen updates This may be used for enabling character at a time line editing without touching the rest of the screen curses flash Flash the screen That is change it to reverse video and then change it back in a short interval Some people prefer such as visible bell to the audible attention signal produced by beep curses flushinp Flush all input buffers This throws away any typeahead that has been typed by the user and has not yet been processed by the program curses getmouse After getch returns KEY_MOUSE to signal a mouse event this method should be called to retrieve the queued mouse event represented as a 5 tuple id x y z bstate id is an ID value used to distinguish multiple devices and x y z are the event s coordinates z is currently unused bstate is an integer value whose bits will be set to indicate the type of event and will be the bitwise OR of one or more of the following constants where n is the button number from 1 to 5 BUTTONn_PRESSED BUTTONn_RELEASED BUTTONn_CLICKED BUTTONn_DOUBLE_CLICKED BUTTONn_TRIPLE_CLICKED BUTTON_SHIFT BUTTON_CTRL BUTTON_ALT Changed in version 3 10 The BUTTON5_ constants are now exposed if they are provided by the underlying curses library curses getsyx Return the current coordinates of the virtual screen cursor as a tuple y x If leaveok is currently True then return 1 1 curses getwin file Read window related data stored in the file by an earlier window putwin call The routine then creates and initializes a new window using that data returning the new window object curses has_colors Return True if the terminal can display colors otherwise return False curses has_extended_color_support Return True if the module supports extended colors otherwise return False Extended color support allows more than 256 color pairs for terminals that support more than 16 colors e g xterm 256color Extended color support requires ncurses version 6 1 or later New in version 3 10 curses has_ic Return True if the terminal has insert and delete character capabilities This function is included for historical reasons only as all modern software terminal emulators have such capabilities curses has_il Return True if the terminal has insert and delete line capabilities or can simulate them using scrolling regions This function is included for historical reasons only as all modern software terminal emulators have such capabilities curses has_key ch Take a key value ch and return True if the current terminal type recognizes a key with that value curses halfdelay tenths Used for half delay mode which is similar to cbreak mode in that characters typed by the user are immediately available to the program However after blocking for tenths tenths of seconds raise an exception if nothing has been typed The value of tenths must be a number between 1 and 255 Use nocbreak to leave half delay mode curses init_color color_number r g b Change the definition of a color taking the number of the color to be changed followed by three RGB values for the amounts of red gree
en
null
326
n and blue components The value of color_number must be between 0 and COLORS 1 Each of r g b must be a value between 0 and 1000 When init_color is used all occurrences of that color on the screen immediately change to the new definition This function is a no op on most terminals it is active only if can_change_color returns True curses init_pair pair_number fg bg Change the definition of a color pair It takes three arguments the number of the color pair to be changed the foreground color number and the background color number The value of pair_number must be between 1 and COLOR_PAIRS 1 the 0 color pair is wired to white on black and cannot be changed The value of fg and bg arguments must be between 0 and COLORS 1 or after calling use_default_colors 1 If the color pair was previously initialized the screen is refreshed and all occurrences of that color pair are changed to the new definition curses initscr Initialize the library Return a window object which represents the whole screen Note If there is an error opening the terminal the underlying curses library may cause the interpreter to exit curses is_term_resized nlines ncols Return True if resize_term would modify the window structure False otherwise curses isendwin Return True if endwin has been called that is the curses library has been deinitialized curses keyname k Return the name of the key numbered k as a bytes object The name of a key generating printable ASCII character is the key s character The name of a control key combination is a two byte bytes object consisting of a caret b followed by the corresponding printable ASCII character The name of an alt key combination 128 255 is a bytes object consisting of the prefix b M followed by the name of the corresponding ASCII character curses killchar Return the user s current line kill character as a one byte bytes object Under Unix operating systems this is a property of the controlling tty of the curses program and is not set by the curses library itself curses longname Return a bytes object containing the terminfo long name field describing the current terminal The maximum length of a verbose description is 128 characters It is defined only after the call to initscr curses meta flag If flag is True allow 8 bit characters to be input If flag is False allow only 7 bit chars curses mouseinterval interval Set the maximum time in milliseconds that can elapse between press and release events in order for them to be recognized as a click and return the previous interval value The default value is 200 milliseconds or one fifth of a second curses mousemask mousemask Set the mouse events to be reported and return a tuple availmask oldmask availmask indicates which of the specified mouse events can be reported on complete failure it returns 0 oldmask is the previous value of the given window s mouse event mask If this function is never called no mouse events are ever reported curses napms ms Sleep for ms milliseconds curses newpad nlines ncols Create and return a pointer to a new pad data structure with the given number of lines and columns Return a pad as a window object A pad is like a window except that it is not restricted by the screen size and is not necessarily associated with a particular part of the screen Pads can be used when a large window is needed and only a part of the window will be on the screen at one time Automatic refreshes of pads such as from scrolling or echoing of input do not occur The refresh and noutrefresh methods of a pad require 6 arguments to specify the part of the pad to be displayed and the location on the screen to be used for the display The arguments are pminrow pmincol sminrow smincol smaxrow smaxcol the p arguments refer to the upper left corner of the pad region to be displayed and the s arguments define a clipping box on the screen within which the pad region is to be displayed curses newwin nlines ncols curses newwin nlines ncols begin_y begin_x Return a new window whose left upper corner is at begin_y begin_x and whose height width is nlines ncols By default the window will extend
en
null
327
from the specified position to the lower right corner of the screen curses nl Enter newline mode This mode translates the return key into newline on input and translates newline into return and line feed on output Newline mode is initially on curses nocbreak Leave cbreak mode Return to normal cooked mode with line buffering curses noecho Leave echo mode Echoing of input characters is turned off curses nonl Leave newline mode Disable translation of return into newline on input and disable low level translation of newline into newline return on output but this does not change the behavior of addch n which always does the equivalent of return and line feed on the virtual screen With translation off curses can sometimes speed up vertical motion a little also it will be able to detect the return key on input curses noqiflush When the noqiflush routine is used normal flush of input and output queues associated with the INTR QUIT and SUSP characters will not be done You may want to call noqiflush in a signal handler if you want output to continue as though the interrupt had not occurred after the handler exits curses noraw Leave raw mode Return to normal cooked mode with line buffering curses pair_content pair_number Return a tuple fg bg containing the colors for the requested color pair The value of pair_number must be between 0 and COLOR_PAIRS 1 curses pair_number attr Return the number of the color pair set by the attribute value attr color_pair is the counterpart to this function curses putp str Equivalent to tputs str 1 putchar emit the value of a specified terminfo capability for the current terminal Note that the output of putp always goes to standard output curses qiflush flag If flag is False the effect is the same as calling noqiflush If flag is True or no argument is provided the queues will be flushed when these control characters are read curses raw Enter raw mode In raw mode normal line buffering and processing of interrupt quit suspend and flow control keys are turned off characters are presented to curses input functions one by one curses reset_prog_mode Restore the terminal to program mode as previously saved by def_prog_mode curses reset_shell_mode Restore the terminal to shell mode as previously saved by def_shell_mode curses resetty Restore the state of the terminal modes to what it was at the last call to savetty curses resize_term nlines ncols Backend function used by resizeterm performing most of the work when resizing the windows resize_term blank fills the areas that are extended The calling application should fill in these areas with appropriate data The resize_term function attempts to resize all windows However due to the calling convention of pads it is not possible to resize these without additional interaction with the application curses resizeterm nlines ncols Resize the standard and current windows to the specified dimensions and adjusts other bookkeeping data used by the curses library that record the window dimensions in particular the SIGWINCH handler curses savetty Save the current state of the terminal modes in a buffer usable by resetty curses get_escdelay Retrieves the value set by set_escdelay New in version 3 9 curses set_escdelay ms Sets the number of milliseconds to wait after reading an escape character to distinguish between an individual escape character entered on the keyboard from escape sequences sent by cursor and function keys New in version 3 9 curses get_tabsize Retrieves the value set by set_tabsize New in version 3 9 curses set_tabsize size Sets the number of columns used by the curses library when converting a tab character to spaces as it adds the tab to a window New in version 3 9 curses setsyx y x Set the virtual screen cursor to y x If y and x are both 1 then leaveok is set True curses setupterm term None fd 1 Initialize the terminal term is a string giving the terminal name or None if omitted or None the value of the TERM environment variable will be used fd is the file descriptor to which any initialization sequences will be sent if not supplied or 1 the file descri
en
null
328
ptor for sys stdout will be used curses start_color Must be called if the programmer wants to use colors and before any other color manipulation routine is called It is good practice to call this routine right after initscr start_color initializes eight basic colors black red green yellow blue magenta cyan and white and two global variables in the curses module COLORS and COLOR_PAIRS containing the maximum number of colors and color pairs the terminal can support It also restores the colors on the terminal to the values they had when the terminal was just turned on curses termattrs Return a logical OR of all video attributes supported by the terminal This information is useful when a curses program needs complete control over the appearance of the screen curses termname Return the value of the environment variable TERM as a bytes object truncated to 14 characters curses tigetflag capname Return the value of the Boolean capability corresponding to the terminfo capability name capname as an integer Return the value 1 if capname is not a Boolean capability or 0 if it is canceled or absent from the terminal description curses tigetnum capname Return the value of the numeric capability corresponding to the terminfo capability name capname as an integer Return the value 2 if capname is not a numeric capability or 1 if it is canceled or absent from the terminal description curses tigetstr capname Return the value of the string capability corresponding to the terminfo capability name capname as a bytes object Return None if capname is not a terminfo string capability or is canceled or absent from the terminal description curses tparm str Instantiate the bytes object str with the supplied parameters where str should be a parameterized string obtained from the terminfo database E g tparm tigetstr cup 5 3 could result in b 033 6 4H the exact result depending on terminal type curses typeahead fd Specify that the file descriptor fd be used for typeahead checking If fd is 1 then no typeahead checking is done The curses library does line breakout optimization by looking for typeahead periodically while updating the screen If input is found and it is coming from a tty the current update is postponed until refresh or doupdate is called again allowing faster response to commands typed in advance This function allows specifying a different file descriptor for typeahead checking curses unctrl ch Return a bytes object which is a printable representation of the character ch Control characters are represented as a caret followed by the character for example as b C Printing characters are left as they are curses ungetch ch Push ch so the next getch will return it Note Only one ch can be pushed before getch is called curses update_lines_cols Update the LINES and COLS module variables Useful for detecting manual screen resize New in version 3 5 curses unget_wch ch Push ch so the next get_wch will return it Note Only one ch can be pushed before get_wch is called New in version 3 3 curses ungetmouse id x y z bstate Push a KEY_MOUSE event onto the input queue associating the given state data with it curses use_env flag If used this function should be called before initscr or newterm are called When flag is False the values of lines and columns specified in the terminfo database will be used even if environment variables LINES and COLUMNS used by default are set or if curses is running in a window in which case default behavior would be to use the window size if LINES and COLUMNS are not set curses use_default_colors Allow use of default values for colors on terminals supporting this feature Use this to support transparency in your application The default color is assigned to the color number 1 After calling this function init_pair x curses COLOR_RED 1 initializes for instance color pair x to a red foreground color on the default background curses wrapper func args kwargs Initialize curses and call another callable object func which should be the rest of your curses using application If the application raises an exception this function will restore t
en
null
329
he terminal to a sane state before re raising the exception and generating a traceback The callable object func is then passed the main window stdscr as its first argument followed by any other arguments passed to wrapper Before calling func wrapper turns on cbreak mode turns off echo enables the terminal keypad and initializes colors if the terminal has color support On exit whether normally or by exception it restores cooked mode turns on echo and disables the terminal keypad Window Objects Window objects as returned by initscr and newwin above have the following methods and attributes window addch ch attr window addch y x ch attr Paint character ch at y x with attributes attr overwriting any character previously painted at that location By default the character position and attributes are the current settings for the window object Note Writing outside the window subwindow or pad raises a curses error Attempting to write to the lower right corner of a window subwindow or pad will cause an exception to be raised after the character is printed window addnstr str n attr window addnstr y x str n attr Paint at most n characters of the character string str at y x with attributes attr overwriting anything previously on the display window addstr str attr window addstr y x str attr Paint the character string str at y x with attributes attr overwriting anything previously on the display Note Writing outside the window subwindow or pad raises curses error Attempting to write to the lower right corner of a window subwindow or pad will cause an exception to be raised after the string is printed A bug in ncurses the backend for this Python module can cause SegFaults when resizing windows This is fixed in ncurses 6 1 20190511 If you are stuck with an earlier ncurses you can avoid triggering this if you do not call addstr with a str that has embedded newlines Instead call addstr separately for each line window attroff attr Remove attribute attr from the background set applied to all writes to the current window window attron attr Add attribute attr from the background set applied to all writes to the current window window attrset attr Set the background set of attributes to attr This set is initially 0 no attributes window bkgd ch attr Set the background property of the window to the character ch with attributes attr The change is then applied to every character position in that window The attribute of every character in the window is changed to the new background attribute Wherever the former background character appears it is changed to the new background character window bkgdset ch attr Set the window s background A window s background consists of a character and any combination of attributes The attribute part of the background is combined OR ed with all non blank characters that are written into the window Both the character and attribute parts of the background are combined with the blank characters The background becomes a property of the character and moves with the character through any scrolling and insert delete line character operations window border ls rs ts bs tl tr bl br Draw a border around the edges of the window Each parameter specifies the character to use for a specific part of the border see the table below for more details Note A 0 value for any parameter will cause the default character to be used for that parameter Keyword parameters can not be used The defaults are listed in this table Parameter Description Default value ls Left side ACS_VLINE rs Right side ACS_VLINE ts Top ACS_HLINE bs Bottom ACS_HLINE tl Upper left corner ACS_ULCORNER tr Upper right corner ACS_URCORNER bl Bottom left corner ACS_LLCORNER br Bottom right corner ACS_LRCORNER window box vertch horch Similar to border but both ls and rs are vertch and both ts and bs are horch The default corner characters are always used by this function window chgat attr window chgat num attr window chgat y x attr window chgat y x num attr Set the attributes of num characters at the current cursor position or at position y x if supplied If num is not given or is
en
null
330
1 the attribute will be set on all the characters to the end of the line This function moves cursor to position y x if supplied The changed line will be touched using the touchline method so that the contents will be redisplayed by the next window refresh window clear Like erase but also cause the whole window to be repainted upon next call to refresh window clearok flag If flag is True the next call to refresh will clear the window completely window clrtobot Erase from cursor to the end of the window all lines below the cursor are deleted and then the equivalent of clrtoeol is performed window clrtoeol Erase from cursor to the end of the line window cursyncup Update the current cursor position of all the ancestors of the window to reflect the current cursor position of the window window delch y x Delete any character at y x window deleteln Delete the line under the cursor All following lines are moved up by one line window derwin begin_y begin_x window derwin nlines ncols begin_y begin_x An abbreviation for derive window derwin is the same as calling subwin except that begin_y and begin_x are relative to the origin of the window rather than relative to the entire screen Return a window object for the derived window window echochar ch attr Add character ch with attribute attr and immediately call refresh on the window window enclose y x Test whether the given pair of screen relative character cell coordinates are enclosed by the given window returning True or False It is useful for determining what subset of the screen windows enclose the location of a mouse event Changed in version 3 10 Previously it returned 1 or 0 instead of True or False window encoding Encoding used to encode method arguments Unicode strings and characters The encoding attribute is inherited from the parent window when a subwindow is created for example with window subwin By default current locale encoding is used see locale getencoding New in version 3 3 window erase Clear the window window getbegyx Return a tuple y x of co ordinates of upper left corner window getbkgd Return the given window s current background character attribute pair window getch y x Get a character Note that the integer returned does not have to be in ASCII range function keys keypad keys and so on are represented by numbers higher than 255 In no delay mode return 1 if there is no input otherwise wait until a key is pressed window get_wch y x Get a wide character Return a character for most keys or an integer for function keys keypad keys and other special keys In no delay mode raise an exception if there is no input New in version 3 3 window getkey y x Get a character returning a string instead of an integer as getch does Function keys keypad keys and other special keys return a multibyte string containing the key name In no delay mode raise an exception if there is no input window getmaxyx Return a tuple y x of the height and width of the window window getparyx Return the beginning coordinates of this window relative to its parent window as a tuple y x Return 1 1 if this window has no parent window getstr window getstr n window getstr y x window getstr y x n Read a bytes object from the user with primitive line editing capacity window getyx Return a tuple y x of current cursor position relative to the window s upper left corner window hline ch n window hline y x ch n Display a horizontal line starting at y x with length n consisting of the character ch window idcok flag If flag is False curses no longer considers using the hardware insert delete character feature of the terminal if flag is True use of character insertion and deletion is enabled When curses is first initialized use of character insert delete is enabled by default window idlok flag If flag is True curses will try and use hardware line editing facilities Otherwise line insertion deletion are disabled window immedok flag If flag is True any change in the window image automatically causes the window to be refreshed you no longer have to call refresh yourself However it may degrade performance considerably due to
en
null
331
repeated calls to wrefresh This option is disabled by default window inch y x Return the character at the given position in the window The bottom 8 bits are the character proper and upper bits are the attributes window insch ch attr window insch y x ch attr Paint character ch at y x with attributes attr moving the line from position x right by one character window insdelln nlines Insert nlines lines into the specified window above the current line The nlines bottom lines are lost For negative nlines delete nlines lines starting with the one under the cursor and move the remaining lines up The bottom nlines lines are cleared The current cursor position remains the same window insertln Insert a blank line under the cursor All following lines are moved down by one line window insnstr str n attr window insnstr y x str n attr Insert a character string as many characters as will fit on the line before the character under the cursor up to n characters If n is zero or negative the entire string is inserted All characters to the right of the cursor are shifted right with the rightmost characters on the line being lost The cursor position does not change after moving to y x if specified window insstr str attr window insstr y x str attr Insert a character string as many characters as will fit on the line before the character under the cursor All characters to the right of the cursor are shifted right with the rightmost characters on the line being lost The cursor position does not change after moving to y x if specified window instr n window instr y x n Return a bytes object of characters extracted from the window starting at the current cursor position or at y x if specified Attributes are stripped from the characters If n is specified instr returns a string at most n characters long exclusive of the trailing NUL window is_linetouched line Return True if the specified line was modified since the last call to refresh otherwise return False Raise a curses error exception if line is not valid for the given window window is_wintouched Return True if the specified window was modified since the last call to refresh otherwise return False window keypad flag If flag is True escape sequences generated by some keys keypad function keys will be interpreted by curses If flag is False escape sequences will be left as is in the input stream window leaveok flag If flag is True cursor is left where it is on update instead of being at cursor position This reduces cursor movement where possible If possible the cursor will be made invisible If flag is False cursor will always be at cursor position after an update window move new_y new_x Move cursor to new_y new_x window mvderwin y x Move the window inside its parent window The screen relative parameters of the window are not changed This routine is used to display different parts of the parent window at the same physical position on the screen window mvwin new_y new_x Move the window so its upper left corner is at new_y new_x window nodelay flag If flag is True getch will be non blocking window notimeout flag If flag is True escape sequences will not be timed out If flag is False after a few milliseconds an escape sequence will not be interpreted and will be left in the input stream as is window noutrefresh Mark for refresh but wait This function updates the data structure representing the desired state of the window but does not force an update of the physical screen To accomplish that call doupdate window overlay destwin sminrow smincol dminrow dmincol dmaxrow dmaxcol Overlay the window on top of destwin The windows need not be the same size only the overlapping region is copied This copy is non destructive which means that the current background character does not overwrite the old contents of destwin To get fine grained control over the copied region the second form of overlay can be used sminrow and smincol are the upper left coordinates of the source window and the other variables mark a rectangle in the destination window window overwrite destwin sminrow smincol dminrow dmincol dmaxrow dmaxc
en
null
332
ol Overwrite the window on top of destwin The windows need not be the same size in which case only the overlapping region is copied This copy is destructive which means that the current background character overwrites the old contents of destwin To get fine grained control over the copied region the second form of overwrite can be used sminrow and smincol are the upper left coordinates of the source window the other variables mark a rectangle in the destination window window putwin file Write all data associated with the window into the provided file object This information can be later retrieved using the getwin function window redrawln beg num Indicate that the num screen lines starting at line beg are corrupted and should be completely redrawn on the next refresh call window redrawwin Touch the entire window causing it to be completely redrawn on the next refresh call window refresh pminrow pmincol sminrow smincol smaxrow smaxcol Update the display immediately sync actual screen with previous drawing deleting methods The 6 optional arguments can only be specified when the window is a pad created with newpad The additional parameters are needed to indicate what part of the pad and screen are involved pminrow and pmincol specify the upper left hand corner of the rectangle to be displayed in the pad sminrow smincol smaxrow and smaxcol specify the edges of the rectangle to be displayed on the screen The lower right hand corner of the rectangle to be displayed in the pad is calculated from the screen coordinates since the rectangles must be the same size Both rectangles must be entirely contained within their respective structures Negative values of pminrow pmincol sminrow or smincol are treated as if they were zero window resize nlines ncols Reallocate storage for a curses window to adjust its dimensions to the specified values If either dimension is larger than the current values the window s data is filled with blanks that have the current background rendition as set by bkgdset merged into them window scroll lines 1 Scroll the screen or scrolling region upward by lines lines window scrollok flag Control what happens when the cursor of a window is moved off the edge of the window or scrolling region either as a result of a newline action on the bottom line or typing the last character of the last line If flag is False the cursor is left on the bottom line If flag is True the window is scrolled up one line Note that in order to get the physical scrolling effect on the terminal it is also necessary to call idlok window setscrreg top bottom Set the scrolling region from line top to line bottom All scrolling actions will take place in this region window standend Turn off the standout attribute On some terminals this has the side effect of turning off all attributes window standout Turn on attribute A_STANDOUT window subpad begin_y begin_x window subpad nlines ncols begin_y begin_x Return a sub window whose upper left corner is at begin_y begin_x and whose width height is ncols nlines window subwin begin_y begin_x window subwin nlines ncols begin_y begin_x Return a sub window whose upper left corner is at begin_y begin_x and whose width height is ncols nlines By default the sub window will extend from the specified position to the lower right corner of the window window syncdown Touch each location in the window that has been touched in any of its ancestor windows This routine is called by refresh so it should almost never be necessary to call it manually window syncok flag If flag is True then syncup is called automatically whenever there is a change in the window window syncup Touch all locations in ancestors of the window that have been changed in the window window timeout delay Set blocking or non blocking read behavior for the window If delay is negative blocking read is used which will wait indefinitely for input If delay is zero then non blocking read is used and getch will return 1 if no input is waiting If delay is positive then getch will block for delay milliseconds and return 1 if there is still no input at the en
en
null
333
d of that time window touchline start count changed Pretend count lines have been changed starting with line start If changed is supplied it specifies whether the affected lines are marked as having been changed changed True or unchanged changed False window touchwin Pretend the whole window has been changed for purposes of drawing optimizations window untouchwin Mark all lines in the window as unchanged since the last call to refresh window vline ch n attr window vline y x ch n attr Display a vertical line starting at y x with length n consisting of the character ch with attributes attr Constants The curses module defines the following data members curses ERR Some curses routines that return an integer such as getch return ERR upon failure curses OK Some curses routines that return an integer such as napms return OK upon success curses version curses __version__ A bytes object representing the current version of the module curses ncurses_version A named tuple containing the three components of the ncurses library version major minor and patch All values are integers The components can also be accessed by name so curses ncurses_version 0 is equivalent to curses ncurses_version major and so on Availability if the ncurses library is used New in version 3 8 curses COLORS The maximum number of colors the terminal can support It is defined only after the call to start_color curses COLOR_PAIRS The maximum number of color pairs the terminal can support It is defined only after the call to start_color curses COLS The width of the screen i e the number of columns It is defined only after the call to initscr Updated by update_lines_cols resizeterm and resize_term curses LINES The height of the screen i e the number of lines It is defined only after the call to initscr Updated by update_lines_cols resizeterm and resize_term Some constants are available to specify character cell attributes The exact constants available are system dependent Attribute Meaning curses A_ALTCHARSET Alternate character set mode curses A_BLINK Blink mode curses A_BOLD Bold mode curses A_DIM Dim mode curses A_INVIS Invisible or blank mode curses A_ITALIC Italic mode curses A_NORMAL Normal attribute curses A_PROTECT Protected mode curses A_REVERSE Reverse background and foreground colors curses A_STANDOUT Standout mode curses A_UNDERLINE Underline mode curses A_HORIZONTAL Horizontal highlight curses A_LEFT Left highlight curses A_LOW Low highlight curses A_RIGHT Right highlight curses A_TOP Top highlight curses A_VERTICAL Vertical highlight New in version 3 7 A_ITALIC was added Several constants are available to extract corresponding attributes returned by some methods Bit mask Meaning curses A_ATTRIBUTES Bit mask to extract attributes curses A_CHARTEXT Bit mask to extract a character curses A_COLOR Bit mask to extract color pair field information Keys are referred to by integer constants with names starting with KEY_ The exact keycaps available are system dependent Key constant Key curses KEY_MIN Minimum key value curses KEY_BREAK Break key unreliable curses KEY_DOWN Down arrow curses KEY_UP Up arrow curses KEY_LEFT Left arrow curses KEY_RIGHT Right arrow curses KEY_HOME Home key upward left arrow curses KEY_BACKSPACE Backspace unreliable curses KEY_F0 Function keys Up to 64 function keys are supported curses KEY_Fn Value of function key n curses KEY_DL Delete line curses KEY_IL Insert line curses KEY_DC Delete character curses KEY_IC Insert char or enter insert mode curses KEY_EIC Exit insert char mode curses KEY_CLEAR Clear screen curses KEY_EOS Clear to end of screen curses KEY_EOL Clear to end of line curses KEY_SF Scroll 1 line forward curses KEY_SR Scroll 1 line backward reverse curses KEY_NPAGE Next page curses KEY_PPAGE Previous page curses KEY_STAB Set tab curses KEY_CTAB Clear tab curses KEY_CATAB Clear all tabs curses KEY_ENTER Enter or send unreliable curses KEY_SRESET Soft partial reset unreliable curses KEY_RESET Reset or hard reset unreliable curses KEY_PRINT Print curses KEY_LL Home down or bottom lower left curses KEY_A1 Upper left of keypa
en
null
334
d curses KEY_A3 Upper right of keypad curses KEY_B2 Center of keypad curses KEY_C1 Lower left of keypad curses KEY_C3 Lower right of keypad curses KEY_BTAB Back tab curses KEY_BEG Beg beginning curses KEY_CANCEL Cancel curses KEY_CLOSE Close curses KEY_COMMAND Cmd command curses KEY_COPY Copy curses KEY_CREATE Create curses KEY_END End curses KEY_EXIT Exit curses KEY_FIND Find curses KEY_HELP Help curses KEY_MARK Mark curses KEY_MESSAGE Message curses KEY_MOVE Move curses KEY_NEXT Next curses KEY_OPEN Open curses KEY_OPTIONS Options curses KEY_PREVIOUS Prev previous curses KEY_REDO Redo curses KEY_REFERENCE Ref reference curses KEY_REFRESH Refresh curses KEY_REPLACE Replace curses KEY_RESTART Restart curses KEY_RESUME Resume curses KEY_SAVE Save curses KEY_SBEG Shifted Beg beginning curses KEY_SCANCEL Shifted Cancel curses KEY_SCOMMAND Shifted Command curses KEY_SCOPY Shifted Copy curses KEY_SCREATE Shifted Create curses KEY_SDC Shifted Delete char curses KEY_SDL Shifted Delete line curses KEY_SELECT Select curses KEY_SEND Shifted End curses KEY_SEOL Shifted Clear line curses KEY_SEXIT Shifted Exit curses KEY_SFIND Shifted Find curses KEY_SHELP Shifted Help curses KEY_SHOME Shifted Home curses KEY_SIC Shifted Input curses KEY_SLEFT Shifted Left arrow curses KEY_SMESSAGE Shifted Message curses KEY_SMOVE Shifted Move curses KEY_SNEXT Shifted Next curses KEY_SOPTIONS Shifted Options curses KEY_SPREVIOUS Shifted Prev curses KEY_SPRINT Shifted Print curses KEY_SREDO Shifted Redo curses KEY_SREPLACE Shifted Replace curses KEY_SRIGHT Shifted Right arrow curses KEY_SRSUME Shifted Resume curses KEY_SSAVE Shifted Save curses KEY_SSUSPEND Shifted Suspend curses KEY_SUNDO Shifted Undo curses KEY_SUSPEND Suspend curses KEY_UNDO Undo curses KEY_MOUSE Mouse event has occurred curses KEY_RESIZE Terminal resize event curses KEY_MAX Maximum key value On VT100s and their software emulations such as X terminal emulators there are normally at least four function keys KEY_F1 KEY_F2 KEY_F3 KEY_F4 available and the arrow keys mapped to KEY_UP KEY_DOWN KEY_LEFT and KEY_RIGHT in the obvious way If your machine has a PC keyboard it is safe to expect arrow keys and twelve function keys older PC keyboards may have only ten function keys also the following keypad mappings are standard Keycap Constant Insert KEY_IC Delete KEY_DC Home KEY_HOME End KEY_END Page Up KEY_PPAGE Page Down KEY_NPAGE The following table lists characters from the alternate character set These are inherited from the VT100 terminal and will generally be available on software emulations such as X terminals When there is no graphic available curses falls back on a crude printable ASCII approximation Note These are available only after initscr has been called ACS code Meaning curses ACS_BBSS alternate name for upper right corner curses ACS_BLOCK solid square block curses ACS_BOARD board of squares curses ACS_BSBS alternate name for horizontal line curses ACS_BSSB alternate name for upper left corner curses ACS_BSSS alternate name for top tee curses ACS_BTEE bottom tee curses ACS_BULLET bullet curses ACS_CKBOARD checker board stipple curses ACS_DARROW arrow pointing down curses ACS_DEGREE degree symbol curses ACS_DIAMOND diamond curses ACS_GEQUAL greater than or equal to curses ACS_HLINE horizontal line curses ACS_LANTERN lantern symbol curses ACS_LARROW left arrow curses ACS_LEQUAL less than or equal to curses ACS_LLCORNER lower left hand corner curses ACS_LRCORNER lower right hand corner curses ACS_LTEE left tee curses ACS_NEQUAL not equal sign curses ACS_PI letter pi curses ACS_PLMINUS plus or minus sign curses ACS_PLUS big plus sign curses ACS_RARROW right arrow curses ACS_RTEE right tee curses ACS_S1 scan line 1 curses ACS_S3 scan line 3 curses ACS_S7 scan line 7 curses ACS_S9 scan line 9 curses ACS_SBBS alternate name for lower right corner curses ACS_SBSB alternate name for vertical line curses ACS_SBSS alternate name for right tee curses ACS_SSBB alternate name for lower left corner curses ACS_SSBS alternate name for bottom tee curses ACS_SSSB alternate name for left tee curs
en
null
335
es ACS_SSSS alternate name for crossover or big plus curses ACS_STERLING pound sterling curses ACS_TTEE top tee curses ACS_UARROW up arrow curses ACS_ULCORNER upper left corner curses ACS_URCORNER upper right corner curses ACS_VLINE vertical line The following table lists mouse button constants used by getmouse Mouse button constant Meaning curses BUTTONn_PRESSED Mouse button n pressed curses BUTTONn_RELEASED Mouse button n released curses BUTTONn_CLICKED Mouse button n clicked curses BUTTONn_DOUBLE_CLICKED Mouse button n double clicked curses BUTTONn_TRIPLE_CLICKED Mouse button n triple clicked curses BUTTON_SHIFT Shift was down during button state change curses BUTTON_CTRL Control was down during button state change curses BUTTON_ALT Control was down during button state change Changed in version 3 10 The BUTTON5_ constants are now exposed if they are provided by the underlying curses library The following table lists the predefined colors Constant Color curses COLOR_BLACK Black curses COLOR_BLUE Blue curses COLOR_CYAN Cyan light greenish blue curses COLOR_GREEN Green curses COLOR_MAGENTA Magenta purplish red curses COLOR_RED Red curses COLOR_WHITE White curses COLOR_YELLOW Yellow curses textpad Text input widget for curses programs The curses textpad module provides a Textbox class that handles elementary text editing in a curses window supporting a set of keybindings resembling those of Emacs thus also of Netscape Navigator BBedit 6 x FrameMaker and many other programs The module also provides a rectangle drawing function useful for framing text boxes or for other purposes The module curses textpad defines the following function curses textpad rectangle win uly ulx lry lrx Draw a rectangle The first argument must be a window object the remaining arguments are coordinates relative to that window The second and third arguments are the y and x coordinates of the upper left hand corner of the rectangle to be drawn the fourth and fifth arguments are the y and x coordinates of the lower right hand corner The rectangle will be drawn using VT100 IBM PC forms characters on terminals that make this possible including xterm and most other software terminal emulators Otherwise it will be drawn with ASCII dashes vertical bars and plus signs Textbox objects You can instantiate a Textbox object as follows class curses textpad Textbox win Return a textbox widget object The win argument should be a curses window object in which the textbox is to be contained The edit cursor of the textbox is initially located at the upper left hand corner of the containing window with coordinates 0 0 The instance s stripspaces flag is initially on Textbox objects have the following methods edit validator This is the entry point you will normally use It accepts editing keystrokes until one of the termination keystrokes is entered If validator is supplied it must be a function It will be called for each keystroke entered with the keystroke as a parameter command dispatch is done on the result This method returns the window contents as a string whether blanks in the window are included is affected by the stripspaces attribute do_command ch Process a single command keystroke Here are the supported special keystrokes Keystroke Action Control A Go to left edge of window Control B Cursor left wrapping to previous line if appropriate Control D Delete character under cursor Control E Go to right edge stripspaces off or end of line stripspaces on Control F Cursor right wrapping to next line when appropriate Control G Terminate returning the window contents Control H Delete character backward Control J Terminate if the window is 1 line otherwise insert newline Control K If line is blank delete it otherwise clear to end of line Control L Refresh screen Control N Cursor down move down one line Control O Insert a blank line at cursor location Control P Cursor up move up one line Move operations do nothing if the cursor is at an edge where the movement is not possible The following synonyms are supported where possible Constant Keystroke KEY_LEFT Control B KEY_RIGHT
en
null
336
Control F KEY_UP Control P KEY_DOWN Control N KEY_BACKSPACE Control h All other keystrokes are treated as a command to insert the given character and move right with line wrapping gather Return the window contents as a string whether blanks in the window are included is affected by the stripspaces member stripspaces This attribute is a flag which controls the interpretation of blanks in the window When it is on trailing blanks on each line are ignored any cursor motion that would land the cursor on a trailing blank goes to the end of that line instead and trailing blanks are stripped when the window contents are gathered
en
null
337
inspect Inspect live objects Source code Lib inspect py The inspect module provides several useful functions to help get information about live objects such as modules classes methods functions tracebacks frame objects and code objects For example it can help you examine the contents of a class retrieve the source code of a method extract and format the argument list for a function or get all the information you need to display a detailed traceback There are four main kinds of services provided by this module type checking getting source code inspecting classes and functions and examining the interpreter stack Types and members The getmembers function retrieves the members of an object such as a class or module The functions whose names begin with is are mainly provided as convenient choices for the second argument to getmembers They also help you determine when you can expect to find the following special attributes see Import related module attributes for module attributes Type Attribute Description class __doc__ documentation string __name__ name with which this class was defined __qualname__ qualified name __module__ name of module in which this class was defined method __doc__ documentation string __name__ name with which this method was defined __qualname__ qualified name __func__ function object containing implementation of method __self__ instance to which this method is bound or None __module__ name of module in which this method was defined function __doc__ documentation string __name__ name with which this function was defined __qualname__ qualified name __code__ code object containing compiled function bytecode __defaults__ tuple of any default values for positional or keyword parameters __kwdefaults__ mapping of any default values for keyword only parameters __globals__ global namespace in which this function was defined __builtins__ builtins namespace __annotations__ mapping of parameters names to annotations return key is reserved for return annotations __module__ name of module in which this function was defined traceback tb_frame frame object at this level tb_lasti index of last attempted instruction in bytecode tb_lineno current line number in Python source code tb_next next inner traceback object called by this level frame f_back next outer frame object this frame s caller f_builtins builtins namespace seen by this frame f_code code object being executed in this frame f_globals global namespace seen by this frame f_lasti index of last attempted instruction in bytecode f_lineno current line number in Python source code f_locals local namespace seen by this frame f_trace tracing function for this frame or None code co_argcount number of arguments not including keyword only arguments or args co_code string of raw compiled bytecode co_cellvars tuple of names of cell variables referenced by containing scopes co_consts tuple of constants used in the bytecode co_filename name of file in which this code object was created co_firstlineno number of first line in Python source code co_flags bitmap of CO_ flags read more here co_lnotab encoded mapping of line numbers to bytecode indices co_freevars tuple of names of free variables referenced via a function s closure co_posonlyargcount number of positional only arguments co_kwonlyargcount number of keyword only arguments not including arg co_name name with which this code object was defined co_qualname fully qualified name with which this code object was defined co_names tuple of names other than arguments and function locals co_nlocals number of local variables co_stacksize virtual machine stack space required co_varnames tuple of names of arguments and local variables generator __name__ name __qualname__ qualified name gi_frame frame gi_running is the generator running gi_code code gi_yieldfrom object being iterated by yield from or None coroutine __name__ name __qualname__ qualified name cr_await object being awaited on or None cr_frame frame cr_running is the coroutine running cr_code code cr_origin where coroutine was created or None See s ys set_coroutine_ori
en
null
338
gin_tr acking_depth builtin __doc__ documentation string __name__ original name of this function or method __qualname__ qualified name __self__ instance to which a method is bound or None Changed in version 3 5 Add __qualname__ and gi_yieldfrom attributes to generators The __name__ attribute of generators is now set from the function name instead of the code name and it can now be modified Changed in version 3 7 Add cr_origin attribute to coroutines Changed in version 3 10 Add __builtins__ attribute to functions inspect getmembers object predicate Return all the members of an object in a list of name value pairs sorted by name If the optional predicate argument which will be called with the value object of each member is supplied only members for which the predicate returns a true value are included Note getmembers will only return class attributes defined in the metaclass when the argument is a class and those attributes have been listed in the metaclass custom __dir__ inspect getmembers_static object predicate Return all the members of an object in a list of name value pairs sorted by name without triggering dynamic lookup via the descriptor protocol __getattr__ or __getattribute__ Optionally only return members that satisfy a given predicate Note getmembers_static may not be able to retrieve all members that getmembers can fetch like dynamically created attributes and may find members that getmembers can t like descriptors that raise AttributeError It can also return descriptor objects instead of instance members in some cases New in version 3 11 inspect getmodulename path Return the name of the module named by the file path without including the names of enclosing packages The file extension is checked against all of the entries in importlib machinery all_suffixes If it matches the final path component is returned with the extension removed Otherwise None is returned Note that this function only returns a meaningful name for actual Python modules paths that potentially refer to Python packages will still return None Changed in version 3 3 The function is based directly on importlib inspect ismodule object Return True if the object is a module inspect isclass object Return True if the object is a class whether built in or created in Python code inspect ismethod object Return True if the object is a bound method written in Python inspect isfunction object Return True if the object is a Python function which includes functions created by a lambda expression inspect isgeneratorfunction object Return True if the object is a Python generator function Changed in version 3 8 Functions wrapped in functools partial now return True if the wrapped function is a Python generator function inspect isgenerator object Return True if the object is a generator inspect iscoroutinefunction object Return True if the object is a coroutine function a function defined with an async def syntax a functools partial wrapping a coroutine function or a sync function marked with markcoroutinefunction New in version 3 5 Changed in version 3 8 Functions wrapped in functools partial now return True if the wrapped function is a coroutine function Changed in version 3 12 Sync functions marked with markcoroutinefunction now return True inspect markcoroutinefunction func Decorator to mark a callable as a coroutine function if it would not otherwise be detected by iscoroutinefunction This may be of use for sync functions that return a coroutine if the function is passed to an API that requires iscoroutinefunction When possible using an async def function is preferred Also acceptable is calling the function and testing the return with iscoroutine New in version 3 12 inspect iscoroutine object Return True if the object is a coroutine created by an async def function New in version 3 5 inspect isawaitable object Return True if the object can be used in await expression Can also be used to distinguish generator based coroutines from regular generators import types def gen yield types coroutine def gen_coro yield assert not isawaitable gen assert isawaitable ge
en
null
339
n_coro New in version 3 5 inspect isasyncgenfunction object Return True if the object is an asynchronous generator function for example async def agen yield 1 inspect isasyncgenfunction agen True New in version 3 6 Changed in version 3 8 Functions wrapped in functools partial now return True if the wrapped function is a asynchronous generator function inspect isasyncgen object Return True if the object is an asynchronous generator iterator created by an asynchronous generator function New in version 3 6 inspect istraceback object Return True if the object is a traceback inspect isframe object Return True if the object is a frame inspect iscode object Return True if the object is a code inspect isbuiltin object Return True if the object is a built in function or a bound built in method inspect ismethodwrapper object Return True if the type of object is a MethodWrapperType These are instances of MethodWrapperType such as __str__ __eq__ and __repr__ New in version 3 11 inspect isroutine object Return True if the object is a user defined or built in function or method inspect isabstract object Return True if the object is an abstract base class inspect ismethoddescriptor object Return True if the object is a method descriptor but not if ismethod isclass isfunction or isbuiltin are true This for example is true of int __add__ An object passing this test has a __get__ method but not a __set__ method but beyond that the set of attributes varies A __name__ attribute is usually sensible and __doc__ often is Methods implemented via descriptors that also pass one of the other tests return False from the ismethoddescriptor test simply because the other tests promise more you can e g count on having the __func__ attribute etc when an object passes ismethod inspect isdatadescriptor object Return True if the object is a data descriptor Data descriptors have a __set__ or a __delete__ method Examples are properties defined in Python getsets and members The latter two are defined in C and there are more specific tests available for those types which is robust across Python implementations Typically data descriptors will also have __name__ and __doc__ attributes properties getsets and members have both of these attributes but this is not guaranteed inspect isgetsetdescriptor object Return True if the object is a getset descriptor CPython implementation detail getsets are attributes defined in extension modules via PyGetSetDef structures For Python implementations without such types this method will always return False inspect ismemberdescriptor object Return True if the object is a member descriptor CPython implementation detail Member descriptors are attributes defined in extension modules via PyMemberDef structures For Python implementations without such types this method will always return False Retrieving source code inspect getdoc object Get the documentation string for an object cleaned up with cleandoc If the documentation string for an object is not provided and the object is a class a method a property or a descriptor retrieve the documentation string from the inheritance hierarchy Return None if the documentation string is invalid or missing Changed in version 3 5 Documentation strings are now inherited if not overridden inspect getcomments object Return in a single string any lines of comments immediately preceding the object s source code for a class function or method or at the top of the Python source file if the object is a module If the object s source code is unavailable return None This could happen if the object has been defined in C or the interactive shell inspect getfile object Return the name of the text or binary file in which an object was defined This will fail with a TypeError if the object is a built in module class or function inspect getmodule object Try to guess which module an object was defined in Return None if the module cannot be determined inspect getsourcefile object Return the name of the Python source file in which an object was defined or None if no way can be identified to get the source This will
en
null
340
fail with a TypeError if the object is a built in module class or function inspect getsourcelines object Return a list of source lines and starting line number for an object The argument may be a module class method function traceback frame or code object The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found An OSError is raised if the source code cannot be retrieved A TypeError is raised if the object is a built in module class or function Changed in version 3 3 OSError is raised instead of IOError now an alias of the former inspect getsource object Return the text of the source code for an object The argument may be a module class method function traceback frame or code object The source code is returned as a single string An OSError is raised if the source code cannot be retrieved A TypeError is raised if the object is a built in module class or function Changed in version 3 3 OSError is raised instead of IOError now an alias of the former inspect cleandoc doc Clean up indentation from docstrings that are indented to line up with blocks of code All leading whitespace is removed from the first line Any leading whitespace that can be uniformly removed from the second line onwards is removed Empty lines at the beginning and end are subsequently removed Also all tabs are expanded to spaces Introspecting callables with the Signature object New in version 3 3 The Signature object represents the call signature of a callable object and its return annotation To retrieve a Signature object use the signature function inspect signature callable follow_wrapped True globals None locals None eval_str False Return a Signature object for the given callable from inspect import signature def foo a b int kwargs pass sig signature foo str sig a b int kwargs str sig parameters b b int sig parameters b annotation class int Accepts a wide range of Python callables from plain functions and classes to functools partial objects For objects defined in modules using stringized annotations from __future__ import annotations signature will attempt to automatically un stringize the annotations using get_annotations The globals locals and eval_str parameters are passed into get_annotations when resolving the annotations see the documentation for get_annotations for instructions on how to use these parameters Raises ValueError if no signature can be provided and TypeError if that type of object is not supported Also if the annotations are stringized and eval_str is not false the eval call s to un stringize the annotations in get_annotations could potentially raise any kind of exception A slash in the signature of a function denotes that the parameters prior to it are positional only For more info see the FAQ entry on positional only parameters Changed in version 3 5 The follow_wrapped parameter was added Pass False to get a signature of callable specifically callable __wrapped__ will not be used to unwrap decorated callables Changed in version 3 10 The globals locals and eval_str parameters were added Note Some callables may not be introspectable in certain implementations of Python For example in CPython some built in functions defined in C provide no metadata about their arguments CPython implementation detail If the passed object has a __signature__ attribute we may use it to create the signature The exact semantics are an implementation detail and are subject to unannounced changes Consult the source code for current semantics class inspect Signature parameters None return_annotation Signature empty A Signature object represents the call signature of a function and its return annotation For each parameter accepted by the function it stores a Parameter object in its parameters collection The optional parameters argument is a sequence of Parameter objects which is validated to check that there are no parameters with duplicate names and that the parameters are in the right order i e positional only first then positional or keyword
en
null
341
and that parameters with defaults follow parameters without defaults The optional return_annotation argument can be an arbitrary Python object It represents the return annotation of the callable Signature objects are immutable Use Signature replace to make a modified copy Changed in version 3 5 Signature objects are now picklable and hashable empty A special class level marker to specify absence of a return annotation parameters An ordered mapping of parameters names to the corresponding Parameter objects Parameters appear in strict definition order including keyword only parameters Changed in version 3 7 Python only explicitly guaranteed that it preserved the declaration order of keyword only parameters as of version 3 7 although in practice this order had always been preserved in Python 3 return_annotation The return annotation for the callable If the callable has no return annotation this attribute is set to Signature empty bind args kwargs Create a mapping from positional and keyword arguments to parameters Returns BoundArguments if args and kwargs match the signature or raises a TypeError bind_partial args kwargs Works the same way as Signature bind but allows the omission of some required arguments mimics functools partial behavior Returns BoundArguments or raises a TypeError if the passed arguments do not match the signature replace parameters return_annotation Create a new Signature instance based on the instance replace was invoked on It is possible to pass different parameters and or return_annotation to override the corresponding properties of the base signature To remove return_annotation from the copied Signature pass in Signature empty def test a b pass sig signature test new_sig sig replace return_annotation new return anno str new_sig a b new return anno classmethod from_callable obj follow_wrapped True globals None locals None eval_str False Return a Signature or its subclass object for a given callable obj This method simplifies subclassing of Signature class MySignature Signature pass sig MySignature from_callable sum assert isinstance sig MySignature Its behavior is otherwise identical to that of signature New in version 3 5 Changed in version 3 10 The globals locals and eval_str parameters were added class inspect Parameter name kind default Parameter empty annotation Parameter empty Parameter objects are immutable Instead of modifying a Parameter object you can use Parameter replace to create a modified copy Changed in version 3 5 Parameter objects are now picklable and hashable empty A special class level marker to specify absence of default values and annotations name The name of the parameter as a string The name must be a valid Python identifier CPython implementation detail CPython generates implicit parameter names of the form 0 on the code objects used to implement comprehensions and generator expressions Changed in version 3 6 These parameter names are now exposed by this module as names like implicit0 default The default value for the parameter If the parameter has no default value this attribute is set to Parameter empty annotation The annotation for the parameter If the parameter has no annotation this attribute is set to Parameter empty kind Describes how argument values are bound to the parameter The possible values are accessible via Parameter like Parameter KEYWORD_ONLY and support comparison and ordering in the following order Name Meaning POSITIONAL_ONLY Value must be supplied as a positional argument Positional only parameters are those which appear before a entry if present in a Python function definition POSITIONAL_OR_KEYWORD Value may be supplied as either a keyword or positional argument this is the standard binding behaviour for functions implemented in Python VAR_POSITIONAL A tuple of positional arguments that aren t bound to any other parameter This corresponds to a args parameter in a Python function definition KEYWORD_ONLY Value must be supplied as a keyword argument Keyword only parameters are those which appear after a or args entry in a Python function definition VAR_K
en
null
342
EYWORD A dict of keyword arguments that aren t bound to any other parameter This corresponds to a kwargs parameter in a Python function definition Example print all keyword only arguments without default values def foo a b c d 10 pass sig signature foo for param in sig parameters values if param kind param KEYWORD_ONLY and param default is param empty print Parameter param Parameter c kind description Describes a enum value of Parameter kind New in version 3 8 Example print all descriptions of arguments def foo a b c d 10 pass sig signature foo for param in sig parameters values print param kind description positional or keyword positional or keyword keyword only keyword only replace name kind default annotation Create a new Parameter instance based on the instance replaced was invoked on To override a Parameter attribute pass the corresponding argument To remove a default value or and an annotation from a Parameter pass Parameter empty from inspect import Parameter param Parameter foo Parameter KEYWORD_ONLY default 42 str param foo 42 str param replace Will create a shallow copy of param foo 42 str param replace default Parameter empty annotation spam foo spam Changed in version 3 4 In Python 3 3 Parameter objects were allowed to have name set to None if their kind was set to POSITIONAL_ONLY This is no longer permitted class inspect BoundArguments Result of a Signature bind or Signature bind_partial call Holds the mapping of arguments to the function s parameters arguments A mutable mapping of parameters names to arguments values Contains only explicitly bound arguments Changes in arguments will reflect in args and kwargs Should be used in conjunction with Signature parameters for any argument processing purposes Note Arguments for which Signature bind or Signature bind_partial relied on a default value are skipped However if needed use BoundArguments apply_defaults to add them Changed in version 3 9 arguments is now of type dict Formerly it was of type collections OrderedDict args A tuple of positional arguments values Dynamically computed from the arguments attribute kwargs A dict of keyword arguments values Dynamically computed from the arguments attribute signature A reference to the parent Signature object apply_defaults Set default values for missing arguments For variable positional arguments args the default is an empty tuple For variable keyword arguments kwargs the default is an empty dict def foo a b ham args pass ba inspect signature foo bind spam ba apply_defaults ba arguments a spam b ham args New in version 3 5 The args and kwargs properties can be used to invoke functions def test a b sig signature test ba sig bind 10 b 20 test ba args ba kwargs See also PEP 362 Function Signature Object The detailed specification implementation details and examples Classes and functions inspect getclasstree classes unique False Arrange the given list of classes into a hierarchy of nested lists Where a nested list appears it contains classes derived from the class whose entry immediately precedes the list Each entry is a 2 tuple containing a class and a tuple of its base classes If the unique argument is true exactly one entry appears in the returned structure for each class in the given list Otherwise classes using multiple inheritance and their descendants will appear multiple times inspect getfullargspec func Get the names and default values of a Python function s parameters A named tuple is returned FullArgSpec args varargs varkw defaults kwonlyargs kwonlydefaults annotations args is a list of the positional parameter names varargs is the name of the parameter or None if arbitrary positional arguments are not accepted varkw is the name of the parameter or None if arbitrary keyword arguments are not accepted defaults is an n tuple of default argument values corresponding to the last n positional parameters or None if there are no such defaults defined kwonlyargs is a list of keyword only parameter names in declaration order kwonlydefaults is a dictionary mapping parameter names from kwonlyargs to the default values us
en
null
343
ed if no argument is supplied annotations is a dictionary mapping parameter names to annotations The special key return is used to report the function return value annotation if any Note that signature and Signature Object provide the recommended API for callable introspection and support additional behaviours like positional only arguments that are sometimes encountered in extension module APIs This function is retained primarily for use in code that needs to maintain compatibility with the Python 2 inspect module API Changed in version 3 4 This function is now based on signature but still ignores __wrapped__ attributes and includes the already bound first parameter in the signature output for bound methods Changed in version 3 6 This method was previously documented as deprecated in favour of signature in Python 3 5 but that decision has been reversed in order to restore a clearly supported standard interface for single source Python 2 3 code migrating away from the legacy getargspec API Changed in version 3 7 Python only explicitly guaranteed that it preserved the declaration order of keyword only parameters as of version 3 7 although in practice this order had always been preserved in Python 3 inspect getargvalues frame Get information about arguments passed into a particular frame A named tuple ArgInfo args varargs keywords locals is returned args is a list of the argument names varargs and keywords are the names of the and arguments or None locals is the locals dictionary of the given frame Note This function was inadvertently marked as deprecated in Python 3 5 inspect formatargvalues args varargs varkw locals formatarg formatvarargs formatvarkw formatvalue Format a pretty argument spec from the four values returned by getargvalues The format arguments are the corresponding optional formatting functions that are called to turn names and values into strings Note This function was inadvertently marked as deprecated in Python 3 5 inspect getmro cls Return a tuple of class cls s base classes including cls in method resolution order No class appears more than once in this tuple Note that the method resolution order depends on cls s type Unless a very peculiar user defined metatype is in use cls will be the first element of the tuple inspect getcallargs func args kwds Bind the args and kwds to the argument names of the Python function or method func as if it was called with them For bound methods bind also the first argument typically named self to the associated instance A dict is returned mapping the argument names including the names of the and arguments if any to their values from args and kwds In case of invoking func incorrectly i e whenever func args kwds would raise an exception because of incompatible signature an exception of the same type and the same or similar message is raised For example from inspect import getcallargs def f a b 1 pos named pass getcallargs f 1 2 3 a 1 named b 2 pos 3 True getcallargs f a 2 x 4 a 2 named x 4 b 1 pos True getcallargs f Traceback most recent call last TypeError f missing 1 required positional argument a New in version 3 2 Deprecated since version 3 5 Use Signature bind and Signature bind_partial instead inspect getclosurevars func Get the mapping of external name references in a Python function or method func to their current values A named tuple ClosureVars nonlocals globals builtins unbound is returned nonlocals maps referenced names to lexical closure variables globals to the function s module globals and builtins to the builtins visible from the function body unbound is the set of names referenced in the function that could not be resolved at all given the current module globals and builtins TypeError is raised if func is not a Python function or method New in version 3 3 inspect unwrap func stop None Get the object wrapped by func It follows the chain of __wrapped__ attributes returning the last object in the chain stop is an optional callback accepting an object in the wrapper chain as its sole argument that allows the unwrapping to be terminated early if the callback
en
null
344
returns a true value If the callback never returns a true value the last object in the chain is returned as usual For example signature uses this to stop unwrapping if any object in the chain has a __signature__ attribute defined ValueError is raised if a cycle is encountered New in version 3 4 inspect get_annotations obj globals None locals None eval_str False Compute the annotations dict for an object obj may be a callable class or module Passing in an object of any other type raises TypeError Returns a dict get_annotations returns a new dict every time it s called calling it twice on the same object will return two different but equivalent dicts This function handles several details for you If eval_str is true values of type str will be un stringized using eval This is intended for use with stringized annotations from __future__ import annotations If obj doesn t have an annotations dict returns an empty dict Functions and methods always have an annotations dict classes modules and other types of callables may not Ignores inherited annotations on classes If a class doesn t have its own annotations dict returns an empty dict All accesses to object members and dict values are done using getattr and dict get for safety Always always always returns a freshly created dict eval_str controls whether or not values of type str are replaced with the result of calling eval on those values If eval_str is true eval is called on values of type str Note that get_annotations doesn t catch exceptions if eval raises an exception it will unwind the stack past the get_annotations call If eval_str is false the default values of type str are unchanged globals and locals are passed in to eval see the documentation for eval for more information If globals or locals is None this function may replace that value with a context specific default contingent on type obj If obj is a module globals defaults to obj __dict__ If obj is a class globals defaults to sys modules obj __module__ __dict__ and locals defaults to the obj class namespace If obj is a callable globals defaults to obj __globals__ although if obj is a wrapped function using functools update_wrapper it is first unwrapped Calling get_annotations is best practice for accessing the annotations dict of any object See Annotations Best Practices for more information on annotations best practices New in version 3 10 The interpreter stack Some of the following functions return FrameInfo objects For backwards compatibility these objects allow tuple like operations on all attributes except positions This behavior is considered deprecated and may be removed in the future class inspect FrameInfo frame The frame object that the record corresponds to filename The file name associated with the code being executed by the frame this record corresponds to lineno The line number of the current line associated with the code being executed by the frame this record corresponds to function The function name that is being executed by the frame this record corresponds to code_context A list of lines of context from the source code that s being executed by the frame this record corresponds to index The index of the current line being executed in the code_context list positions A dis Positions object containing the start line number end line number start column offset and end column offset associated with the instruction being executed by the frame this record corresponds to Changed in version 3 5 Return a named tuple instead of a tuple Changed in version 3 11 FrameInfo is now a class instance that is backwards compatible with the previous named tuple class inspect Traceback filename The file name associated with the code being executed by the frame this traceback corresponds to lineno The line number of the current line associated with the code being executed by the frame this traceback corresponds to function The function name that is being executed by the frame this traceback corresponds to code_context A list of lines of context from the source code that s being executed by the frame this traceback correspon
en
null
345
ds to index The index of the current line being executed in the code_context list positions A dis Positions object containing the start line number end line number start column offset and end column offset associated with the instruction being executed by the frame this traceback corresponds to Changed in version 3 11 Traceback is now a class instance that is backwards compatible with the previous named tuple Note Keeping references to frame objects as found in the first element of the frame records these functions return can cause your program to create reference cycles Once a reference cycle has been created the lifespan of all objects which can be accessed from the objects which form the cycle can become much longer even if Python s optional cycle detector is enabled If such cycles must be created it is important to ensure they are explicitly broken to avoid the delayed destruction of objects and increased memory consumption which occurs Though the cycle detector will catch these destruction of the frames and local variables can be made deterministic by removing the cycle in a finally clause This is also important if the cycle detector was disabled when Python was compiled or using gc disable For example def handle_stackframe_without_leak frame inspect currentframe try do something with the frame finally del frame If you want to keep the frame around for example to print a traceback later you can also break reference cycles by using the frame clear method The optional context argument supported by most of these functions specifies the number of lines of context to return which are centered around the current line inspect getframeinfo frame context 1 Get information about a frame or traceback object A Traceback object is returned Changed in version 3 11 A Traceback object is returned instead of a named tuple inspect getouterframes frame context 1 Get a list of FrameInfo objects for a frame and all outer frames These frames represent the calls that lead to the creation of frame The first entry in the returned list represents frame the last entry represents the outermost call on frame s stack Changed in version 3 5 A list of named tuples FrameInfo frame filename lineno function code_context index is returned Changed in version 3 11 A list of FrameInfo objects is returned inspect getinnerframes traceback context 1 Get a list of FrameInfo objects for a traceback s frame and all inner frames These frames represent calls made as a consequence of frame The first entry in the list represents traceback the last entry represents where the exception was raised Changed in version 3 5 A list of named tuples FrameInfo frame filename lineno function code_context index is returned Changed in version 3 11 A list of FrameInfo objects is returned inspect currentframe Return the frame object for the caller s stack frame CPython implementation detail This function relies on Python stack frame support in the interpreter which isn t guaranteed to exist in all implementations of Python If running in an implementation without Python stack frame support this function returns None inspect stack context 1 Return a list of FrameInfo objects for the caller s stack The first entry in the returned list represents the caller the last entry represents the outermost call on the stack Changed in version 3 5 A list of named tuples FrameInfo frame filename lineno function code_context index is returned Changed in version 3 11 A list of FrameInfo objects is returned inspect trace context 1 Return a list of FrameInfo objects for the stack between the current frame and the frame in which an exception currently being handled was raised in The first entry in the list represents the caller the last entry represents where the exception was raised Changed in version 3 5 A list of named tuples FrameInfo frame filename lineno function code_context index is returned Changed in version 3 11 A list of FrameInfo objects is returned Fetching attributes statically Both getattr and hasattr can trigger code execution when fetching or checking for the existence of attributes
en
null
346
Descriptors like properties will be invoked and __getattr__ and __getattribute__ may be called For cases where you want passive introspection like documentation tools this can be inconvenient getattr_static has the same signature as getattr but avoids executing code when it fetches attributes inspect getattr_static obj attr default None Retrieve attributes without triggering dynamic lookup via the descriptor protocol __getattr__ or __getattribute__ Note this function may not be able to retrieve all attributes that getattr can fetch like dynamically created attributes and may find attributes that getattr can t like descriptors that raise AttributeError It can also return descriptors objects instead of instance members If the instance __dict__ is shadowed by another member for example a property then this function will be unable to find instance members New in version 3 2 getattr_static does not resolve descriptors for example slot descriptors or getset descriptors on objects implemented in C The descriptor object is returned instead of the underlying attribute You can handle these with code like the following Note that for arbitrary getset descriptors invoking these may trigger code execution example code for resolving the builtin descriptor types class _foo __slots__ foo slot_descriptor type _foo foo getset_descriptor type type open __file__ name wrapper_descriptor type str __dict__ __add__ descriptor_types slot_descriptor getset_descriptor wrapper_descriptor result getattr_static some_object foo if type result in descriptor_types try result result __get__ except AttributeError descriptors can raise AttributeError to indicate there is no underlying value in which case the descriptor itself will have to do pass Current State of Generators Coroutines and Asynchronous Generators When implementing coroutine schedulers and for other advanced uses of generators it is useful to determine whether a generator is currently executing is waiting to start or resume or execution or has already terminated getgeneratorstate allows the current state of a generator to be determined easily inspect getgeneratorstate generator Get current state of a generator iterator Possible states are GEN_CREATED Waiting to start execution GEN_RUNNING Currently being executed by the interpreter GEN_SUSPENDED Currently suspended at a yield expression GEN_CLOSED Execution has completed New in version 3 2 inspect getcoroutinestate coroutine Get current state of a coroutine object The function is intended to be used with coroutine objects created by async def functions but will accept any coroutine like object that has cr_running and cr_frame attributes Possible states are CORO_CREATED Waiting to start execution CORO_RUNNING Currently being executed by the interpreter CORO_SUSPENDED Currently suspended at an await expression CORO_CLOSED Execution has completed New in version 3 5 inspect getasyncgenstate agen Get current state of an asynchronous generator object The function is intended to be used with asynchronous iterator objects created by async def functions which use the yield statement but will accept any asynchronous generator like object that has ag_running and ag_frame attributes Possible states are AGEN_CREATED Waiting to start execution AGEN_RUNNING Currently being executed by the interpreter AGEN_SUSPENDED Currently suspended at a yield expression AGEN_CLOSED Execution has completed New in version 3 12 The current internal state of the generator can also be queried This is mostly useful for testing purposes to ensure that internal state is being updated as expected inspect getgeneratorlocals generator Get the mapping of live local variables in generator to their current values A dictionary is returned that maps from variable names to values This is the equivalent of calling locals in the body of the generator and all the same caveats apply If generator is a generator with no currently associated frame then an empty dictionary is returned TypeError is raised if generator is not a Python generator object CPython implementation detail This function r
en
null
347
elies on the generator exposing a Python stack frame for introspection which isn t guaranteed to be the case in all implementations of Python In such cases this function will always return an empty dictionary New in version 3 3 inspect getcoroutinelocals coroutine This function is analogous to getgeneratorlocals but works for coroutine objects created by async def functions New in version 3 5 inspect getasyncgenlocals agen This function is analogous to getgeneratorlocals but works for asynchronous generator objects created by async def functions which use the yield statement New in version 3 12 Code Objects Bit Flags Python code objects have a co_flags attribute which is a bitmap of the following flags inspect CO_OPTIMIZED The code object is optimized using fast locals inspect CO_NEWLOCALS If set a new dict will be created for the frame s f_locals when the code object is executed inspect CO_VARARGS The code object has a variable positional parameter args like inspect CO_VARKEYWORDS The code object has a variable keyword parameter kwargs like inspect CO_NESTED The flag is set when the code object is a nested function inspect CO_GENERATOR The flag is set when the code object is a generator function i e a generator object is returned when the code object is executed inspect CO_COROUTINE The flag is set when the code object is a coroutine function When the code object is executed it returns a coroutine object See PEP 492 for more details New in version 3 5 inspect CO_ITERABLE_COROUTINE The flag is used to transform generators into generator based coroutines Generator objects with this flag can be used in await expression and can yield from coroutine objects See PEP 492 for more details New in version 3 5 inspect CO_ASYNC_GENERATOR The flag is set when the code object is an asynchronous generator function When the code object is executed it returns an asynchronous generator object See PEP 525 for more details New in version 3 6 Note The flags are specific to CPython and may not be defined in other Python implementations Furthermore the flags are an implementation detail and can be removed or deprecated in future Python releases It s recommended to use public APIs from the inspect module for any introspection needs Buffer flags class inspect BufferFlags This is an enum IntFlag that represents the flags that can be passed to the __buffer__ method of objects implementing the buffer protocol The meaning of the flags is explained at Buffer request types SIMPLE WRITABLE FORMAT ND STRIDES C_CONTIGUOUS F_CONTIGUOUS ANY_CONTIGUOUS INDIRECT CONTIG CONTIG_RO STRIDED STRIDED_RO RECORDS RECORDS_RO FULL FULL_RO READ WRITE New in version 3 12 Command Line Interface The inspect module also provides a basic introspection capability from the command line By default accepts the name of a module and prints the source of that module A class or function within the module can be printed instead by appended a colon and the qualified name of the target object details Print information about the specified object rather than the source code
en
null
348
timeit Measure execution time of small code snippets Source code Lib timeit py This module provides a simple way to time small bits of Python code It has both a Command Line Interface as well as a callable one It avoids a number of common traps for measuring execution times See also Tim Peters introduction to the Algorithms chapter in the second edition of Python Cookbook published by O Reilly Basic Examples The following example shows how the Command Line Interface can be used to compare three different expressions python m timeit join str n for n in range 100 10000 loops best of 5 30 2 usec per loop python m timeit join str n for n in range 100 10000 loops best of 5 27 5 usec per loop python m timeit join map str range 100 10000 loops best of 5 23 2 usec per loop This can be achieved from the Python Interface with import timeit timeit timeit join str n for n in range 100 number 10000 0 3018611848820001 timeit timeit join str n for n in range 100 number 10000 0 2727368790656328 timeit timeit join map str range 100 number 10000 0 23702679807320237 A callable can also be passed from the Python Interface timeit timeit lambda join map str range 100 number 10000 0 19665591977536678 Note however that timeit will automatically determine the number of repetitions only when the command line interface is used In the Examples section you can find more advanced examples Python Interface The module defines three convenience functions and a public class timeit timeit stmt pass setup pass timer default timer number 1000000 globals None Create a Timer instance with the given statement setup code and timer function and run its timeit method with number executions The optional globals argument specifies a namespace in which to execute the code Changed in version 3 5 The optional globals parameter was added timeit repeat stmt pass setup pass timer default timer repeat 5 number 1000000 globals None Create a Timer instance with the given statement setup code and timer function and run its repeat method with the given repeat count and number executions The optional globals argument specifies a namespace in which to execute the code Changed in version 3 5 The optional globals parameter was added Changed in version 3 7 Default value of repeat changed from 3 to 5 timeit default_timer The default timer which is always time perf_counter returns float seconds An alternative time perf_counter_ns returns integer nanoseconds Changed in version 3 3 time perf_counter is now the default timer class timeit Timer stmt pass setup pass timer timer function globals None Class for timing execution speed of small code snippets The constructor takes a statement to be timed an additional statement used for setup and a timer function Both statements default to pass the timer function is platform dependent see the module doc string stmt and setup may also contain multiple statements separated by or newlines as long as they don t contain multi line string literals The statement will by default be executed within timeit s namespace this behavior can be controlled by passing a namespace to globals To measure the execution time of the first statement use the timeit method The repeat and autorange methods are convenience methods to call timeit multiple times The execution time of setup is excluded from the overall timed execution run The stmt and setup parameters can also take objects that are callable without arguments This will embed calls to them in a timer function that will then be executed by timeit Note that the timing overhead is a little larger in this case because of the extra function calls Changed in version 3 5 The optional globals parameter was added timeit number 1000000 Time number executions of the main statement This executes the setup statement once and then returns the time it takes to execute the main statement a number of times The default timer returns seconds as a float The argument is the number of times through the loop defaulting to one million The main statement the setup statement and the timer function to be used are passed to the construc
en
null
349
tor Note By default timeit temporarily turns off garbage collection during the timing The advantage of this approach is that it makes independent timings more comparable The disadvantage is that GC may be an important component of the performance of the function being measured If so GC can be re enabled as the first statement in the setup string For example timeit Timer for i in range 10 oct i gc enable timeit autorange callback None Automatically determine how many times to call timeit This is a convenience function that calls timeit repeatedly so that the total time 0 2 second returning the eventual number of loops time taken for that number of loops It calls timeit with increasing numbers from the sequence 1 2 5 10 20 50 until the time taken is at least 0 2 seconds If callback is given and is not None it will be called after each trial with two arguments callback number time_taken New in version 3 6 repeat repeat 5 number 1000000 Call timeit a few times This is a convenience function that calls the timeit repeatedly returning a list of results The first argument specifies how many times to call timeit The second argument specifies the number argument for timeit Note It s tempting to calculate mean and standard deviation from the result vector and report these However this is not very useful In a typical case the lowest value gives a lower bound for how fast your machine can run the given code snippet higher values in the result vector are typically not caused by variability in Python s speed but by other processes interfering with your timing accuracy So the min of the result is probably the only number you should be interested in After that you should look at the entire vector and apply common sense rather than statistics Changed in version 3 7 Default value of repeat changed from 3 to 5 print_exc file None Helper to print a traceback from the timed code Typical use t Timer outside the try except try t timeit or t repeat except Exception t print_exc The advantage over the standard traceback is that source lines in the compiled template will be displayed The optional file argument directs where the traceback is sent it defaults to sys stderr Command Line Interface When called as a program from the command line the following form is used python m timeit n N r N u U s S p v h statement Where the following options are understood n N number N how many times to execute statement r N repeat N how many times to repeat the timer default 5 s S setup S statement to be executed once initially default pass p process measure process time not wallclock time using time process_time instead of time perf_counter which is the default New in version 3 3 u unit U specify a time unit for timer output can select nsec usec msec or sec New in version 3 5 v verbose print raw timing results repeat for more digits precision h help print a short usage message and exit A multi line statement may be given by specifying each line as a separate statement argument indented lines are possible by enclosing an argument in quotes and using leading spaces Multiple s options are treated similarly If n is not given a suitable number of loops is calculated by trying increasing numbers from the sequence 1 2 5 10 20 50 until the total time is at least 0 2 seconds default_timer measurements can be affected by other programs running on the same machine so the best thing to do when accurate timing is necessary is to repeat the timing a few times and use the best time The r option is good for this the default of 5 repetitions is probably enough in most cases You can use time process_time to measure CPU time Note There is a certain baseline overhead associated with executing a pass statement The code here doesn t try to hide it but you should be aware of it The baseline overhead can be measured by invoking the program without arguments and it might differ between Python versions Examples It is possible to provide a setup statement that is executed only once at the beginning python m timeit s text sample string char g char in text 5000000 loops best of 5 0 0877 usec
en
null
350
per loop python m timeit s text sample string char g text find char 1000000 loops best of 5 0 342 usec per loop In the output there are three fields The loop count which tells you how many times the statement body was run per timing loop repetition The repetition count best of 5 which tells you how many times the timing loop was repeated and finally the time the statement body took on average within the best repetition of the timing loop That is the time the fastest repetition took divided by the loop count import timeit timeit timeit char in text setup text sample string char g 0 41440500499993504 timeit timeit text find char setup text sample string char g 1 7246671520006203 The same can be done using the Timer class and its methods import timeit t timeit Timer char in text setup text sample string char g t timeit 0 3955516149999312 t repeat 0 40183617287970225 0 37027556854118704 0 38344867356679524 0 3712595970846668 0 37866875250654886 The following examples show how to time expressions that contain multiple lines Here we compare the cost of using hasattr vs try except to test for missing and present object attributes python m timeit try str __bool__ except AttributeError pass 20000 loops best of 5 15 7 usec per loop python m timeit if hasattr str __bool__ pass 50000 loops best of 5 4 26 usec per loop python m timeit try int __bool__ except AttributeError pass 200000 loops best of 5 1 43 usec per loop python m timeit if hasattr int __bool__ pass 100000 loops best of 5 2 23 usec per loop import timeit attribute is missing s try str __bool__ except AttributeError pass timeit timeit stmt s number 100000 0 9138244460009446 s if hasattr str __bool__ pass timeit timeit stmt s number 100000 0 5829014980008651 attribute is present s try int __bool__ except AttributeError pass timeit timeit stmt s number 100000 0 04215312199994514 s if hasattr int __bool__ pass timeit timeit stmt s number 100000 0 08588060699912603 To give the timeit module access to functions you define you can pass a setup parameter which contains an import statement def test Stupid test function L i for i in range 100 if __name__ __main__ import timeit print timeit timeit test setup from __main__ import test Another option is to pass globals to the globals parameter which will cause the code to be executed within your current global namespace This can be more convenient than individually specifying imports def f x return x 2 def g x return x 4 def h x return x 8 import timeit print timeit timeit func 42 for func in f g h globals globals
en
null
351
File and Directory Access The modules described in this chapter deal with disk files and directories For example there are modules for reading the properties of files manipulating paths in a portable way and creating temporary files The full list of modules in this chapter is pathlib Object oriented filesystem paths Basic use Pure paths General properties Operators Accessing individual parts Methods and properties Concrete paths Methods Correspondence to tools in the os module os path Common pathname manipulations fileinput Iterate over lines from multiple input streams stat Interpreting stat results filecmp File and Directory Comparisons The dircmp class tempfile Generate temporary files and directories Examples Deprecated functions and variables glob Unix style pathname pattern expansion fnmatch Unix filename pattern matching linecache Random access to text lines shutil High level file operations Directory and files operations Platform dependent efficient copy operations copytree example rmtree example Archiving operations Archiving example Archiving example with base_dir Querying the size of the output terminal See also Module os Operating system interfaces including functions to work with files at a lower level than Python file objects Module io Python s built in I O library including both abstract classes and some concrete classes such as file I O Built in function open The standard way to open files for reading and writing with Python
en
null
352
Generic Operating System Services The modules described in this chapter provide interfaces to operating system features that are available on almost all operating systems such as files and a clock The interfaces are generally modeled after the Unix or C interfaces but they are available on most other systems as well Here s an overview os Miscellaneous operating system interfaces File Names Command Line Arguments and Environment Variables Python UTF 8 Mode Process Parameters File Object Creation File Descriptor Operations Querying the size of a terminal Inheritance of File Descriptors Files and Directories Linux extended attributes Process Management Interface to the scheduler Miscellaneous System Information Random numbers io Core tools for working with streams Overview Text I O Binary I O Raw I O Text Encoding Opt in EncodingWarning High level Module Interface Class hierarchy I O Base Classes Raw File I O Buffered Streams Text I O Performance Binary I O Text I O Multi threading Reentrancy time Time access and conversions Functions Clock ID Constants Timezone Constants argparse Parser for command line options arguments and sub commands Core Functionality Quick Links for add_argument Example Creating a parser Adding arguments Parsing arguments ArgumentParser objects prog usage description epilog parents formatter_class prefix_chars fromfile_prefix_chars argument_default allow_abbrev conflict_handler add_help exit_on_error The add_argument method name or flags action nargs const default type choices required help metavar dest Action classes The parse_args method Option value syntax Invalid arguments Arguments containing Argument abbreviations prefix matching Beyond sys argv The Namespace object Other utilities Sub commands FileType objects Argument groups Mutual exclusion Parser defaults Printing help Partial parsing Customizing file parsing Exiting methods Intermixed parsing Upgrading optparse code Exceptions getopt C style parser for command line options logging Logging facility for Python Logger Objects Logging Levels Handler Objects Formatter Objects Filter Objects LogRecord Objects LogRecord attributes LoggerAdapter Objects Thread Safety Module Level Functions Module Level Attributes Integration with the warnings module logging config Logging configuration Configuration functions Security considerations Configuration dictionary schema Dictionary Schema Details Incremental Configuration Object connections User defined objects Handler configuration order Access to external objects Access to internal objects Import resolution and custom importers Configuring QueueHandler and QueueListener Configuration file format logging handlers Logging handlers StreamHandler FileHandler NullHandler WatchedFileHandler BaseRotatingHandler RotatingFileHandler TimedRotatingFileHandler SocketHandler DatagramHandler SysLogHandler NTEventLogHandler SMTPHandler MemoryHandler HTTPHandler QueueHandler QueueListener getpass Portable password input curses Terminal handling for character cell displays Functions Window Objects Constants curses textpad Text input widget for curses programs Textbox objects curses ascii Utilities for ASCII characters curses panel A panel stack extension for curses Functions Panel Objects platform Access to underlying platform s identifying data Cross Platform Java Platform Windows Platform macOS Platform Unix Platforms Linux Platforms errno Standard errno system symbols ctypes A foreign function library for Python ctypes tutorial Loading dynamic link libraries Accessing functions from loaded dlls Calling functions Fundamental data types Calling functions continued Calling variadic functions Calling functions with your own custom data types Specifying the required argument types function prototypes Return types Passing pointers or passing parameters by reference Structures and unions Structure union alignment and byte order Bit fields in structures and unions Arrays Pointers Type conversions Incomplete Types Callback functions Accessing values exported from dlls Surprises Variable sized data types ctypes reference Find
en
null
353
ing shared libraries Loading shared libraries Foreign functions Function prototypes Utility functions Data types Fundamental data types Structured data types Arrays and pointers
en
null
354
sndhdr Determine type of sound file Source code Lib sndhdr py Deprecated since version 3 11 will be removed in version 3 13 The sndhdr module is deprecated see PEP 594 for details and alternatives The sndhdr provides utility functions which attempt to determine the type of sound data which is in a file When these functions are able to determine what type of sound data is stored in a file they return a namedtuple containing five attributes filetype framerate nchannels nframes sampwidth The value for type indicates the data type and will be one of the strings aifc aiff au hcom sndr sndt voc wav 8svx sb ub or ul The sampling_rate will be either the actual value or 0 if unknown or difficult to decode Similarly channels will be either the number of channels or 0 if it cannot be determined or if the value is difficult to decode The value for frames will be either the number of frames or 1 The last item in the tuple bits_per_sample will either be the sample size in bits or A for A LAW or U for u LAW sndhdr what filename Determines the type of sound data stored in the file filename using whathdr If it succeeds returns a namedtuple as described above otherwise None is returned Changed in version 3 5 Result changed from a tuple to a namedtuple sndhdr whathdr filename Determines the type of sound data stored in a file based on the file header The name of the file is given by filename This function returns a namedtuple as described above on success or None Changed in version 3 5 Result changed from a tuple to a namedtuple The following sound header types are recognized as listed below with the return value from whathdr and what Value Sound header format aifc Compressed Audio Interchange Files aiff Audio Interchange Files au Au Files hcom HCOM Files sndt Sndtool Sound Files voc Creative Labs Audio Files wav Waveform Audio File Format Files 8svx 8 Bit Sampled Voice Files sb Signed Byte Audio Data Files ub UB Files ul uLAW Audio Files sndhdr tests A list of functions performing the individual tests Each function takes two arguments the byte stream and an open file like object When what is called with a byte stream the file like object will be None The test function should return a string describing the image type if the test succeeded or None if it failed Example import sndhdr imghdr what bass wav wav imghdr whathdr bass wav wav
en
null
355
7 Input and Output There are several ways to present the output of a program data can be printed in a human readable form or written to a file for future use This chapter will discuss some of the possibilities 7 1 Fancier Output Formatting So far we ve encountered two ways of writing values expression statements and the print function A third way is using the write method of file objects the standard output file can be referenced as sys stdout See the Library Reference for more information on this Often you ll want more control over the formatting of your output than simply printing space separated values There are several ways to format output To use formatted string literals begin a string with f or F before the opening quotation mark or triple quotation mark Inside this string you can write a Python expression between and characters that can refer to variables or literal values year 2016 event Referendum f Results of the year event Results of the 2016 Referendum The str format method of strings requires more manual effort You ll still use and to mark where a variable will be substituted and can provide detailed formatting directives but you ll also need to provide the information to be formatted yes_votes 42_572_654 no_votes 43_132_495 percentage yes_votes yes_votes no_votes 9 YES votes 2 2 format yes_votes percentage 42572654 YES votes 49 67 Finally you can do all the string handling yourself by using string slicing and concatenation operations to create any layout you can imagine The string type has some methods that perform useful operations for padding strings to a given column width When you don t need fancy output but just want a quick display of some variables for debugging purposes you can convert any value to a string with the repr or str functions The str function is meant to return representations of values which are fairly human readable while repr is meant to generate representations which can be read by the interpreter or will force a SyntaxError if there is no equivalent syntax For objects which don t have a particular representation for human consumption str will return the same value as repr Many values such as numbers or structures like lists and dictionaries have the same representation using either function Strings in particular have two distinct representations Some examples s Hello world str s Hello world repr s Hello world str 1 7 0 14285714285714285 x 10 3 25 y 200 200 s The value of x is repr x and y is repr y print s The value of x is 32 5 and y is 40000 The repr of a string adds string quotes and backslashes hello hello world n hellos repr hello print hellos hello world n The argument to repr may be any Python object repr x y spam eggs 32 5 40000 spam eggs The string module contains a Template class that offers yet another way to substitute values into strings using placeholders like x and replacing them with values from a dictionary but offers much less control of the formatting 7 1 1 Formatted String Literals Formatted string literals also called f strings for short let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as expression An optional format specifier can follow the expression This allows greater control over how the value is formatted The following example rounds pi to three places after the decimal import math print f The value of pi is approximately math pi 3f The value of pi is approximately 3 142 Passing an integer after the will cause that field to be a minimum number of characters wide This is useful for making columns line up table Sjoerd 4127 Jack 4098 Dcab 7678 for name phone in table items print f name 10 phone 10d Sjoerd 4127 Jack 4098 Dcab 7678 Other modifiers can be used to convert the value before it is formatted a applies ascii s applies str and r applies repr animals eels print f My hovercraft is full of animals My hovercraft is full of eels print f My hovercraft is full of animals r My hovercraft is full of eels The specifier can be used to expand an expression to the text of the expression an
en
null
356
equal sign then the representation of the evaluated expression bugs roaches count 13 area living room print f Debugging bugs count area Debugging bugs roaches count 13 area living room See self documenting expressions for more information on the specifier For a reference on these format specifications see the reference guide for the Format Specification Mini Language 7 1 2 The String format Method Basic usage of the str format method looks like this print We are the who say format knights Ni We are the knights who say Ni The brackets and characters within them called format fields are replaced with the objects passed into the str format method A number in the brackets can be used to refer to the position of the object passed into the str format method print 0 and 1 format spam eggs spam and eggs print 1 and 0 format spam eggs eggs and spam If keyword arguments are used in the str format method their values are referred to by using the name of the argument print This food is adjective format food spam adjective absolutely horrible This spam is absolutely horrible Positional and keyword arguments can be arbitrarily combined print The story of 0 1 and other format Bill Manfred other Georg The story of Bill Manfred and Georg If you have a really long format string that you don t want to split up it would be nice if you could reference the variables to be formatted by name instead of by position This can be done by simply passing the dict and using square brackets to access the keys table Sjoerd 4127 Jack 4098 Dcab 8637678 print Jack 0 Jack d Sjoerd 0 Sjoerd d Dcab 0 Dcab d format table Jack 4098 Sjoerd 4127 Dcab 8637678 This could also be done by passing the table dictionary as keyword arguments with the notation table Sjoerd 4127 Jack 4098 Dcab 8637678 print Jack Jack d Sjoerd Sjoerd d Dcab Dcab d format table Jack 4098 Sjoerd 4127 Dcab 8637678 This is particularly useful in combination with the built in function vars which returns a dictionary containing all local variables As an example the following lines produce a tidily aligned set of columns giving integers and their squares and cubes for x in range 1 11 print 0 2d 1 3d 2 4d format x x x x x x 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 For a complete overview of string formatting with str format see Format String Syntax 7 1 3 Manual String Formatting Here s the same table of squares and cubes formatted manually for x in range 1 11 print repr x rjust 2 repr x x rjust 3 end Note use of end on previous line print repr x x x rjust 4 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 Note that the one space between each column was added by the way print works it always adds spaces between its arguments The str rjust method of string objects right justifies a string in a field of a given width by padding it with spaces on the left There are similar methods str ljust and str center These methods do not write anything they just return a new string If the input string is too long they don t truncate it but return it unchanged this will mess up your column lay out but that s usually better than the alternative which would be lying about a value If you really want truncation you can always add a slice operation as in x ljust n n There is another method str zfill which pads a numeric string on the left with zeros It understands about plus and minus signs 12 zfill 5 00012 3 14 zfill 7 003 14 3 14159265359 zfill 5 3 14159265359 7 1 4 Old string formatting The operator modulo can also be used for string formatting Given string values instances of in string are replaced with zero or more elements of values This operation is commonly known as string interpolation For example import math print The value of pi is approximately 5 3f math pi The value of pi is approximately 3 142 More information can be found in the printf style String Formatting section 7 2 Reading and Writing Files open returns a file object and is most commonly used with two positional arguments and one keyword argument open filename mode encodi
en
null
357
ng None f open workfile w encoding utf 8 The first argument is a string containing the filename The second argument is another string containing a few characters describing the way in which the file will be used mode can be r when the file will only be read w for only writing an existing file with the same name will be erased and a opens the file for appending any data written to the file is automatically added to the end r opens the file for both reading and writing The mode argument is optional r will be assumed if it s omitted Normally files are opened in text mode that means you read and write strings from and to the file which are encoded in a specific encoding If encoding is not specified the default is platform dependent see open Because UTF 8 is the modern de facto standard encoding utf 8 is recommended unless you know that you need to use a different encoding Appending a b to the mode opens the file in binary mode Binary mode data is read and written as bytes objects You can not specify encoding when opening file in binary mode In text mode the default when reading is to convert platform specific line endings n on Unix r n on Windows to just n When writing in text mode the default is to convert occurrences of n back to platform specific line endings This behind the scenes modification to file data is fine for text files but will corrupt binary data like that in JPEG or EXE files Be very careful to use binary mode when reading and writing such files It is good practice to use the with keyword when dealing with file objects The advantage is that the file is properly closed after its suite finishes even if an exception is raised at some point Using with is also much shorter than writing equivalent try finally blocks with open workfile encoding utf 8 as f read_data f read We can check that the file has been automatically closed f closed True If you re not using the with keyword then you should call f close to close the file and immediately free up any system resources used by it Warning Calling f write without using the with keyword or calling f close might result in the arguments of f write not being completely written to the disk even if the program exits successfully After a file object is closed either by a with statement or by calling f close attempts to use the file object will automatically fail f close f read Traceback most recent call last File stdin line 1 in module ValueError I O operation on closed file 7 2 1 Methods of File Objects The rest of the examples in this section will assume that a file object called f has already been created To read a file s contents call f read size which reads some quantity of data and returns it as a string in text mode or bytes object in binary mode size is an optional numeric argument When size is omitted or negative the entire contents of the file will be read and returned it s your problem if the file is twice as large as your machine s memory Otherwise at most size characters in text mode or size bytes in binary mode are read and returned If the end of the file has been reached f read will return an empty string f read This is the entire file n f read f readline reads a single line from the file a newline character n is left at the end of the string and is only omitted on the last line of the file if the file doesn t end in a newline This makes the return value unambiguous if f readline returns an empty string the end of the file has been reached while a blank line is represented by n a string containing only a single newline f readline This is the first line of the file n f readline Second line of the file n f readline For reading lines from a file you can loop over the file object This is memory efficient fast and leads to simple code for line in f print line end This is the first line of the file Second line of the file If you want to read all the lines of a file in a list you can also use list f or f readlines f write string writes the contents of string to the file returning the number of characters written f write This is a test n 15 Other types of objects need
en
null
358
to be converted either to a string in text mode or a bytes object in binary mode before writing them value the answer 42 s str value convert the tuple to string f write s 18 f tell returns an integer giving the file object s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode To change the file object s position use f seek offset whence The position is computed from adding offset to a reference point the reference point is selected by the whence argument A whence value of 0 measures from the beginning of the file 1 uses the current file position and 2 uses the end of the file as the reference point whence can be omitted and defaults to 0 using the beginning of the file as the reference point f open workfile rb f write b 0123456789abcdef 16 f seek 5 Go to the 6th byte in the file 5 f read 1 b 5 f seek 3 2 Go to the 3rd byte before the end 13 f read 1 b d In text files those opened without a b in the mode string only seeks relative to the beginning of the file are allowed the exception being seeking to the very file end with seek 0 2 and the only valid offset values are those returned from the f tell or zero Any other offset value produces undefined behaviour File objects have some additional methods such as isatty and truncate which are less frequently used consult the Library Reference for a complete guide to file objects 7 2 2 Saving structured data with json Strings can easily be written to and read from a file Numbers take a bit more effort since the read method only returns strings which will have to be passed to a function like int which takes a string like 123 and returns its numeric value 123 When you want to save more complex data types like nested lists and dictionaries parsing and serializing by hand becomes complicated Rather than having users constantly writing and debugging code to save complicated data types to files Python allows you to use the popular data interchange format called JSON JavaScript Object Notation The standard module called json can take Python data hierarchies and convert them to string representations this process is called serializing Reconstructing the data from the string representation is called deserializing Between serializing and deserializing the string representing the object may have been stored in a file or data or sent over a network connection to some distant machine Note The JSON format is commonly used by modern applications to allow for data exchange Many programmers are already familiar with it which makes it a good choice for interoperability If you have an object x you can view its JSON string representation with a simple line of code import json x 1 simple list json dumps x 1 simple list Another variant of the dumps function called dump simply serializes the object to a text file So if f is a text file object opened for writing we can do this json dump x f To decode the object again if f is a binary file or text file object which has been opened for reading x json load f Note JSON files must be encoded in UTF 8 Use encoding utf 8 when opening JSON file as a text file for both of reading and writing This simple serialization technique can handle lists and dictionaries but serializing arbitrary class instances in JSON requires a bit of extra effort The reference for the json module contains an explanation of this See also pickle the pickle module Contrary to JSON pickle is a protocol which allows the serialization of arbitrarily complex Python objects As such it is specific to Python and cannot be used to communicate with applications written in other languages It is also insecure by default deserializing pickle data coming from an untrusted source can execute arbitrary code if the data was crafted by a skilled attacker
en
null
359
getpass Portable password input Source code Lib getpass py Availability not Emscripten not WASI This module does not work or is not available on WebAssembly platforms wasm32 emscripten and wasm32 wasi See WebAssembly platforms for more information The getpass module provides two functions getpass getpass prompt Password stream None Prompt the user for a password without echoing The user is prompted using the string prompt which defaults to Password On Unix the prompt is written to the file like object stream using the replace error handler if needed stream defaults to the controlling terminal dev tty or if that is unavailable to sys stderr this argument is ignored on Windows If echo free input is unavailable getpass falls back to printing a warning message to stream and reading from sys stdin and issuing a GetPassWarning Note If you call getpass from within IDLE the input may be done in the terminal you launched IDLE from rather than the idle window itself exception getpass GetPassWarning A UserWarning subclass issued when password input may be echoed getpass getuser Return the login name of the user This function checks the environment variables LOGNAME USER LNAME and USERNAME in order and returns the value of the first one which is set to a non empty string If none are set the login name from the password database is returned on systems which support the pwd module otherwise an exception is raised In general this function should be preferred over os getlogin
en
null
360
HOWTO Fetch Internet Resources Using The urllib Package Author Michael Foord Introduction Related Articles You may also find useful the following article on fetching web resources with Python Basic Authentication A tutorial on Basic Authentication with examples in Python urllib request is a Python module for fetching URLs Uniform Resource Locators It offers a very simple interface in the form of the urlopen function This is capable of fetching URLs using a variety of different protocols It also offers a slightly more complex interface for handling common situations like basic authentication cookies proxies and so on These are provided by objects called handlers and openers urllib request supports fetching URLs for many URL schemes identified by the string before the in URL for example ftp is the URL scheme of ftp python org using their associated network protocols e g FTP HTTP This tutorial focuses on the most common case HTTP For straightforward situations urlopen is very easy to use But as soon as you encounter errors or non trivial cases when opening HTTP URLs you will need some understanding of the HyperText Transfer Protocol The most comprehensive and authoritative reference to HTTP is RFC 2616 This is a technical document and not intended to be easy to read This HOWTO aims to illustrate using urllib with enough detail about HTTP to help you through It is not intended to replace the urllib request docs but is supplementary to them Fetching URLs The simplest way to use urllib request is as follows import urllib request with urllib request urlopen http python org as response html response read If you wish to retrieve a resource via URL and store it in a temporary location you can do so via the shutil copyfileobj and tempfile NamedTemporaryFile functions import shutil import tempfile import urllib request with urllib request urlopen http python org as response with tempfile NamedTemporaryFile delete False as tmp_file shutil copyfileobj response tmp_file with open tmp_file name as html pass Many uses of urllib will be that simple note that instead of an http URL we could have used a URL starting with ftp file etc However it s the purpose of this tutorial to explain the more complicated cases concentrating on HTTP HTTP is based on requests and responses the client makes requests and servers send responses urllib request mirrors this with a Request object which represents the HTTP request you are making In its simplest form you create a Request object that specifies the URL you want to fetch Calling urlopen with this Request object returns a response object for the URL requested This response is a file like object which means you can for example call read on the response import urllib request req urllib request Request http python org with urllib request urlopen req as response the_page response read Note that urllib request makes use of the same Request interface to handle all URL schemes For example you can make an FTP request like so req urllib request Request ftp example com In the case of HTTP there are two extra things that Request objects allow you to do First you can pass data to be sent to the server Second you can pass extra information metadata about the data or about the request itself to the server this information is sent as HTTP headers Let s look at each of these in turn Data Sometimes you want to send data to a URL often the URL will refer to a CGI Common Gateway Interface script or other web application With HTTP this is often done using what s known as a POST request This is often what your browser does when you submit a HTML form that you filled in on the web Not all POSTs have to come from forms you can use a POST to transmit arbitrary data to your own application In the common case of HTML forms the data needs to be encoded in a standard way and then passed to the Request object as the data argument The encoding is done using a function from the urllib parse library import urllib parse import urllib request url http www someserver com cgi bin register cgi values name Michael Foord location Northampto
en
null
361
n language Python data urllib parse urlencode values data data encode ascii data should be bytes req urllib request Request url data with urllib request urlopen req as response the_page response read Note that other encodings are sometimes required e g for file upload from HTML forms see HTML Specification Form Submission for more details If you do not pass the data argument urllib uses a GET request One way in which GET and POST requests differ is that POST requests often have side effects they change the state of the system in some way for example by placing an order with the website for a hundredweight of tinned spam to be delivered to your door Though the HTTP standard makes it clear that POSTs are intended to always cause side effects and GET requests never to cause side effects nothing prevents a GET request from having side effects nor a POST requests from having no side effects Data can also be passed in an HTTP GET request by encoding it in the URL itself This is done as follows 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 name Somebody Here language Python location Northampton url http www example com example cgi full_url url url_values data urllib request urlopen full_url Notice that the full URL is created by adding a to the URL followed by the encoded values Headers We ll discuss here one particular HTTP header to illustrate how to add headers to your HTTP request Some websites 1 dislike being browsed by programs or send different versions to different browsers 2 By default urllib identifies itself as Python urllib x y where x and y are the major and minor version numbers of the Python release e g Python urllib 2 5 which may confuse the site or just plain not work The way a browser identifies itself is through the User Agent header 3 When you create a Request object you can pass a dictionary of headers in The following example makes the same request as above but identifies itself as a version of Internet Explorer 4 import urllib parse import urllib request url http www someserver com cgi bin register cgi user_agent Mozilla 5 0 Windows NT 6 1 Win64 x64 values name Michael Foord location Northampton language Python headers User Agent user_agent data urllib parse urlencode values data data encode ascii req urllib request Request url data headers with urllib request urlopen req as response the_page response read The response also has two useful methods See the section on info and geturl which comes after we have a look at what happens when things go wrong Handling Exceptions urlopen raises URLError when it cannot handle a response though as usual with Python APIs built in exceptions such as ValueError TypeError etc may also be raised HTTPError is the subclass of URLError raised in the specific case of HTTP URLs The exception classes are exported from the urllib error module URLError Often URLError is raised because there is no network connection no route to the specified server or the specified server doesn t exist In this case the exception raised will have a reason attribute which is a tuple containing an error code and a text error message e g req urllib request Request http www pretend_server org try urllib request urlopen req except urllib error URLError as e print e reason 4 getaddrinfo failed HTTPError Every HTTP response from the server contains a numeric status code Sometimes the status code indicates that the server is unable to fulfil the request The default handlers will handle some of these responses for you for example if the response is a redirection that requests the client fetch the document from a different URL urllib will handle that for you For those it can t handle urlopen will raise an HTTPError Typical errors include 404 page not found 403 request forbidden and 401 authentication required See section 10 of RFC 2616 for a reference on all the HTTP error codes The HTTPError instance raised will have an integer code attribute which co
en
null
362
rresponds to the error sent by the server Error Codes Because the default handlers handle redirects codes in the 300 range and codes in the 100 299 range indicate success you will usually only see error codes in the 400 599 range http server BaseHTTPRequestHandler responses is a useful dictionary of response codes in that shows all the response codes used by RFC 2616 The dictionary is reproduced here for convenience Table mapping response codes to messages entries have the form code shortmessage longmessage responses 100 Continue Request received please continue 101 Switching Protocols Switching to new protocol obey Upgrade header 200 OK Request fulfilled document follows 201 Created Document created URL follows 202 Accepted Request accepted processing continues off line 203 Non Authoritative Information Request fulfilled from cache 204 No Content Request fulfilled nothing follows 205 Reset Content Clear input form for further input 206 Partial Content Partial content follows 300 Multiple Choices Object has several resources see URI list 301 Moved Permanently Object moved permanently see URI list 302 Found Object moved temporarily see URI list 303 See Other Object moved see Method and URL list 304 Not Modified Document has not changed since given time 305 Use Proxy You must use proxy specified in Location to access this resource 307 Temporary Redirect Object moved temporarily see URI list 400 Bad Request Bad request syntax or unsupported method 401 Unauthorized No permission see authorization schemes 402 Payment Required No payment see charging schemes 403 Forbidden Request forbidden authorization will not help 404 Not Found Nothing matches the given URI 405 Method Not Allowed Specified method is invalid for this server 406 Not Acceptable URI not available in preferred format 407 Proxy Authentication Required You must authenticate with this proxy before proceeding 408 Request Timeout Request timed out try again later 409 Conflict Request conflict 410 Gone URI no longer exists and has been permanently removed 411 Length Required Client must specify Content Length 412 Precondition Failed Precondition in headers is false 413 Request Entity Too Large Entity is too large 414 Request URI Too Long URI is too long 415 Unsupported Media Type Entity body in unsupported format 416 Requested Range Not Satisfiable Cannot satisfy request range 417 Expectation Failed Expect condition could not be satisfied 500 Internal Server Error Server got itself in trouble 501 Not Implemented Server does not support this operation 502 Bad Gateway Invalid responses from another server proxy 503 Service Unavailable The server cannot process the request due to a high load 504 Gateway Timeout The gateway server did not receive a timely response 505 HTTP Version Not Supported Cannot fulfill request When an error is raised the server responds by returning an HTTP error code and an error page You can use the HTTPError instance as a response on the page returned This means that as well as the code attribute it also has read geturl and info methods as returned by the urllib response module req urllib request Request http www python org fish html try urllib request urlopen req except urllib error HTTPError as e print e code print e read 404 b DOCTYPE html PUBLIC W3C DTD XHTML 1 0 Transitional EN http www w3 org TR xhtml1 DTD xhtml1 transitional dtd n n n html title Page Not Found title n Wrapping it Up So if you want to be prepared for HTTPError or URLError there are two basic approaches I prefer the second approach Number 1 from urllib request import Request urlopen from urllib error import URLError HTTPError req Request someurl try response urlopen req except HTTPError as e print The server couldn t fulfill the request print Error code e code except URLError as e print We failed to reach a server print Reason e reason else everything is fine Note The except HTTPError must come first otherwise except URLError will also catch an HTTPError Number 2 from urllib request import Request urlopen from urllib error import URLError req Request someurl try response ur
en
null
363
lopen req except URLError as e if hasattr e reason print We failed to reach a server print Reason e reason elif hasattr e code print The server couldn t fulfill the request print Error code e code else everything is fine info and geturl The response returned by urlopen or the HTTPError instance has two useful methods info and geturl and is defined in the module urllib response geturl this returns the real URL of the page fetched This is useful because urlopen or the opener object used may have followed a redirect The URL of the page fetched may not be the same as the URL requested info this returns a dictionary like object that describes the page fetched particularly the headers sent by the server It is currently an http client HTTPMessage instance Typical headers include Content length Content type and so on See the Quick Reference to HTTP Headers for a useful listing of HTTP headers with brief explanations of their meaning and use Openers and Handlers When you fetch a URL you use an opener an instance of the perhaps confusingly named urllib request OpenerDirector Normally we have been using the default opener via urlopen but you can create custom openers Openers use handlers All the heavy lifting is done by the handlers Each handler knows how to open URLs for a particular URL scheme http ftp etc or how to handle an aspect of URL opening for example HTTP redirections or HTTP cookies You will want to create openers if you want to fetch URLs with specific handlers installed for example to get an opener that handles cookies or to get an opener that does not handle redirections To create an opener instantiate an OpenerDirector and then call add_handler some_handler_instance repeatedly Alternatively you can use build_opener which is a convenience function for creating opener objects with a single function call build_opener adds several handlers by default but provides a quick way to add more and or override the default handlers Other sorts of handlers you might want to can handle proxies authentication and other common but slightly specialised situations install_opener can be used to make an opener object the global default opener This means that calls to urlopen will use the opener you have installed Opener objects have an open method which can be called directly to fetch urls in the same way as the urlopen function there s no need to call install_opener except as a convenience Basic Authentication To illustrate creating and installing a handler we will use the HTTPBasicAuthHandler For a more detailed discussion of this subject including an explanation of how Basic Authentication works see the Basic Authentication Tutorial When authentication is required the server sends a header as well as the 401 error code requesting authentication This specifies the authentication scheme and a realm The header looks like WWW Authenticate SCHEME realm REALM e g WWW Authenticate Basic realm cPanel Users The client should then retry the request with the appropriate name and password for the realm included as a header in the request This is basic authentication In order to simplify this process we can create an instance of HTTPBasicAuthHandler and an opener to use this handler The HTTPBasicAuthHandler uses an object called a password manager to handle the mapping of URLs and realms to passwords and usernames If you know what the realm is from the authentication header sent by the server then you can use a HTTPPasswordMgr Frequently one doesn t care what the realm is In that case it is convenient to use HTTPPasswordMgrWithDefaultRealm This allows you to specify a default username and password for a URL This will be supplied in the absence of you providing an alternative combination for a specific realm We indicate this by providing None as the realm argument to the add_password method The top level URL is the first URL that requires authentication URLs deeper than the URL you pass to add_password will also match create a password manager password_mgr urllib request HTTPPasswordMgrWithDefaultRealm Add the username and password If we knew the
en
null
364
realm we could use it instead of None top_level_url http example com foo password_mgr add_password None top_level_url username password handler urllib request HTTPBasicAuthHandler password_mgr create opener OpenerDirector instance opener urllib request build_opener handler use the opener to fetch a URL opener open a_url Install the opener Now all calls to urllib request urlopen use our opener urllib request install_opener opener Note In the above example we only supplied our HTTPBasicAuthHandler to build_opener By default openers have the handlers for normal situations ProxyHandler if a proxy setting such as an http_proxy environment variable is set UnknownHandler HTTPHandler HTTPDefaultErrorHandler HTTPRedirectHandler FTPHandler FileHandler DataHandler HTTPErrorProcessor top_level_url is in fact either a full URL including the http scheme component and the hostname and optionally the port number e g http example com or an authority i e the hostname optionally including the port number e g example com or example com 8080 the latter example includes a port number The authority if present must NOT contain the userinfo component for example joe password example com is not correct Proxies urllib will auto detect your proxy settings and use those This is through the ProxyHandler which is part of the normal handler chain when a proxy setting is detected Normally that s a good thing but there are occasions when it may not be helpful 5 One way to do this is to setup our own ProxyHandler with no proxies defined This is done using similar steps to setting up a Basic Authentication handler proxy_support urllib request ProxyHandler opener urllib request build_opener proxy_support urllib request install_opener opener Note Currently urllib request does not support fetching of https locations through a proxy However this can be enabled by extending urllib request as shown in the recipe 6 Note HTTP_PROXY will be ignored if a variable REQUEST_METHOD is set see the documentation on getproxies Sockets and Layers The Python support for fetching resources from the web is layered urllib uses the http client library which in turn uses the socket library As of Python 2 3 you can specify how long a socket should wait for a response before timing out This can be useful in applications which have to fetch web pages By default the socket module has no timeout and can hang Currently the socket timeout is not exposed at the http client or urllib request levels However you can set the default timeout globally for all sockets using import socket import urllib request timeout in seconds timeout 10 socket setdefaulttimeout timeout this call to urllib request urlopen now uses the default timeout we have set in the socket module req urllib request Request http www voidspace org uk response urllib request urlopen req Footnotes This document was reviewed and revised by John Lee 1 Google for example 2 Browser sniffing is a very bad practice for website design building sites using web standards is much more sensible Unfortunately a lot of sites still send different versions to different browsers 3 The user agent for MSIE 6 is Mozilla 4 0 compatible MSIE 6 0 Windows NT 5 1 SV1 NET CLR 1 1 4322 4 For details of more HTTP request headers see Quick Reference to HTTP Headers 5 In my case I have to use a proxy to access the internet at work If you attempt to fetch localhost URLs through this proxy it blocks them IE is set to use the proxy which urllib picks up on In order to test scripts with a localhost server I have to prevent urllib from using the proxy 6 urllib opener for SSL proxy CONNECT method ASPN Cookbook Recipe
en
null
365
concurrent futures Launching parallel tasks New in version 3 2 Source code Lib concurrent futures thread py and Lib concurrent futures process py The concurrent futures module provides a high level interface for asynchronously executing callables The asynchronous execution can be performed with threads using ThreadPoolExecutor or separate processes using ProcessPoolExecutor Both implement the same interface which is defined by the abstract Executor class Availability not Emscripten not WASI This module does not work or is not available on WebAssembly platforms wasm32 emscripten and wasm32 wasi See WebAssembly platforms for more information Executor Objects class concurrent futures Executor An abstract class that provides methods to execute calls asynchronously It should not be used directly but through its concrete subclasses submit fn args kwargs Schedules the callable fn to be executed as fn args kwargs and returns a Future object representing the execution of the callable with ThreadPoolExecutor max_workers 1 as executor future executor submit pow 323 1235 print future result map fn iterables timeout None chunksize 1 Similar to map fn iterables except the iterables are collected immediately rather than lazily fn is executed asynchronously and several calls to fn may be made concurrently The returned iterator raises a TimeoutError if __next__ is called and the result isn t available after timeout seconds from the original call to Executor map timeout can be an int or a float If timeout is not specified or None there is no limit to the wait time If a fn call raises an exception then that exception will be raised when its value is retrieved from the iterator When using ProcessPoolExecutor this method chops iterables into a number of chunks which it submits to the pool as separate tasks The approximate size of these chunks can be specified by setting chunksize to a positive integer For very long iterables using a large value for chunksize can significantly improve performance compared to the default size of 1 With ThreadPoolExecutor chunksize has no effect Changed in version 3 5 Added the chunksize argument shutdown wait True cancel_futures False Signal the executor that it should free any resources that it is using when the currently pending futures are done executing Calls to Executor submit and Executor map made after shutdown will raise RuntimeError If wait is True then this method will not return until all the pending futures are done executing and the resources associated with the executor have been freed If wait is False then this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing Regardless of the value of wait the entire Python program will not exit until all pending futures are done executing If cancel_futures is True this method will cancel all pending futures that the executor has not started running Any futures that are completed or running won t be cancelled regardless of the value of cancel_futures If both cancel_futures and wait are True all futures that the executor has started running will be completed prior to this method returning The remaining futures are cancelled You can avoid having to call this method explicitly if you use the with statement which will shutdown the Executor waiting as if Executor shutdown were called with wait set to True import shutil with ThreadPoolExecutor max_workers 4 as e e submit shutil copy src1 txt dest1 txt e submit shutil copy src2 txt dest2 txt e submit shutil copy src3 txt dest3 txt e submit shutil copy src4 txt dest4 txt Changed in version 3 9 Added cancel_futures ThreadPoolExecutor ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously Deadlocks can occur when the callable associated with a Future waits on the results of another Future For example import time def wait_on_b time sleep 5 print b result b will never complete because it is waiting on a return 5 def wait_on_a time sleep 5 print a result a will never complete because it is w
en
null
366
aiting on b return 6 executor ThreadPoolExecutor max_workers 2 a executor submit wait_on_b b executor submit wait_on_a And def wait_on_future f executor submit pow 5 2 This will never complete because there is only one worker thread and it is executing this function print f result executor ThreadPoolExecutor max_workers 1 executor submit wait_on_future class concurrent futures ThreadPoolExecutor max_workers None thread_name_prefix initializer None initargs An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously All threads enqueued to ThreadPoolExecutor will be joined before the interpreter can exit Note that the exit handler which does this is executed before any exit handlers added using atexit This means exceptions in the main thread must be caught and handled in order to signal threads to exit gracefully For this reason it is recommended that ThreadPoolExecutor not be used for long running tasks initializer is an optional callable that is called at the start of each worker thread initargs is a tuple of arguments passed to the initializer Should initializer raise an exception all currently pending jobs will raise a BrokenThreadPool as well as any attempt to submit more jobs to the pool Changed in version 3 5 If max_workers is None or not given it will default to the number of processors on the machine multiplied by 5 assuming that ThreadPoolExecutor is often used to overlap I O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor Changed in version 3 6 Added the thread_name_prefix parameter to allow users to control the threading Thread names for worker threads created by the pool for easier debugging Changed in version 3 7 Added the initializer and initargs arguments Changed in version 3 8 Default value of max_workers is changed to min 32 os cpu_count 4 This default value preserves at least 5 workers for I O bound tasks It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL And it avoids using very large resources implicitly on many core machines ThreadPoolExecutor now reuses idle worker threads before starting max_workers worker threads too ThreadPoolExecutor Example import concurrent futures import urllib request URLS http www foxnews com http www cnn com http europe wsj com http www bbc co uk http nonexistant subdomain python org Retrieve a single page and report the URL and contents def load_url url timeout with urllib request urlopen url timeout timeout as conn return conn read We can use a with statement to ensure threads are cleaned up promptly with concurrent futures ThreadPoolExecutor max_workers 5 as executor Start the load operations and mark each future with its URL future_to_url executor submit load_url url 60 url for url in URLS for future in concurrent futures as_completed future_to_url url future_to_url future try data future result except Exception as exc print r generated an exception s url exc else print r page is d bytes url len data ProcessPoolExecutor The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously ProcessPoolExecutor uses the multiprocessing module which allows it to side step the Global Interpreter Lock but also means that only picklable objects can be executed and returned The __main__ module must be importable by worker subprocesses This means that ProcessPoolExecutor will not work in the interactive interpreter Calling Executor or Future methods from a callable submitted to a ProcessPoolExecutor will result in deadlock class concurrent futures ProcessPoolExecutor max_workers None mp_context None initializer None initargs max_tasks_per_child None An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes If max_workers is None or not given it will default to the number of processors on the machine If max_workers is less than or equal to 0 then a ValueError will be raised On Windows max_workers must be less than or equal to 61 If it is not then ValueError will
en
null
367
be raised If max_workers is None then the default chosen will be at most 61 even if more processors are available mp_context can be a multiprocessing context or None It will be used to launch the workers If mp_context is None or not given the default multiprocessing context is used See Contexts and start methods initializer is an optional callable that is called at the start of each worker process initargs is a tuple of arguments passed to the initializer Should initializer raise an exception all currently pending jobs will raise a BrokenProcessPool as well as any attempt to submit more jobs to the pool max_tasks_per_child is an optional argument that specifies the maximum number of tasks a single process can execute before it will exit and be replaced with a fresh worker process By default max_tasks_per_child is None which means worker processes will live as long as the pool When a max is specified the spawn multiprocessing start method will be used by default in absence of a mp_context parameter This feature is incompatible with the fork start method Changed in version 3 3 When one of the worker processes terminates abruptly a BrokenProcessPool error is now raised Previously behaviour was undefined but operations on the executor or its futures would often freeze or deadlock Changed in version 3 7 The mp_context argument was added to allow users to control the start_method for worker processes created by the pool Added the initializer and initargs arguments Note The default multiprocessing start method see Contexts and start methods will change away from fork in Python 3 14 Code that requires fork be used for their ProcessPoolExecutor should explicitly specify that by passing a mp_context multiprocessing get_context fork parameter Changed in version 3 11 The max_tasks_per_child argument was added to allow users to control the lifetime of workers in the pool Changed in version 3 12 On POSIX systems if your application has multiple threads and the multiprocessing context uses the fork start method The os fork function called internally to spawn workers may raise a DeprecationWarning Pass a mp_context configured to use a different start method See the os fork documentation for further explanation ProcessPoolExecutor Example import concurrent futures import math PRIMES 112272535095293 112582705942171 112272535095293 115280095190773 115797848077099 1099726899285419 def is_prime n if n 2 return False if n 2 return True if n 2 0 return False sqrt_n int math floor math sqrt n for i in range 3 sqrt_n 1 2 if n i 0 return False return True def main with concurrent futures ProcessPoolExecutor as executor for number prime in zip PRIMES executor map is_prime PRIMES print d is prime s number prime if __name__ __main__ main Future Objects The Future class encapsulates the asynchronous execution of a callable Future instances are created by Executor submit class concurrent futures Future Encapsulates the asynchronous execution of a callable Future instances are created by Executor submit and should not be created directly except for testing cancel Attempt to cancel the call If the call is currently being executed or finished running and cannot be cancelled then the method will return False otherwise the call will be cancelled and the method will return True cancelled Return True if the call was successfully cancelled running Return True if the call is currently being executed and cannot be cancelled done Return True if the call was successfully cancelled or finished running result timeout None Return the value returned by the call If the call hasn t yet completed then this method will wait up to timeout seconds If the call hasn t completed in timeout seconds then a TimeoutError will be raised timeout can be an int or float If timeout is not specified or None there is no limit to the wait time If the future is cancelled before completing then CancelledError will be raised If the call raised an exception this method will raise the same exception exception timeout None Return the exception raised by the call If the call hasn t yet complet
en
null
368
ed then this method will wait up to timeout seconds If the call hasn t completed in timeout seconds then a TimeoutError will be raised timeout can be an int or float If timeout is not specified or None there is no limit to the wait time If the future is cancelled before completing then CancelledError will be raised If the call completed without raising None is returned add_done_callback fn Attaches the callable fn to the future fn will be called with the future as its only argument when the future is cancelled or finishes running Added callables are called in the order that they were added and are always called in a thread belonging to the process that added them If the callable raises an Exception subclass it will be logged and ignored If the callable raises a BaseException subclass the behavior is undefined If the future has already completed or been cancelled fn will be called immediately The following Future methods are meant for use in unit tests and Executor implementations set_running_or_notify_cancel This method should only be called by Executor implementations before executing the work associated with the Future and by unit tests If the method returns False then the Future was cancelled i e Future cancel was called and returned True Any threads waiting on the Future completing i e through as_completed or wait will be woken up If the method returns True then the Future was not cancelled and has been put in the running state i e calls to Future running will return True This method can only be called once and cannot be called after Future set_result or Future set_exception have been called set_result result Sets the result of the work associated with the Future to result This method should only be used by Executor implementations and unit tests Changed in version 3 8 This method raises concurrent futures InvalidStateError if the Future is already done set_exception exception Sets the result of the work associated with the Future to the Exception exception This method should only be used by Executor implementations and unit tests Changed in version 3 8 This method raises concurrent futures InvalidStateError if the Future is already done Module Functions concurrent futures wait fs timeout None return_when ALL_COMPLETED Wait for the Future instances possibly created by different Executor instances given by fs to complete Duplicate futures given to fs are removed and will be returned only once Returns a named 2 tuple of sets The first set named done contains the futures that completed finished or cancelled futures before the wait completed The second set named not_done contains the futures that did not complete pending or running futures timeout can be used to control the maximum number of seconds to wait before returning timeout can be an int or float If timeout is not specified or None there is no limit to the wait time return_when indicates when this function should return It must be one of the following constants Constant Description concurrent futures FIRST_COMPLETED The function will return when any future finishes or is cancelled concurrent futures FIRST_EXCEPTION The function will return when any future finishes by raising an exception If no future raises an exception then it is equivalent to ALL_COMPLETED concurrent futures ALL_COMPLETED The function will return when all futures finish or are cancelled concurrent futures as_completed fs timeout None Returns an iterator over the Future instances possibly created by different Executor instances given by fs that yields futures as they complete finished or cancelled futures Any futures given by fs that are duplicated will be returned once Any futures that completed before as_completed is called will be yielded first The returned iterator raises a TimeoutError if __next__ is called and the result isn t available after timeout seconds from the original call to as_completed timeout can be an int or float If timeout is not specified or None there is no limit to the wait time See also PEP 3148 futures execute computations asynchronously The proposal which described thi
en
null
369
s feature for inclusion in the Python standard library Exception classes exception concurrent futures CancelledError Raised when a future is cancelled exception concurrent futures TimeoutError A deprecated alias of TimeoutError raised when a future operation exceeds the given timeout Changed in version 3 11 This class was made an alias of TimeoutError exception concurrent futures BrokenExecutor Derived from RuntimeError this exception class is raised when an executor is broken for some reason and cannot be used to submit or execute new tasks New in version 3 7 exception concurrent futures InvalidStateError Raised when an operation is performed on a future that is not allowed in the current state New in version 3 8 exception concurrent futures thread BrokenThreadPool Derived from BrokenExecutor this exception class is raised when one of the workers of a ThreadPoolExecutor has failed initializing New in version 3 7 exception concurrent futures process BrokenProcessPool Derived from BrokenExecutor formerly RuntimeError this exception class is raised when one of the workers of a ProcessPoolExecutor has terminated in a non clean fashion for example if it was killed from the outside New in version 3 3
en
null
370
Context Variables Objects New in version 3 7 Changed in version 3 7 1 Note In Python 3 7 1 the signatures of all context variables C APIs were changed to use PyObject pointers instead of PyContext PyContextVar and PyContextToken e g in 3 7 0 PyContext PyContext_New void in 3 7 1 PyObject PyContext_New void See bpo 34762 for more details This section details the public C API for the contextvars module type PyContext The C structure used to represent a contextvars Context object type PyContextVar The C structure used to represent a contextvars ContextVar object type PyContextToken The C structure used to represent a contextvars Token object PyTypeObject PyContext_Type The type object representing the context type PyTypeObject PyContextVar_Type The type object representing the context variable type PyTypeObject PyContextToken_Type The type object representing the context variable token type Type check macros int PyContext_CheckExact PyObject o Return true if o is of type PyContext_Type o must not be NULL This function always succeeds int PyContextVar_CheckExact PyObject o Return true if o is of type PyContextVar_Type o must not be NULL This function always succeeds int PyContextToken_CheckExact PyObject o Return true if o is of type PyContextToken_Type o must not be NULL This function always succeeds Context object management functions PyObject PyContext_New void Return value New reference Create a new empty context object Returns NULL if an error has occurred PyObject PyContext_Copy PyObject ctx Return value New reference Create a shallow copy of the passed ctx context object Returns NULL if an error has occurred PyObject PyContext_CopyCurrent void Return value New reference Create a shallow copy of the current thread context Returns NULL if an error has occurred int PyContext_Enter PyObject ctx Set ctx as the current context for the current thread Returns 0 on success and 1 on error int PyContext_Exit PyObject ctx Deactivate the ctx context and restore the previous context as the current context for the current thread Returns 0 on success and 1 on error Context variable functions PyObject PyContextVar_New const char name PyObject def Return value New reference Create a new ContextVar object The name parameter is used for introspection and debug purposes The def parameter specifies a default value for the context variable or NULL for no default If an error has occurred this function returns NULL int PyContextVar_Get PyObject var PyObject default_value PyObject value Get the value of a context variable Returns 1 if an error has occurred during lookup and 0 if no error occurred whether or not a value was found If the context variable was found value will be a pointer to it If the context variable was not found value will point to default_value if not NULL the default value of var if not NULL NULL Except for NULL the function returns a new reference PyObject PyContextVar_Set PyObject var PyObject value Return value New reference Set the value of var to value in the current context Returns a new token object for this change or NULL if an error has occurred int PyContextVar_Reset PyObject var PyObject token Reset the state of the var context variable to that it was in before PyContextVar_Set that returned the token was called This function returns 0 on success and 1 on error
en
null
371
Old Buffer Protocol Deprecated since version 3 0 These functions were part of the old buffer protocol API in Python 2 In Python 3 this protocol doesn t exist anymore but the functions are still exposed to ease porting 2 x code They act as a compatibility wrapper around the new buffer protocol but they don t give you control over the lifetime of the resources acquired when a buffer is exported Therefore it is recommended that you call PyObject_GetBuffer or the y or w format codes with the PyArg_ParseTuple family of functions to get a buffer view over an object and PyBuffer_Release when the buffer view can be released int PyObject_AsCharBuffer PyObject obj const char buffer Py_ssize_t buffer_len Part of the Stable ABI Returns a pointer to a read only memory location usable as character based input The obj argument must support the single segment character buffer interface On success returns 0 sets buffer to the memory location and buffer_len to the buffer length Returns 1 and sets a TypeError on error int PyObject_AsReadBuffer PyObject obj const void buffer Py_ssize_t buffer_len Part of the Stable ABI Returns a pointer to a read only memory location containing arbitrary data The obj argument must support the single segment readable buffer interface On success returns 0 sets buffer to the memory location and buffer_len to the buffer length Returns 1 and sets a TypeError on error int PyObject_CheckReadBuffer PyObject o Part of the Stable ABI Returns 1 if o supports the single segment readable buffer interface Otherwise returns 0 This function always succeeds Note that this function tries to get and release a buffer and exceptions which occur while calling corresponding functions will get suppressed To get error reporting use PyObject_GetBuffer instead int PyObject_AsWriteBuffer PyObject obj void buffer Py_ssize_t buffer_len Part of the Stable ABI Returns a pointer to a writable memory location The obj argument must support the single segment character buffer interface On success returns 0 sets buffer to the memory location and buffer_len to the buffer length Returns 1 and sets a TypeError on error
en
null
372
Coroutines and Tasks This section outlines high level asyncio APIs to work with coroutines and Tasks Coroutines Awaitables Creating Tasks Task Cancellation Task Groups Sleeping Running Tasks Concurrently Eager Task Factory Shielding From Cancellation Timeouts Waiting Primitives Running in Threads Scheduling From Other Threads Introspection Task Object Coroutines Source code Lib asyncio coroutines py Coroutines declared with the async await syntax is the preferred way of writing asyncio applications For example the following snippet of code prints hello waits 1 second and then prints world import asyncio async def main print hello await asyncio sleep 1 print world asyncio run main hello world Note that simply calling a coroutine will not schedule it to be executed main coroutine object main at 0x1053bb7c8 To actually run a coroutine asyncio provides the following mechanisms The asyncio run function to run the top level entry point main function see the above example Awaiting on a coroutine The following snippet of code will print hello after waiting for 1 second and then print world after waiting for another 2 seconds import asyncio import time async def say_after delay what await asyncio sleep delay print what async def main print f started at time strftime X await say_after 1 hello await say_after 2 world print f finished at time strftime X asyncio run main Expected output started at 17 13 52 hello world finished at 17 13 55 The asyncio create_task function to run coroutines concurrently as asyncio Tasks Let s modify the above example and run two say_after coroutines concurrently async def main task1 asyncio create_task say_after 1 hello task2 asyncio create_task say_after 2 world print f started at time strftime X Wait until both tasks are completed should take around 2 seconds await task1 await task2 print f finished at time strftime X Note that expected output now shows that the snippet runs 1 second faster than before started at 17 14 32 hello world finished at 17 14 34 The asyncio TaskGroup class provides a more modern alternative to create_task Using this API the last example becomes async def main async with asyncio TaskGroup as tg task1 tg create_task say_after 1 hello task2 tg create_task say_after 2 world print f started at time strftime X The await is implicit when the context manager exits print f finished at time strftime X The timing and output should be the same as for the previous version New in version 3 11 asyncio TaskGroup Awaitables We say that an object is an awaitable object if it can be used in an await expression Many asyncio APIs are designed to accept awaitables There are three main types of awaitable objects coroutines Tasks and Futures Coroutines Python coroutines are awaitables and therefore can be awaited from other coroutines import asyncio async def nested return 42 async def main Nothing happens if we just call nested A coroutine object is created but not awaited so it won t run at all nested Let s do it differently now and await it print await nested will print 42 asyncio run main Important In this documentation the term coroutine can be used for two closely related concepts a coroutine function an async def function a coroutine object an object returned by calling a coroutine function Tasks Tasks are used to schedule coroutines concurrently When a coroutine is wrapped into a Task with functions like asyncio create_task the coroutine is automatically scheduled to run soon import asyncio async def nested return 42 async def main Schedule nested to run soon concurrently with main task asyncio create_task nested task can now be used to cancel nested or can simply be awaited to wait until it is complete await task asyncio run main Futures A Future is a special low level awaitable object that represents an eventual result of an asynchronous operation When a Future object is awaited it means that the coroutine will wait until the Future is resolved in some other place Future objects in asyncio are needed to allow callback based code to be used with async await Normally there is no need to cre
en
null
373
ate Future objects at the application level code Future objects sometimes exposed by libraries and some asyncio APIs can be awaited async def main await function_that_returns_a_future_object this is also valid await asyncio gather function_that_returns_a_future_object some_python_coroutine A good example of a low level function that returns a Future object is loop run_in_executor Creating Tasks Source code Lib asyncio tasks py asyncio create_task coro name None context None Wrap the coro coroutine into a Task and schedule its execution Return the Task object If name is not None it is set as the name of the task using Task set_name An optional keyword only context argument allows specifying a custom contextvars Context for the coro to run in The current context copy is created when no context is provided The task is executed in the loop returned by get_running_loop RuntimeError is raised if there is no running loop in current thread Note asyncio TaskGroup create_task is a new alternative leveraging structural concurrency it allows for waiting for a group of related tasks with strong safety guarantees Important Save a reference to the result of this function to avoid a task disappearing mid execution The event loop only keeps weak references to tasks A task that isn t referenced elsewhere may get garbage collected at any time even before it s done For reliable fire and forget background tasks gather them in a collection background_tasks set for i in range 10 task asyncio create_task some_coro param i Add task to the set This creates a strong reference background_tasks add task To prevent keeping references to finished tasks forever make each task remove its own reference from the set after completion task add_done_callback background_tasks discard New in version 3 7 Changed in version 3 8 Added the name parameter Changed in version 3 11 Added the context parameter Task Cancellation Tasks can easily and safely be cancelled When a task is cancelled asyncio CancelledError will be raised in the task at the next opportunity It is recommended that coroutines use try finally blocks to robustly perform clean up logic In case asyncio CancelledError is explicitly caught it should generally be propagated when clean up is complete asyncio CancelledError directly subclasses BaseException so most code will not need to be aware of it The asyncio components that enable structured concurrency like asyncio TaskGroup and asyncio timeout are implemented using cancellation internally and might misbehave if a coroutine swallows asyncio CancelledError Similarly user code should not generally call uncancel However in cases when suppressing asyncio CancelledError is truly desired it is necessary to also call uncancel to completely remove the cancellation state Task Groups Task groups combine a task creation API with a convenient and reliable way to wait for all tasks in the group to finish class asyncio TaskGroup An asynchronous context manager holding a group of tasks Tasks can be added to the group using create_task All tasks are awaited when the context manager exits New in version 3 11 create_task coro name None context None Create a task in this task group The signature matches that of asyncio create_task Example async def main async with asyncio TaskGroup as tg task1 tg create_task some_coro task2 tg create_task another_coro print f Both tasks have completed now task1 result task2 result The async with statement will wait for all tasks in the group to finish While waiting new tasks may still be added to the group for example by passing tg into one of the coroutines and calling tg create_task in that coroutine Once the last task has finished and the async with block is exited no new tasks may be added to the group The first time any of the tasks belonging to the group fails with an exception other than asyncio CancelledError the remaining tasks in the group are cancelled No further tasks can then be added to the group At this point if the body of the async with statement is still active i e __aexit__ hasn t been called yet the task directly c
en
null
374
ontaining the async with statement is also cancelled The resulting asyncio CancelledError will interrupt an await but it will not bubble out of the containing async with statement Once all tasks have finished if any tasks have failed with an exception other than asyncio CancelledError those exceptions are combined in an ExceptionGroup or BaseExceptionGroup as appropriate see their documentation which is then raised Two base exceptions are treated specially If any task fails with KeyboardInterrupt or SystemExit the task group still cancels the remaining tasks and waits for them but then the initial KeyboardInterrupt or SystemExit is re raised instead of ExceptionGroup or BaseExceptionGroup If the body of the async with statement exits with an exception so __aexit__ is called with an exception set this is treated the same as if one of the tasks failed the remaining tasks are cancelled and then waited for and non cancellation exceptions are grouped into an exception group and raised The exception passed into __aexit__ unless it is asyncio CancelledError is also included in the exception group The same special case is made for KeyboardInterrupt and SystemExit as in the previous paragraph Sleeping coroutine asyncio sleep delay result None Block for delay seconds If result is provided it is returned to the caller when the coroutine completes sleep always suspends the current task allowing other tasks to run Setting the delay to 0 provides an optimized path to allow other tasks to run This can be used by long running functions to avoid blocking the event loop for the full duration of the function call Example of coroutine displaying the current date every second for 5 seconds import asyncio import datetime async def display_date loop asyncio get_running_loop end_time loop time 5 0 while True print datetime datetime now if loop time 1 0 end_time break await asyncio sleep 1 asyncio run display_date Changed in version 3 10 Removed the loop parameter Running Tasks Concurrently awaitable asyncio gather aws return_exceptions False Run awaitable objects in the aws sequence concurrently If any awaitable in aws is a coroutine it is automatically scheduled as a Task If all awaitables are completed successfully the result is an aggregate list of returned values The order of result values corresponds to the order of awaitables in aws If return_exceptions is False default the first raised exception is immediately propagated to the task that awaits on gather Other awaitables in the aws sequence won t be cancelled and will continue to run If return_exceptions is True exceptions are treated the same as successful results and aggregated in the result list If gather is cancelled all submitted awaitables that have not completed yet are also cancelled If any Task or Future from the aws sequence is cancelled it is treated as if it raised CancelledError the gather call is not cancelled in this case This is to prevent the cancellation of one submitted Task Future to cause other Tasks Futures to be cancelled Note A new alternative to create and run tasks concurrently and wait for their completion is asyncio TaskGroup TaskGroup provides stronger safety guarantees than gather for scheduling a nesting of subtasks if a task or a subtask a task scheduled by a task raises an exception TaskGroup will while gather will not cancel the remaining scheduled tasks Example import asyncio async def factorial name number f 1 for i in range 2 number 1 print f Task name Compute factorial number currently i i await asyncio sleep 1 f i print f Task name factorial number f return f async def main Schedule three calls concurrently L await asyncio gather factorial A 2 factorial B 3 factorial C 4 print L asyncio run main Expected output Task A Compute factorial 2 currently i 2 Task B Compute factorial 3 currently i 2 Task C Compute factorial 4 currently i 2 Task A factorial 2 2 Task B Compute factorial 3 currently i 3 Task C Compute factorial 4 currently i 3 Task B factorial 3 6 Task C Compute factorial 4 currently i 4 Task C factorial 4 24 2 6 24 Note If return_exceptions i
en
null
375
s False cancelling gather after it has been marked done won t cancel any submitted awaitables For instance gather can be marked done after propagating an exception to the caller therefore calling gather cancel after catching an exception raised by one of the awaitables from gather won t cancel any other awaitables Changed in version 3 7 If the gather itself is cancelled the cancellation is propagated regardless of return_exceptions Changed in version 3 10 Removed the loop parameter Deprecated since version 3 10 Deprecation warning is emitted if no positional arguments are provided or not all positional arguments are Future like objects and there is no running event loop Eager Task Factory asyncio eager_task_factory loop coro name None context None A task factory for eager task execution When using this factory via loop set_task_factory asyncio eager_task_factory coroutines begin execution synchronously during Task construction Tasks are only scheduled on the event loop if they block This can be a performance improvement as the overhead of loop scheduling is avoided for coroutines that complete synchronously A common example where this is beneficial is coroutines which employ caching or memoization to avoid actual I O when possible Note Immediate execution of the coroutine is a semantic change If the coroutine returns or raises the task is never scheduled to the event loop If the coroutine execution blocks the task is scheduled to the event loop This change may introduce behavior changes to existing applications For example the application s task execution order is likely to change New in version 3 12 asyncio create_eager_task_factory custom_task_constructor Create an eager task factory similar to eager_task_factory using the provided custom_task_constructor when creating a new task instead of the default Task custom_task_constructor must be a callable with the signature matching the signature of Task __init__ The callable must return a asyncio Task compatible object This function returns a callable intended to be used as a task factory of an event loop via loop set_task_factory factory New in version 3 12 Shielding From Cancellation awaitable asyncio shield aw Protect an awaitable object from being cancelled If aw is a coroutine it is automatically scheduled as a Task The statement task asyncio create_task something res await shield task is equivalent to res await something except that if the coroutine containing it is cancelled the Task running in something is not cancelled From the point of view of something the cancellation did not happen Although its caller is still cancelled so the await expression still raises a CancelledError If something is cancelled by other means i e from within itself that would also cancel shield If it is desired to completely ignore cancellation not recommended the shield function should be combined with a try except clause as follows task asyncio create_task something try res await shield task except CancelledError res None Important Save a reference to tasks passed to this function to avoid a task disappearing mid execution The event loop only keeps weak references to tasks A task that isn t referenced elsewhere may get garbage collected at any time even before it s done Changed in version 3 10 Removed the loop parameter Deprecated since version 3 10 Deprecation warning is emitted if aw is not Future like object and there is no running event loop Timeouts asyncio timeout delay Return an asynchronous context manager that can be used to limit the amount of time spent waiting on something delay can either be None or a float int number of seconds to wait If delay is None no time limit will be applied this can be useful if the delay is unknown when the context manager is created In either case the context manager can be rescheduled after creation using Timeout reschedule Example async def main async with asyncio timeout 10 await long_running_task If long_running_task takes more than 10 seconds to complete the context manager will cancel the current task and handle the resulting asyncio Cancelle
en
null
376
dError internally transforming it into a TimeoutError which can be caught and handled Note The asyncio timeout context manager is what transforms the asyncio CancelledError into a TimeoutError which means the TimeoutError can only be caught outside of the context manager Example of catching TimeoutError async def main try async with asyncio timeout 10 await long_running_task except TimeoutError print The long operation timed out but we ve handled it print This statement will run regardless The context manager produced by asyncio timeout can be rescheduled to a different deadline and inspected class asyncio Timeout when An asynchronous context manager for cancelling overdue coroutines when should be an absolute time at which the context should time out as measured by the event loop s clock If when is None the timeout will never trigger If when loop time the timeout will trigger on the next iteration of the event loop when float None Return the current deadline or None if the current deadline is not set reschedule when float None Reschedule the timeout expired bool Return whether the context manager has exceeded its deadline expired Example async def main try We do not know the timeout when starting so we pass None async with asyncio timeout None as cm We know the timeout now so we reschedule it new_deadline get_running_loop time 10 cm reschedule new_deadline await long_running_task except TimeoutError pass if cm expired print Looks like we haven t finished on time Timeout context managers can be safely nested New in version 3 11 asyncio timeout_at when Similar to asyncio timeout except when is the absolute time to stop waiting or None Example async def main loop get_running_loop deadline loop time 20 try async with asyncio timeout_at deadline await long_running_task except TimeoutError print The long operation timed out but we ve handled it print This statement will run regardless New in version 3 11 coroutine asyncio wait_for aw timeout Wait for the aw awaitable to complete with a timeout If aw is a coroutine it is automatically scheduled as a Task timeout can either be None or a float or int number of seconds to wait for If timeout is None block until the future completes If a timeout occurs it cancels the task and raises TimeoutError To avoid the task cancellation wrap it in shield The function will wait until the future is actually cancelled so the total wait time may exceed the timeout If an exception happens during cancellation it is propagated If the wait is cancelled the future aw is also cancelled Example async def eternity Sleep for one hour await asyncio sleep 3600 print yay async def main Wait for at most 1 second try await asyncio wait_for eternity timeout 1 0 except TimeoutError print timeout asyncio run main Expected output timeout Changed in version 3 7 When aw is cancelled due to a timeout wait_for waits for aw to be cancelled Previously it raised TimeoutError immediately Changed in version 3 10 Removed the loop parameter Changed in version 3 11 Raises TimeoutError instead of asyncio TimeoutError Waiting Primitives coroutine asyncio wait aws timeout None return_when ALL_COMPLETED Run Future and Task instances in the aws iterable concurrently and block until the condition specified by return_when The aws iterable must not be empty Returns two sets of Tasks Futures done pending Usage done pending await asyncio wait aws timeout a float or int if specified can be used to control the maximum number of seconds to wait before returning Note that this function does not raise TimeoutError Futures or Tasks that aren t done when the timeout occurs are simply returned in the second set return_when indicates when this function should return It must be one of the following constants Constant Description asyncio FIRST_COMPLETED The function will return when any future finishes or is cancelled asyncio FIRST_EXCEPTION The function will return when any future finishes by raising an exception If no future raises an exception then it is equivalent to ALL_COMPLETED asyncio ALL_COMPLETED The function will return when all futur
en
null
377
es finish or are cancelled Unlike wait_for wait does not cancel the futures when a timeout occurs Changed in version 3 10 Removed the loop parameter Changed in version 3 11 Passing coroutine objects to wait directly is forbidden Changed in version 3 12 Added support for generators yielding tasks asyncio as_completed aws timeout None Run awaitable objects in the aws iterable concurrently Return an iterator of coroutines Each coroutine returned can be awaited to get the earliest next result from the iterable of the remaining awaitables Raises TimeoutError if the timeout occurs before all Futures are done Example for coro in as_completed aws earliest_result await coro Changed in version 3 10 Removed the loop parameter Deprecated since version 3 10 Deprecation warning is emitted if not all awaitable objects in the aws iterable are Future like objects and there is no running event loop Changed in version 3 12 Added support for generators yielding tasks Running in Threads coroutine asyncio to_thread func args kwargs Asynchronously run function func in a separate thread Any args and kwargs supplied for this function are directly passed to func Also the current contextvars Context is propagated allowing context variables from the event loop thread to be accessed in the separate thread Return a coroutine that can be awaited to get the eventual result of func This coroutine function is primarily intended to be used for executing IO bound functions methods that would otherwise block the event loop if they were run in the main thread For example def blocking_io print f start blocking_io at time strftime X Note that time sleep can be replaced with any blocking IO bound operation such as file operations time sleep 1 print f blocking_io complete at time strftime X async def main print f started main at time strftime X await asyncio gather asyncio to_thread blocking_io asyncio sleep 1 print f finished main at time strftime X asyncio run main Expected output started main at 19 50 53 start blocking_io at 19 50 53 blocking_io complete at 19 50 54 finished main at 19 50 54 Directly calling blocking_io in any coroutine would block the event loop for its duration resulting in an additional 1 second of run time Instead by using asyncio to_thread we can run it in a separate thread without blocking the event loop Note Due to the GIL asyncio to_thread can typically only be used to make IO bound functions non blocking However for extension modules that release the GIL or alternative Python implementations that don t have one asyncio to_thread can also be used for CPU bound functions New in version 3 9 Scheduling From Other Threads asyncio run_coroutine_threadsafe coro loop Submit a coroutine to the given event loop Thread safe Return a concurrent futures Future to wait for the result from another OS thread This function is meant to be called from a different OS thread than the one where the event loop is running Example Create a coroutine coro asyncio sleep 1 result 3 Submit the coroutine to a given loop future asyncio run_coroutine_threadsafe coro loop Wait for the result with an optional timeout argument assert future result timeout 3 If an exception is raised in the coroutine the returned Future will be notified It can also be used to cancel the task in the event loop try result future result timeout except TimeoutError print The coroutine took too long cancelling the task future cancel except Exception as exc print f The coroutine raised an exception exc r else print f The coroutine returned result r See the concurrency and multithreading section of the documentation Unlike other asyncio functions this function requires the loop argument to be passed explicitly New in version 3 5 1 Introspection asyncio current_task loop None Return the currently running Task instance or None if no task is running If loop is None get_running_loop is used to get the current loop New in version 3 7 asyncio all_tasks loop None Return a set of not yet finished Task objects run by the loop If loop is None get_running_loop is used for getting current loop New in ver
en
null
378
sion 3 7 asyncio iscoroutine obj Return True if obj is a coroutine object New in version 3 4 Task Object class asyncio Task coro loop None name None context None eager_start False A Future like object that runs a Python coroutine Not thread safe Tasks are used to run coroutines in event loops If a coroutine awaits on a Future the Task suspends the execution of the coroutine and waits for the completion of the Future When the Future is done the execution of the wrapped coroutine resumes Event loops use cooperative scheduling an event loop runs one Task at a time While a Task awaits for the completion of a Future the event loop runs other Tasks callbacks or performs IO operations Use the high level asyncio create_task function to create Tasks or the low level loop create_task or ensure_future functions Manual instantiation of Tasks is discouraged To cancel a running Task use the cancel method Calling it will cause the Task to throw a CancelledError exception into the wrapped coroutine If a coroutine is awaiting on a Future object during cancellation the Future object will be cancelled cancelled can be used to check if the Task was cancelled The method returns True if the wrapped coroutine did not suppress the CancelledError exception and was actually cancelled asyncio Task inherits from Future all of its APIs except Future set_result and Future set_exception An optional keyword only context argument allows specifying a custom contextvars Context for the coro to run in If no context is provided the Task copies the current context and later runs its coroutine in the copied context An optional keyword only eager_start argument allows eagerly starting the execution of the asyncio Task at task creation time If set to True and the event loop is running the task will start executing the coroutine immediately until the first time the coroutine blocks If the coroutine returns or raises without blocking the task will be finished eagerly and will skip scheduling to the event loop Changed in version 3 7 Added support for the contextvars module Changed in version 3 8 Added the name parameter Deprecated since version 3 10 Deprecation warning is emitted if loop is not specified and there is no running event loop Changed in version 3 11 Added the context parameter Changed in version 3 12 Added the eager_start parameter done Return True if the Task is done A Task is done when the wrapped coroutine either returned a value raised an exception or the Task was cancelled result Return the result of the Task If the Task is done the result of the wrapped coroutine is returned or if the coroutine raised an exception that exception is re raised If the Task has been cancelled this method raises a CancelledError exception If the Task s result isn t yet available this method raises a InvalidStateError exception exception Return the exception of the Task If the wrapped coroutine raised an exception that exception is returned If the wrapped coroutine returned normally this method returns None If the Task has been cancelled this method raises a CancelledError exception If the Task isn t done yet this method raises an InvalidStateError exception add_done_callback callback context None Add a callback to be run when the Task is done This method should only be used in low level callback based code See the documentation of Future add_done_callback for more details remove_done_callback callback Remove callback from the callbacks list This method should only be used in low level callback based code See the documentation of Future remove_done_callback for more details get_stack limit None Return the list of stack frames for this Task If the wrapped coroutine is not done this returns the stack where it is suspended If the coroutine has completed successfully or was cancelled this returns an empty list If the coroutine was terminated by an exception this returns the list of traceback frames The frames are always ordered from oldest to newest Only one stack frame is returned for a suspended coroutine The optional limit argument sets the maximum number of frames to
en
null
379
return by default all available frames are returned The ordering of the returned list differs depending on whether a stack or a traceback is returned the newest frames of a stack are returned but the oldest frames of a traceback are returned This matches the behavior of the traceback module print_stack limit None file None Print the stack or traceback for this Task This produces output similar to that of the traceback module for the frames retrieved by get_stack The limit argument is passed to get_stack directly The file argument is an I O stream to which the output is written by default output is written to sys stdout get_coro Return the coroutine object wrapped by the Task Note This will return None for Tasks which have already completed eagerly See the Eager Task Factory New in version 3 8 Changed in version 3 12 Newly added eager task execution means result may be None get_context Return the contextvars Context object associated with the task New in version 3 12 get_name Return the name of the Task If no name has been explicitly assigned to the Task the default asyncio Task implementation generates a default name during instantiation New in version 3 8 set_name value Set the name of the Task The value argument can be any object which is then converted to a string In the default Task implementation the name will be visible in the repr output of a task object New in version 3 8 cancel msg None Request the Task to be cancelled This arranges for a CancelledError exception to be thrown into the wrapped coroutine on the next cycle of the event loop The coroutine then has a chance to clean up or even deny the request by suppressing the exception with a try except CancelledError finally block Therefore unlike Future cancel Task cancel does not guarantee that the Task will be cancelled although suppressing cancellation completely is not common and is actively discouraged Should the coroutine nevertheless decide to suppress the cancellation it needs to call Task uncancel in addition to catching the exception Changed in version 3 9 Added the msg parameter Changed in version 3 11 The msg parameter is propagated from cancelled task to its awaiter The following example illustrates how coroutines can intercept the cancellation request async def cancel_me print cancel_me before sleep try Wait for 1 hour await asyncio sleep 3600 except asyncio CancelledError print cancel_me cancel sleep raise finally print cancel_me after sleep async def main Create a cancel_me Task task asyncio create_task cancel_me Wait for 1 second await asyncio sleep 1 task cancel try await task except asyncio CancelledError print main cancel_me is cancelled now asyncio run main Expected output cancel_me before sleep cancel_me cancel sleep cancel_me after sleep main cancel_me is cancelled now cancelled Return True if the Task is cancelled The Task is cancelled when the cancellation was requested with cancel and the wrapped coroutine propagated the CancelledError exception thrown into it uncancel Decrement the count of cancellation requests to this Task Returns the remaining number of cancellation requests Note that once execution of a cancelled task completed further calls to uncancel are ineffective New in version 3 11 This method is used by asyncio s internals and isn t expected to be used by end user code In particular if a Task gets successfully uncancelled this allows for elements of structured concurrency like Task Groups and asyncio timeout to continue running isolating cancellation to the respective structured block For example async def make_request_with_timeout try async with asyncio timeout 1 Structured block affected by the timeout await make_request await make_another_request except TimeoutError log There was a timeout Outer code not affected by the timeout await unrelated_code While the block with make_request and make_another_request might get cancelled due to the timeout unrelated_code should continue running even in case of the timeout This is implemented with uncancel TaskGroup context managers use uncancel in a similar fashion If end user code
en
null
380
is for some reason suppresing cancellation by catching CancelledError it needs to call this method to remove the cancellation state cancelling Return the number of pending cancellation requests to this Task i e the number of calls to cancel less the number of uncancel calls Note that if this number is greater than zero but the Task is still executing cancelled will still return False This is because this number can be lowered by calling uncancel which can lead to the task not being cancelled after all if the cancellation requests go down to zero This method is used by asyncio s internals and isn t expected to be used by end user code See uncancel for more details New in version 3 11
en
null
381
math Mathematical functions This module provides access to the mathematical functions defined by the C standard These functions cannot be used with complex numbers use the functions of the same name from the cmath module if you require support for complex numbers The distinction between functions which support complex numbers and those which don t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter so that the programmer can determine how and why it was generated in the first place The following functions are provided by this module Except when explicitly noted otherwise all return values are floats Number theoretic and representation functions math ceil x Return the ceiling of x the smallest integer greater than or equal to x If x is not a float delegates to x __ceil__ which should return an Integral value math comb n k Return the number of ways to choose k items from n items without repetition and without order Evaluates to n k n k when k n and evaluates to zero when k n Also called the binomial coefficient because it is equivalent to the coefficient of k th term in polynomial expansion of 1 x ⁿ Raises TypeError if either of the arguments are not integers Raises ValueError if either of the arguments are negative New in version 3 8 math copysign x y Return a float with the magnitude absolute value of x but the sign of y On platforms that support signed zeros copysign 1 0 0 0 returns 1 0 math fabs x Return the absolute value of x math factorial n Return n factorial as an integer Raises ValueError if n is not integral or is negative Deprecated since version 3 9 Accepting floats with integral values like 5 0 is deprecated math floor x Return the floor of x the largest integer less than or equal to x If x is not a float delegates to x __floor__ which should return an Integral value math fmod x y Return fmod x y as defined by the platform C library Note that the Python expression x y may not return the same result The intent of the C standard is that fmod x y be exactly mathematically to infinite precision equal to x n y for some integer n such that the result has the same sign as x and magnitude less than abs y Python s x y returns a result with the sign of y instead and may not be exactly computable for float arguments For example fmod 1e 100 1e100 is 1e 100 but the result of Python s 1e 100 1e100 is 1e100 1e 100 which cannot be represented exactly as a float and rounds to the surprising 1e100 For this reason function fmod is generally preferred when working with floats while Python s x y is preferred when working with integers math frexp x Return the mantissa and exponent of x as the pair m e m is a float and e is an integer such that x m 2 e exactly If x is zero returns 0 0 0 otherwise 0 5 abs m 1 This is used to pick apart the internal representation of a float in a portable way math fsum iterable Return an accurate floating point sum of values in the iterable Avoids loss of precision by tracking multiple intermediate partial sums The algorithm s accuracy depends on IEEE 754 arithmetic guarantees and the typical case where the rounding mode is half even On some non Windows builds the underlying C library uses extended precision addition and may occasionally double round an intermediate sum causing it to be off in its least significant bit For further discussion and two alternative approaches see the ASPN cookbook recipes for accurate floating point summation math gcd integers Return the greatest common divisor of the specified integer arguments If any of the arguments is nonzero then the returned value is the largest positive integer that is a divisor of all arguments If all arguments are zero then the returned value is 0 gcd without arguments returns 0 New in version 3 5 Changed in version 3 9 Added support for an arbitrary number of arguments Formerly only two arguments were supported math isclose a b rel_tol 1e 09 abs_tol 0 0 Ret
en
null
382
urn True if the values a and b are close to each other and False otherwise Whether or not two values are considered close is determined according to given absolute and relative tolerances rel_tol is the relative tolerance it is the maximum allowed difference between a and b relative to the larger absolute value of a or b For example to set a tolerance of 5 pass rel_tol 0 05 The default tolerance is 1e 09 which assures that the two values are the same within about 9 decimal digits rel_tol must be greater than zero abs_tol is the minimum absolute tolerance useful for comparisons near zero abs_tol must be at least zero If no errors occur the result will be abs a b max rel_tol max abs a abs b abs_tol The IEEE 754 special values of NaN inf and inf will be handled according to IEEE rules Specifically NaN is not considered close to any other value including NaN inf and inf are only considered close to themselves New in version 3 5 See also PEP 485 A function for testing approximate equality math isfinite x Return True if x is neither an infinity nor a NaN and False otherwise Note that 0 0 is considered finite New in version 3 2 math isinf x Return True if x is a positive or negative infinity and False otherwise math isnan x Return True if x is a NaN not a number and False otherwise math isqrt n Return the integer square root of the nonnegative integer n This is the floor of the exact square root of n or equivalently the greatest integer a such that a ² n For some applications it may be more convenient to have the least integer a such that n a ² or in other words the ceiling of the exact square root of n For positive n this can be computed using a 1 isqrt n 1 New in version 3 8 math lcm integers Return the least common multiple of the specified integer arguments If all arguments are nonzero then the returned value is the smallest positive integer that is a multiple of all arguments If any of the arguments is zero then the returned value is 0 lcm without arguments returns 1 New in version 3 9 math ldexp x i Return x 2 i This is essentially the inverse of function frexp math modf x Return the fractional and integer parts of x Both results carry the sign of x and are floats math nextafter x y steps 1 Return the floating point value steps steps after x towards y If x is equal to y return y unless steps is zero Examples math nextafter x math inf goes up towards positive infinity math nextafter x math inf goes down towards minus infinity math nextafter x 0 0 goes towards zero math nextafter x math copysign math inf x goes away from zero See also math ulp New in version 3 9 Changed in version 3 12 Added the steps argument math perm n k None Return the number of ways to choose k items from n items without repetition and with order Evaluates to n n k when k n and evaluates to zero when k n If k is not specified or is None then k defaults to n and the function returns n Raises TypeError if either of the arguments are not integers Raises ValueError if either of the arguments are negative New in version 3 8 math prod iterable start 1 Calculate the product of all the elements in the input iterable The default start value for the product is 1 When the iterable is empty return the start value This function is intended specifically for use with numeric values and may reject non numeric types New in version 3 8 math remainder x y Return the IEEE 754 style remainder of x with respect to y For finite x and finite nonzero y this is the difference x n y where n is the closest integer to the exact value of the quotient x y If x y is exactly halfway between two consecutive integers the nearest even integer is used for n The remainder r remainder x y thus always satisfies abs r 0 5 abs y Special cases follow IEEE 754 in particular remainder x math inf is x for any finite x and remainder x 0 and remainder math inf x raise ValueError for any non NaN x If the result of the remainder operation is zero that zero will have the same sign as x On platforms using IEEE 754 binary floating point the result of this operation is always exactly representable no roun
en
null
383
ding error is introduced New in version 3 7 math sumprod p q Return the sum of products of values from two iterables p and q Raises ValueError if the inputs do not have the same length Roughly equivalent to sum itertools starmap operator mul zip p q strict True For float and mixed int float inputs the intermediate products and sums are computed with extended precision New in version 3 12 math trunc x Return x with the fractional part removed leaving the integer part This rounds toward 0 trunc is equivalent to floor for positive x and equivalent to ceil for negative x If x is not a float delegates to x __trunc__ which should return an Integral value math ulp x Return the value of the least significant bit of the float x If x is a NaN not a number return x If x is negative return ulp x If x is a positive infinity return x If x is equal to zero return the smallest positive denormalized representable float smaller than the minimum positive normalized float sys float_info min If x is equal to the largest positive representable float return the value of the least significant bit of x such that the first float smaller than x is x ulp x Otherwise x is a positive finite number return the value of the least significant bit of x such that the first float bigger than x is x ulp x ULP stands for Unit in the Last Place See also math nextafter and sys float_info epsilon New in version 3 9 Note that frexp and modf have a different call return pattern than their C equivalents they take a single argument and return a pair of values rather than returning their second return value through an output parameter there is no such thing in Python For the ceil floor and modf functions note that all floating point numbers of sufficiently large magnitude are exact integers Python floats typically carry no more than 53 bits of precision the same as the platform C double type in which case any float x with abs x 2 52 necessarily has no fractional bits Power and logarithmic functions math cbrt x Return the cube root of x New in version 3 11 math exp x Return e raised to the power x where e 2 718281 is the base of natural logarithms This is usually more accurate than math e x or pow math e x math exp2 x Return 2 raised to the power x New in version 3 11 math expm1 x Return e raised to the power x minus 1 Here e is the base of natural logarithms For small floats x the subtraction in exp x 1 can result in a significant loss of precision the expm1 function provides a way to compute this quantity to full precision from math import exp expm1 exp 1e 5 1 gives result accurate to 11 places 1 0000050000069649e 05 expm1 1e 5 result accurate to full precision 1 0000050000166668e 05 New in version 3 2 math log x base With one argument return the natural logarithm of x to base e With two arguments return the logarithm of x to the given base calculated as log x log base math log1p x Return the natural logarithm of 1 x base e The result is calculated in a way which is accurate for x near zero math log2 x Return the base 2 logarithm of x This is usually more accurate than log x 2 New in version 3 3 See also int bit_length returns the number of bits necessary to represent an integer in binary excluding the sign and leading zeros math log10 x Return the base 10 logarithm of x This is usually more accurate than log x 10 math pow x y Return x raised to the power y Exceptional cases follow the IEEE 754 standard as far as possible In particular pow 1 0 x and pow x 0 0 always return 1 0 even when x is a zero or a NaN If both x and y are finite x is negative and y is not an integer then pow x y is undefined and raises ValueError Unlike the built in operator math pow converts both its arguments to type float Use or the built in pow function for computing exact integer powers Changed in version 3 11 The special cases pow 0 0 inf and pow 0 0 inf were changed to return inf instead of raising ValueError for consistency with IEEE 754 math sqrt x Return the square root of x Trigonometric functions math acos x Return the arc cosine of x in radians The result is between 0 and pi math a
en
null
384
sin x Return the arc sine of x in radians The result is between pi 2 and pi 2 math atan x Return the arc tangent of x in radians The result is between pi 2 and pi 2 math atan2 y x Return atan y x in radians The result is between pi and pi The vector in the plane from the origin to point x y makes this angle with the positive X axis The point of atan2 is that the signs of both inputs are known to it so it can compute the correct quadrant for the angle For example atan 1 and atan2 1 1 are both pi 4 but atan2 1 1 is 3 pi 4 math cos x Return the cosine of x radians math dist p q Return the Euclidean distance between two points p and q each given as a sequence or iterable of coordinates The two points must have the same dimension Roughly equivalent to sqrt sum px qx 2 0 for px qx in zip p q New in version 3 8 math hypot coordinates Return the Euclidean norm sqrt sum x 2 for x in coordinates This is the length of the vector from the origin to the point given by the coordinates For a two dimensional point x y this is equivalent to computing the hypotenuse of a right triangle using the Pythagorean theorem sqrt x x y y Changed in version 3 8 Added support for n dimensional points Formerly only the two dimensional case was supported Changed in version 3 10 Improved the algorithm s accuracy so that the maximum error is under 1 ulp unit in the last place More typically the result is almost always correctly rounded to within 1 2 ulp math sin x Return the sine of x radians math tan x Return the tangent of x radians Angular conversion math degrees x Convert angle x from radians to degrees math radians x Convert angle x from degrees to radians Hyperbolic functions Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles math acosh x Return the inverse hyperbolic cosine of x math asinh x Return the inverse hyperbolic sine of x math atanh x Return the inverse hyperbolic tangent of x math cosh x Return the hyperbolic cosine of x math sinh x Return the hyperbolic sine of x math tanh x Return the hyperbolic tangent of x Special functions math erf x Return the error function at x The erf function can be used to compute traditional statistical functions such as the cumulative standard normal distribution def phi x Cumulative distribution function for the standard normal distribution return 1 0 erf x sqrt 2 0 2 0 New in version 3 2 math erfc x Return the complementary error function at x The complementary error function is defined as 1 0 erf x It is used for large values of x where a subtraction from one would cause a loss of significance New in version 3 2 math gamma x Return the Gamma function at x New in version 3 2 math lgamma x Return the natural logarithm of the absolute value of the Gamma function at x New in version 3 2 Constants math pi The mathematical constant π 3 141592 to available precision math e The mathematical constant e 2 718281 to available precision math tau The mathematical constant τ 6 283185 to available precision Tau is a circle constant equal to 2 π the ratio of a circle s circumference to its radius To learn more about Tau check out Vi Hart s video Pi is still Wrong and start celebrating Tau day by eating twice as much pie New in version 3 6 math inf A floating point positive infinity For negative infinity use math inf Equivalent to the output of float inf New in version 3 5 math nan A floating point not a number NaN value Equivalent to the output of float nan Due to the requirements of the IEEE 754 standard math nan and float nan are not considered to equal to any other numeric value including themselves To check whether a number is a NaN use the isnan function to test for NaNs instead of is or Example import math math nan math nan False float nan float nan False math isnan math nan True math isnan float nan True New in version 3 5 Changed in version 3 11 It is now always available CPython implementation detail The math module consists mostly of thin wrappers around the platform C math library functions Behavior in exceptional cases follows Annex F of the C99 standar
en
null
385
d where appropriate The current implementation will raise ValueError for invalid operations like sqrt 1 0 or log 0 0 where C99 Annex F recommends signaling invalid operation or divide by zero and OverflowError for results that overflow for example exp 1000 0 A NaN will not be returned from any of the functions above unless one or more of the input arguments was a NaN in that case most functions will return a NaN but again following C99 Annex F there are some exceptions to this rule for example pow float nan 0 0 or hypot float nan float inf Note that Python makes no effort to distinguish signaling NaNs from quiet NaNs and behavior for signaling NaNs remains unspecified Typical behavior is to treat all NaNs as though they were quiet See also Module cmath Complex number versions of many of these functions
en
null
386
Built in Constants A small number of constants live in the built in namespace They are False The false value of the bool type Assignments to False are illegal and raise a SyntaxError True The true value of the bool type Assignments to True are illegal and raise a SyntaxError None An object frequently used to represent the absence of a value as when default arguments are not passed to a function Assignments to None are illegal and raise a SyntaxError None is the sole instance of the NoneType type NotImplemented A special value which should be returned by the binary special methods e g __eq__ __lt__ __add__ __rsub__ etc to indicate that the operation is not implemented with respect to the other type may be returned by the in place binary special methods e g __imul__ __iand__ etc for the same purpose It should not be evaluated in a boolean context NotImplemented is the sole instance of the types NotImplementedType type Note When a binary or in place method returns NotImplemented the interpreter will try the reflected operation on the other type or some other fallback depending on the operator If all attempts return NotImplemented the interpreter will raise an appropriate exception Incorrectly returning NotImplemented will result in a misleading error message or the NotImplemented value being returned to Python code See Implementing the arithmetic operations for examples Note NotImplementedError and NotImplemented are not interchangeable even though they have similar names and purposes See NotImplementedError for details on when to use it Changed in version 3 9 Evaluating NotImplemented in a boolean context is deprecated While it currently evaluates as true it will emit a DeprecationWarning It will raise a TypeError in a future version of Python Ellipsis The same as the ellipsis literal Special value used mostly in conjunction with extended slicing syntax for user defined container data types Ellipsis is the sole instance of the types EllipsisType type __debug__ This constant is true if Python was not started with an O option See also the assert statement Note The names None False True and __debug__ cannot be reassigned assignments to them even as an attribute name raise SyntaxError so they can be considered true constants Constants added by the site module The site module which is imported automatically during startup except if the S command line option is given adds several constants to the built in namespace They are useful for the interactive interpreter shell and should not be used in programs quit code None exit code None Objects that when printed print a message like Use quit or Ctrl D i e EOF to exit and when called raise SystemExit with the specified exit code copyright credits Objects that when printed or called print the text of copyright or credits respectively license Object that when printed prints the message Type license to see the full license text and when called displays the full license text in a pager like fashion one screen at a time
en
null
387
locale Internationalization services Source code Lib locale py The locale module opens access to the POSIX locale database and functionality The POSIX locale mechanism allows programmers to deal with certain cultural issues in an application without requiring the programmer to know all the specifics of each country where the software is executed The locale module is implemented on top of the _locale module which in turn uses an ANSI C locale implementation if available The locale module defines the following exception and functions exception locale Error Exception raised when the locale passed to setlocale is not recognized locale setlocale category locale None If locale is given and not None setlocale modifies the locale setting for the category The available categories are listed in the data description below locale may be a string or an iterable of two strings language code and encoding If it s an iterable it s converted to a locale name using the locale aliasing engine An empty string specifies the user s default settings If the modification of the locale fails the exception Error is raised If successful the new locale setting is returned If locale is omitted or None the current setting for category is returned setlocale is not thread safe on most systems Applications typically start with a call of import locale locale setlocale locale LC_ALL This sets the locale for all categories to the user s default setting typically specified in the LANG environment variable If the locale is not changed thereafter using multithreading should not cause problems locale localeconv Returns the database of the local conventions as a dictionary This dictionary has the following strings as keys Category Key Meaning LC_NUMERIC decimal_point Decimal point character grouping Sequence of numbers specifying which relative positions the thousands_sep is expected If the sequence is terminated with CHAR_MAX no further grouping is performed If the sequence terminates with a 0 the last group size is repeatedly used thousands_sep Character used between groups LC_MONETARY int_curr_symbol International currency symbol currency_symbol Local currency symbol p_cs_precedes n_cs_precedes Whether the currency symbol precedes the value for positive resp negative values p_sep_by_space n_sep_by_space Whether the currency symbol is separated from the value by a space for positive resp negative values mon_decimal_point Decimal point used for monetary values frac_digits Number of fractional digits used in local formatting of monetary values int_frac_digits Number of fractional digits used in international formatting of monetary values mon_thousands_sep Group separator used for monetary values mon_grouping Equivalent to grouping used for monetary values positive_sign Symbol used to annotate a positive monetary value negative_sign Symbol used to annotate a negative monetary value p_sign_posn n_sign_posn The position of the sign for positive resp negative values see below All numeric values can be set to CHAR_MAX to indicate that there is no value specified in this locale The possible values for p_sign_posn and n_sign_posn are given below Value Explanation 0 Currency and value are surrounded by parentheses 1 The sign should precede the value and currency symbol 2 The sign should follow the value and currency symbol 3 The sign should immediately precede the value 4 The sign should immediately follow the value CHAR_MAX Nothing is specified in this locale The function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale or the LC_MONETARY locale if locales are different and numeric or monetary strings are non ASCII This temporary change affects other threads Changed in version 3 7 The function now temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale in some cases locale nl_langinfo option Return some locale specific information as a string This function is not available on all systems and the set of possible options might also vary across platforms The possible argument values are numbers for which symbolic constants are available in the locale mod
en
null
388
ule The nl_langinfo function accepts one of the following keys Most descriptions are taken from the corresponding description in the GNU C library locale CODESET Get a string with the name of the character encoding used in the selected locale locale D_T_FMT Get a string that can be used as a format string for time strftime to represent date and time in a locale specific way locale D_FMT Get a string that can be used as a format string for time strftime to represent a date in a locale specific way locale T_FMT Get a string that can be used as a format string for time strftime to represent a time in a locale specific way locale T_FMT_AMPM Get a format string for time strftime to represent time in the am pm format locale DAY_1 locale DAY_2 locale DAY_3 locale DAY_4 locale DAY_5 locale DAY_6 locale DAY_7 Get the name of the n th day of the week Note This follows the US convention of DAY_1 being Sunday not the international convention ISO 8601 that Monday is the first day of the week locale ABDAY_1 locale ABDAY_2 locale ABDAY_3 locale ABDAY_4 locale ABDAY_5 locale ABDAY_6 locale ABDAY_7 Get the abbreviated name of the n th day of the week locale MON_1 locale MON_2 locale MON_3 locale MON_4 locale MON_5 locale MON_6 locale MON_7 locale MON_8 locale MON_9 locale MON_10 locale MON_11 locale MON_12 Get the name of the n th month locale ABMON_1 locale ABMON_2 locale ABMON_3 locale ABMON_4 locale ABMON_5 locale ABMON_6 locale ABMON_7 locale ABMON_8 locale ABMON_9 locale ABMON_10 locale ABMON_11 locale ABMON_12 Get the abbreviated name of the n th month locale RADIXCHAR Get the radix character decimal dot decimal comma etc locale THOUSEP Get the separator character for thousands groups of three digits locale YESEXPR Get a regular expression that can be used with the regex function to recognize a positive response to a yes no question locale NOEXPR Get a regular expression that can be used with the regex 3 function to recognize a negative response to a yes no question Note The regular expressions for YESEXPR and NOEXPR use syntax suitable for the regex function from the C library which might differ from the syntax used in re locale CRNCYSTR Get the currency symbol preceded by if the symbol should appear before the value if the symbol should appear after the value or if the symbol should replace the radix character locale ERA Get a string that represents the era used in the current locale Most locales do not define this value An example of a locale which does define this value is the Japanese one In Japan the traditional representation of dates includes the name of the era corresponding to the then emperor s reign Normally it should not be necessary to use this value directly Specifying the E modifier in their format strings causes the time strftime function to use this information The format of the returned string is not specified and therefore you should not assume knowledge of it on different systems locale ERA_D_T_FMT Get a format string for time strftime to represent date and time in a locale specific era based way locale ERA_D_FMT Get a format string for time strftime to represent a date in a locale specific era based way locale ERA_T_FMT Get a format string for time strftime to represent a time in a locale specific era based way locale ALT_DIGITS Get a representation of up to 100 values used to represent the values 0 to 99 locale getdefaultlocale envvars Tries to determine the default locale settings and returns them as a tuple of the form language code encoding According to POSIX a program which has not called setlocale LC_ALL runs using the portable C locale Calling setlocale LC_ALL lets it use the default locale as defined by the LANG variable Since we do not want to interfere with the current locale setting we thus emulate the behavior in the way described above To maintain compatibility with other platforms not only the LANG variable is tested but a list of variables given as envvars parameter The first found to be defined will be used envvars defaults to the search path used in GNU gettext it must always contain the varia
en
null
389
ble name LANG The GNU gettext search path contains LC_ALL LC_CTYPE LANG and LANGUAGE in that order Except for the code C the language code corresponds to RFC 1766 language code and encoding may be None if their values cannot be determined Deprecated since version 3 11 will be removed in version 3 15 locale getlocale category LC_CTYPE Returns the current setting for the given locale category as sequence containing language code encoding category may be one of the LC_ values except LC_ALL It defaults to LC_CTYPE Except for the code C the language code corresponds to RFC 1766 language code and encoding may be None if their values cannot be determined locale getpreferredencoding do_setlocale True Return the locale encoding used for text data according to user preferences User preferences are expressed differently on different systems and might not be available programmatically on some systems so this function only returns a guess On some systems it is necessary to invoke setlocale to obtain the user preferences so this function is not thread safe If invoking setlocale is not necessary or desired do_setlocale should be set to False On Android or if the Python UTF 8 Mode is enabled always return utf 8 the locale encoding and the do_setlocale argument are ignored The Python preinitialization configures the LC_CTYPE locale See also the filesystem encoding and error handler Changed in version 3 7 The function now always returns utf 8 on Android or if the Python UTF 8 Mode is enabled locale getencoding Get the current locale encoding On Android and VxWorks return utf 8 On Unix return the encoding of the current LC_CTYPE locale Return utf 8 if nl_langinfo CODESET returns an empty string for example if the current LC_CTYPE locale is not supported On Windows return the ANSI code page The Python preinitialization configures the LC_CTYPE locale See also the filesystem encoding and error handler This function is similar to getpreferredencoding False except this function ignores the Python UTF 8 Mode New in version 3 11 locale normalize localename Returns a normalized locale code for the given locale name The returned locale code is formatted for use with setlocale If normalization fails the original name is returned unchanged If the given encoding is not known the function defaults to the default encoding for the locale code just like setlocale locale resetlocale category LC_ALL Sets the locale for category to the default setting The default setting is determined by calling getdefaultlocale category defaults to LC_ALL Deprecated since version 3 11 will be removed in version 3 13 locale strcoll string1 string2 Compares two strings according to the current LC_COLLATE setting As any other compare function returns a negative or a positive value or 0 depending on whether string1 collates before or after string2 or is equal to it locale strxfrm string Transforms a string to one that can be used in locale aware comparisons For example strxfrm s1 strxfrm s2 is equivalent to strcoll s1 s2 0 This function can be used when the same string is compared repeatedly e g when collating a sequence of strings locale format_string format val grouping False monetary False Formats a number val according to the current LC_NUMERIC setting The format follows the conventions of the operator For floating point values the decimal point is modified if appropriate If grouping is True also takes the grouping into account If monetary is true the conversion uses monetary thousands separator and grouping strings Processes formatting specifiers as in format val but takes the current locale settings into account Changed in version 3 7 The monetary keyword parameter was added locale currency val symbol True grouping False international False Formats a number val according to the current LC_MONETARY settings The returned string includes the currency symbol if symbol is true which is the default If grouping is True which is not the default grouping is done with the value If international is True which is not the default the international currency symbol is used Note This fun
en
null
390
ction will not work with the C locale so you have to set a locale via setlocale first locale str float Formats a floating point number using the same format as the built in function str float but takes the decimal point into account locale delocalize string Converts a string into a normalized number string following the LC_NUMERIC settings New in version 3 5 locale localize string grouping False monetary False Converts a normalized number string into a formatted string following the LC_NUMERIC settings New in version 3 10 locale atof string func float Converts a string to a number following the LC_NUMERIC settings by calling func on the result of calling delocalize on string locale atoi string Converts a string to an integer following the LC_NUMERIC conventions locale LC_CTYPE Locale category for the character type functions Most importantly this category defines the text encoding i e how bytes are interpreted as Unicode codepoints See PEP 538 and PEP 540 for how this variable might be automatically coerced to C UTF 8 to avoid issues created by invalid settings in containers or incompatible settings passed over remote SSH connections Python doesn t internally use locale dependent character transformation functions from ctype h Instead an internal pyctype h provides locale independent equivalents like Py_TOLOWER locale LC_COLLATE Locale category for sorting strings The functions strcoll and strxfrm of the locale module are affected locale LC_TIME Locale category for the formatting of time The function time strftime follows these conventions locale LC_MONETARY Locale category for formatting of monetary values The available options are available from the localeconv function locale LC_MESSAGES Locale category for message display Python currently does not support application specific locale aware messages Messages displayed by the operating system like those returned by os strerror might be affected by this category This value may not be available on operating systems not conforming to the POSIX standard most notably Windows locale LC_NUMERIC Locale category for formatting numbers The functions format_string atoi atof and str of the locale module are affected by that category All other numeric formatting operations are not affected locale LC_ALL Combination of all locale settings If this flag is used when the locale is changed setting the locale for all categories is attempted If that fails for any category no category is changed at all When the locale is retrieved using this flag a string indicating the setting for all categories is returned This string can be later used to restore the settings locale CHAR_MAX This is a symbolic constant used for different values returned by localeconv Example import locale loc locale getlocale get current locale use German locale name might vary with platform locale setlocale locale LC_ALL de_DE locale strcoll f xe4n foo compare a string containing an umlaut locale setlocale locale LC_ALL use user s preferred locale locale setlocale locale LC_ALL C use default C locale locale setlocale locale LC_ALL loc restore saved locale Background details hints tips and caveats The C standard defines the locale as a program wide property that may be relatively expensive to change On top of that some implementations are broken in such a way that frequent locale changes may cause core dumps This makes the locale somewhat painful to use correctly Initially when a program is started the locale is the C locale no matter what the user s preferred locale is There is one exception the LC_CTYPE category is changed at startup to set the current locale encoding to the user s preferred locale encoding The program must explicitly say that it wants the user s preferred locale settings for other categories by calling setlocale LC_ALL It is generally a bad idea to call setlocale in some library routine since as a side effect it affects the entire program Saving and restoring it is almost as bad it is expensive and affects other threads that happen to run before the settings have been restored If when coding a module fo
en
null
391
r general use you need a locale independent version of an operation that is affected by the locale such as certain formats used with time strftime you will have to find a way to do it without using the standard library routine Even better is convincing yourself that using locale settings is okay Only as a last resort should you document that your module is not compatible with non C locale settings The only way to perform numeric operations according to the locale is to use the special functions defined by this module atof atoi format_string str There is no way to perform case conversions and character classifications according to the locale For Unicode text strings these are done according to the character value only while for byte strings the conversions and classifications are done according to the ASCII value of the byte and bytes whose high bit is set i e non ASCII bytes are never converted or considered part of a character class such as letter or whitespace For extension writers and programs that embed Python Extension modules should never call setlocale except to find out what the current locale is But since the return value can only be used portably to restore it that is not very useful except perhaps to find out whether or not the locale is C When Python code uses the locale module to change the locale this also affects the embedding application If the embedding application doesn t want this to happen it should remove the _locale extension module which does all the work from the table of built in modules in the config c file and make sure that the _locale module is not accessible as a shared library Access to message catalogs locale gettext msg locale dgettext domain msg locale dcgettext domain msg category locale textdomain domain locale bindtextdomain domain dir locale bind_textdomain_codeset domain codeset The locale module exposes the C library s gettext interface on systems that provide this interface It consists of the functions gettext dgettext dcgettext textdomain bindtextdomain and bind_textdomain_codeset These are similar to the same functions in the gettext module but use the C library s binary format for message catalogs and the C library s search algorithms for locating message catalogs Python applications should normally find no need to invoke these functions and should use gettext instead A known exception to this rule are applications that link with additional C libraries which internally invoke C functions gettext or dcgettext For these applications it may be necessary to bind the text domain so that the libraries can properly locate their message catalogs
en
null
392
Cryptographic Services The modules described in this chapter implement various algorithms of a cryptographic nature They are available at the discretion of the installation On Unix systems the crypt module may also be available Here s an overview hashlib Secure hashes and message digests Hash algorithms Usage Constructors Attributes Hash Objects SHAKE variable length digests File hashing Key derivation BLAKE2 Creating hash objects Constants Examples Simple hashing Using different digest sizes Keyed hashing Randomized hashing Personalization Tree mode Credits hmac Keyed Hashing for Message Authentication secrets Generate secure random numbers for managing secrets Random numbers Generating tokens How many bytes should tokens use Other functions Recipes and best practices
en
null
393
time Time access and conversions This module provides various time related functions For related functionality see also the datetime and calendar modules Although this module is always available not all functions are available on all platforms Most of the functions defined in this module call platform C library functions with the same name It may sometimes be helpful to consult the platform documentation because the semantics of these functions varies among platforms An explanation of some terminology and conventions is in order The epoch is the point where the time starts the return value of time gmtime 0 It is January 1 1970 00 00 00 UTC on all platforms The term seconds since the epoch refers to the total number of elapsed seconds since the epoch typically excluding leap seconds Leap seconds are excluded from this total on all POSIX compliant platforms The functions in this module may not handle dates and times before the epoch or far in the future The cut off point in the future is determined by the C library for 32 bit systems it is typically in 2038 Function strptime can parse 2 digit years when given y format code When 2 digit years are parsed they are converted according to the POSIX and ISO C standards values 69 99 are mapped to 1969 1999 and values 0 68 are mapped to 2000 2068 UTC is Coordinated Universal Time formerly known as Greenwich Mean Time or GMT The acronym UTC is not a mistake but a compromise between English and French DST is Daylight Saving Time an adjustment of the timezone by usually one hour during part of the year DST rules are magic determined by local law and can change from year to year The C library has a table containing the local rules often it is read from a system file for flexibility and is the only source of True Wisdom in this respect The precision of the various real time functions may be less than suggested by the units in which their value or argument is expressed E g on most Unix systems the clock ticks only 50 or 100 times a second On the other hand the precision of time and sleep is better than their Unix equivalents times are expressed as floating point numbers time returns the most accurate time available using Unix gettimeofday where available and sleep will accept a time with a nonzero fraction Unix select is used to implement this where available The time value as returned by gmtime localtime and strptime and accepted by asctime mktime and strftime is a sequence of 9 integers The return values of gmtime localtime and strptime also offer attribute names for individual fields See struct_time for a description of these objects Changed in version 3 3 The struct_time type was extended to provide the tm_gmtoff and tm_zone attributes when platform supports corresponding struct tm members Changed in version 3 6 The struct_time attributes tm_gmtoff and tm_zone are now available on all platforms Use the following functions to convert between time representations From To Use seconds since the epoch struct_time in UTC gmtime seconds since the epoch struct_time in local localtime time struct_time in UTC seconds since the epoch calendar timegm struct_time in local seconds since the epoch mktime time Functions time asctime t Convert a tuple or struct_time representing a time as returned by gmtime or localtime to a string of the following form Sun Jun 20 23 21 05 1993 The day field is two characters long and is space padded if the day is a single digit e g Wed Jun 9 04 26 40 1993 If t is not provided the current time as returned by localtime is used Locale information is not used by asctime Note Unlike the C function of the same name asctime does not add a trailing newline time pthread_getcpuclockid thread_id Return the clk_id of the thread specific CPU time clock for the specified thread_id Use threading get_ident or the ident attribute of threading Thread objects to get a suitable value for thread_id Warning Passing an invalid or expired thread_id may result in undefined behavior such as segmentation fault Availability Unix See the man page for pthread_getcpuclockid 3 for further informa
en
null
394
tion New in version 3 7 time clock_getres clk_id Return the resolution precision of the specified clock clk_id Refer to Clock ID Constants for a list of accepted values for clk_id Availability Unix New in version 3 3 time clock_gettime clk_id float Return the time of the specified clock clk_id Refer to Clock ID Constants for a list of accepted values for clk_id Use clock_gettime_ns to avoid the precision loss caused by the float type Availability Unix New in version 3 3 time clock_gettime_ns clk_id int Similar to clock_gettime but return time as nanoseconds Availability Unix New in version 3 7 time clock_settime clk_id time float Set the time of the specified clock clk_id Currently CLOCK_REALTIME is the only accepted value for clk_id Use clock_settime_ns to avoid the precision loss caused by the float type Availability Unix New in version 3 3 time clock_settime_ns clk_id time int Similar to clock_settime but set time with nanoseconds Availability Unix New in version 3 7 time ctime secs Convert a time expressed in seconds since the epoch to a string of a form Sun Jun 20 23 21 05 1993 representing local time The day field is two characters long and is space padded if the day is a single digit e g Wed Jun 9 04 26 40 1993 If secs is not provided or None the current time as returned by time is used ctime secs is equivalent to asctime localtime secs Locale information is not used by ctime time get_clock_info name Get information on the specified clock as a namespace object Supported clock names and the corresponding functions to read their value are monotonic time monotonic perf_counter time perf_counter process_time time process_time thread_time time thread_time time time time The result has the following attributes adjustable True if the clock can be changed automatically e g by a NTP daemon or manually by the system administrator False otherwise implementation The name of the underlying C function used to get the clock value Refer to Clock ID Constants for possible values monotonic True if the clock cannot go backward False otherwise resolution The resolution of the clock in seconds float New in version 3 3 time gmtime secs Convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero If secs is not provided or None the current time as returned by time is used Fractions of a second are ignored See above for a description of the struct_time object See calendar timegm for the inverse of this function time localtime secs Like gmtime but converts to local time If secs is not provided or None the current time as returned by time is used The dst flag is set to 1 when DST applies to the given time localtime may raise OverflowError if the timestamp is outside the range of values supported by the platform C localtime or gmtime functions and OSError on localtime or gmtime failure It s common for this to be restricted to years between 1970 and 2038 time mktime t This is the inverse function of localtime Its argument is the struct_time or full 9 tuple since the dst flag is needed use 1 as the dst flag if it is unknown which expresses the time in local time not UTC It returns a floating point number for compatibility with time If the input value cannot be represented as a valid time either OverflowError or ValueError will be raised which depends on whether the invalid value is caught by Python or the underlying C libraries The earliest date for which it can generate a time is platform dependent time monotonic float Return the value in fractional seconds of a monotonic clock i e a clock that cannot go backwards The clock is not affected by system clock updates The reference point of the returned value is undefined so that only the difference between the results of two calls is valid Use monotonic_ns to avoid the precision loss caused by the float type New in version 3 3 Changed in version 3 5 The function is now always available and always system wide Changed in version 3 10 On macOS the function is now system wide time monotonic_ns int Similar to monotonic but return time as nanoseconds
en
null
395
New in version 3 7 time perf_counter float Return the value in fractional seconds of a performance counter i e a clock with the highest available resolution to measure a short duration It does include time elapsed during sleep and is system wide The reference point of the returned value is undefined so that only the difference between the results of two calls is valid Use perf_counter_ns to avoid the precision loss caused by the float type New in version 3 3 Changed in version 3 10 On Windows the function is now system wide time perf_counter_ns int Similar to perf_counter but return time as nanoseconds New in version 3 7 time process_time float Return the value in fractional seconds of the sum of the system and user CPU time of the current process It does not include time elapsed during sleep It is process wide by definition The reference point of the returned value is undefined so that only the difference between the results of two calls is valid Use process_time_ns to avoid the precision loss caused by the float type New in version 3 3 time process_time_ns int Similar to process_time but return time as nanoseconds New in version 3 7 time sleep secs Suspend execution of the calling thread for the given number of seconds The argument may be a floating point number to indicate a more precise sleep time If the sleep is interrupted by a signal and no exception is raised by the signal handler the sleep is restarted with a recomputed timeout The suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system On Windows if secs is zero the thread relinquishes the remainder of its time slice to any other thread that is ready to run If there are no other threads ready to run the function returns immediately and the thread continues execution On Windows 8 1 and newer the implementation uses a high resolution timer which provides resolution of 100 nanoseconds If secs is zero Sleep 0 is used Unix implementation Use clock_nanosleep if available resolution 1 nanosecond Or use nanosleep if available resolution 1 nanosecond Or use select resolution 1 microsecond Changed in version 3 5 The function now sleeps at least secs even if the sleep is interrupted by a signal except if the signal handler raises an exception see PEP 475 for the rationale Changed in version 3 11 On Unix the clock_nanosleep and nanosleep functions are now used if available On Windows a waitable timer is now used time strftime format t Convert a tuple or struct_time representing a time as returned by gmtime or localtime to a string as specified by the format argument If t is not provided the current time as returned by localtime is used format must be a string ValueError is raised if any field in t is outside of the allowed range 0 is a legal argument for any position in the time tuple if it is normally illegal the value is forced to a correct one The following directives can be embedded in the format string They are shown without the optional field width and precision specification and are replaced by the indicated characters in the strftime result Directive Meaning Notes a Locale s abbreviated weekday name A Locale s full weekday name b Locale s abbreviated month name B Locale s full month name c Locale s appropriate date and time representation d Day of the month as a decimal number 01 31 f Microseconds as a decimal number 1 000000 999999 H Hour 24 hour clock as a decimal number 00 23 I Hour 12 hour clock as a decimal number 01 12 j Day of the year as a decimal number 001 366 m Month as a decimal number 01 12 M Minute as a decimal number 00 59 p Locale s equivalent of either AM or PM 2 S Second as a decimal number 00 61 3 U Week number of the year Sunday as the first day 4 of the week as a decimal number 00 53 All days in a new year preceding the first Sunday are considered to be in week 0 w Weekday as a decimal number 0 Sunday 6 W Week number of the year Monday as the first day 4 of the week as a decimal number 00 53 All days in a new year preceding the first Monday are considered to be in week 0 x L
en
null
396
ocale s appropriate date representation X Locale s appropriate time representation y Year without century as a decimal number 00 99 Y Year with century as a decimal number z Time zone offset indicating a positive or negative time difference from UTC GMT of the form HHMM or HHMM where H represents decimal hour digits and M represents decimal minute digits 23 59 23 59 1 Z Time zone name no characters if no time zone exists Deprecated 1 A literal character Notes 1 The f format directive only applies to strptime not to strftime However see also datetime datetime strptime and datetime datetime strftime where the f format directive applies to microseconds 2 When used with the strptime function the p directive only affects the output hour field if the I directive is used to parse the hour 3 The range really is 0 to 61 value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons 4 When used with the strptime function U and W are only used in calculations when the day of the week and the year are specified Here is an example a format for dates compatible with that specified in the RFC 2822 Internet email standard 1 from time import gmtime strftime strftime a d b Y H M S 0000 gmtime Thu 28 Jun 2001 14 17 15 0000 Additional directives may be supported on certain platforms but only the ones listed here have a meaning standardized by ANSI C To see the full set of format codes supported on your platform consult the strftime 3 documentation On some platforms an optional field width and precision specification can immediately follow the initial of a directive in the following order this is also not portable The field width is normally 2 except for j where it is 3 time strptime string format Parse a string representing a time according to a format The return value is a struct_time as returned by gmtime or localtime The format parameter uses the same directives as those used by strftime it defaults to a b d H M S Y which matches the formatting returned by ctime If string cannot be parsed according to format or if it has excess data after parsing ValueError is raised The default values used to fill in any missing data when more accurate values cannot be inferred are 1900 1 1 0 0 0 0 1 1 Both string and format must be strings For example import time time strptime 30 Nov 00 d b y time struct_time tm_year 2000 tm_mon 11 tm_mday 30 tm_hour 0 tm_min 0 tm_sec 0 tm_wday 3 tm_yday 335 tm_isdst 1 Support for the Z directive is based on the values contained in tzname and whether daylight is true Because of this it is platform specific except for recognizing UTC and GMT which are always known and are considered to be non daylight savings timezones Only the directives specified in the documentation are supported Because strftime is implemented per platform it can sometimes offer more directives than those listed But strptime is independent of any platform and thus does not necessarily support all directives available that are not documented as supported class time struct_time The type of the time value sequence returned by gmtime localtime and strptime It is an object with a named tuple interface values can be accessed by index and by attribute name The following values are present Index Attribute Values 0 tm_year for example 1993 1 tm_mon range 1 12 2 tm_day range 1 31 3 tm_hour range 0 23 4 tm_min range 0 59 5 tm_sec range 0 61 see Note 2 in strftime 6 tm_wday range 0 6 Monday is 0 7 tm_yday range 1 366 8 tm_isdst 0 1 or 1 see below N A tm_zone abbreviation of timezone name N A tm_gmtoff offset east of UTC in seconds Note that unlike the C structure the month value is a range of 1 12 not 0 11 In calls to mktime tm_isdst may be set to 1 when daylight savings time is in effect and 0 when it is not A value of 1 indicates that this is not known and will usually result in the correct state being filled in When a tuple with an incorrect length is passed to a function expecting a struct_time or having elements of the wrong type a TypeError is raised time time float Return the time in seconds since the epoch as
en
null
397
a floating point number The handling of leap seconds is platform dependent On Windows and most Unix systems the leap seconds are not counted towards the time in seconds since the epoch This is commonly referred to as Unix time Note that even though the time is always returned as a floating point number not all systems provide time with a better precision than 1 second While this function normally returns non decreasing values it can return a lower value than a previous call if the system clock has been set back between the two calls The number returned by time may be converted into a more common time format i e year month day hour etc in UTC by passing it to gmtime function or in local time by passing it to the localtime function In both cases a struct_time object is returned from which the components of the calendar date may be accessed as attributes Use time_ns to avoid the precision loss caused by the float type time time_ns int Similar to time but returns time as an integer number of nanoseconds since the epoch New in version 3 7 time thread_time float Return the value in fractional seconds of the sum of the system and user CPU time of the current thread It does not include time elapsed during sleep It is thread specific by definition The reference point of the returned value is undefined so that only the difference between the results of two calls in the same thread is valid Use thread_time_ns to avoid the precision loss caused by the float type Availability Linux Unix Windows Unix systems supporting CLOCK_THREAD_CPUTIME_ID New in version 3 7 time thread_time_ns int Similar to thread_time but return time as nanoseconds New in version 3 7 time tzset Reset the time conversion rules used by the library routines The environment variable TZ specifies how this is done It will also set the variables tzname from the TZ environment variable timezone non DST seconds West of UTC altzone DST seconds west of UTC and daylight to 0 if this timezone does not have any daylight saving time rules or to nonzero if there is a time past present or future when daylight saving time applies Availability Unix Note Although in many cases changing the TZ environment variable may affect the output of functions like localtime without calling tzset this behavior should not be relied on The TZ environment variable should contain no whitespace The standard format of the TZ environment variable is whitespace added for clarity std offset dst offset start time end time Where the components are std and dst Three or more alphanumerics giving the timezone abbreviations These will be propagated into time tzname offset The offset has the form hh mm ss This indicates the value added the local time to arrive at UTC If preceded by a the timezone is east of the Prime Meridian otherwise it is west If no offset follows dst summer time is assumed to be one hour ahead of standard time start time end time Indicates when to change to and back from DST The format of the start and end dates are one of the following J n The Julian day n 1 n 365 Leap days are not counted so in all years February 28 is day 59 and March 1 is day 60 n The zero based Julian day 0 n 365 Leap days are counted and it is possible to refer to February 29 M m n d The d th day 0 d 6 of week n of month m of the year 1 n 5 1 m 12 where week 5 means the last d day in month m which may occur in either the fourth or the fifth week Week 1 is the first week in which the d th day occurs Day zero is a Sunday time has the same format as offset except that no leading sign or is allowed The default if time is not given is 02 00 00 os environ TZ EST 05EDT M4 1 0 M10 5 0 time tzset time strftime X x Z 02 07 36 05 08 03 EDT os environ TZ AEST 10AEDT 11 M10 5 0 M3 5 0 time tzset time strftime X x Z 16 08 12 05 08 03 AEST On many Unix systems including BSD Linux Solaris and Darwin it is more convenient to use the system s zoneinfo tzfile 5 database to specify the timezone rules To do this set the TZ environment variable to the path of the required timezone datafile relative to the root of the systems zoneinfo time
en
null
398
zone database usually located at usr share zoneinfo For example US Eastern Australia Melbourne Egypt or Europe Amsterdam os environ TZ US Eastern time tzset time tzname EST EDT os environ TZ Egypt time tzset time tzname EET EEST Clock ID Constants These constants are used as parameters for clock_getres and clock_gettime time CLOCK_BOOTTIME Identical to CLOCK_MONOTONIC except it also includes any time that the system is suspended This allows applications to get a suspend aware monotonic clock without having to deal with the complications of CLOCK_REALTIME which may have discontinuities if the time is changed using settimeofday or similar Availability Linux 2 6 39 New in version 3 7 time CLOCK_HIGHRES The Solaris OS has a CLOCK_HIGHRES timer that attempts to use an optimal hardware source and may give close to nanosecond resolution CLOCK_HIGHRES is the nonadjustable high resolution clock Availability Solaris New in version 3 3 time CLOCK_MONOTONIC Clock that cannot be set and represents monotonic time since some unspecified starting point Availability Unix New in version 3 3 time CLOCK_MONOTONIC_RAW Similar to CLOCK_MONOTONIC but provides access to a raw hardware based time that is not subject to NTP adjustments Availability Linux 2 6 28 macOS 10 12 New in version 3 3 time CLOCK_PROCESS_CPUTIME_ID High resolution per process timer from the CPU Availability Unix New in version 3 3 time CLOCK_PROF High resolution per process timer from the CPU Availability FreeBSD NetBSD 7 OpenBSD New in version 3 7 time CLOCK_TAI International Atomic Time The system must have a current leap second table in order for this to give the correct answer PTP or NTP software can maintain a leap second table Availability Linux New in version 3 9 time CLOCK_THREAD_CPUTIME_ID Thread specific CPU time clock Availability Unix New in version 3 3 time CLOCK_UPTIME Time whose absolute value is the time the system has been running and not suspended providing accurate uptime measurement both absolute and interval Availability FreeBSD OpenBSD 5 5 New in version 3 7 time CLOCK_UPTIME_RAW Clock that increments monotonically tracking the time since an arbitrary point unaffected by frequency or time adjustments and not incremented while the system is asleep Availability macOS 10 12 New in version 3 8 The following constant is the only parameter that can be sent to clock_settime time CLOCK_REALTIME System wide real time clock Setting this clock requires appropriate privileges Availability Unix New in version 3 3 Timezone Constants time altzone The offset of the local DST timezone in seconds west of UTC if one is defined This is negative if the local DST timezone is east of UTC as in Western Europe including the UK Only use this if daylight is nonzero See note below time daylight Nonzero if a DST timezone is defined See note below time timezone The offset of the local non DST timezone in seconds west of UTC negative in most of Western Europe positive in the US zero in the UK See note below time tzname A tuple of two strings the first is the name of the local non DST timezone the second is the name of the local DST timezone If no DST timezone is defined the second string should not be used See note below Note For the above Timezone constants altzone daylight timezone and tzname the value is determined by the timezone rules in effect at module load time or the last time tzset is called and may be incorrect for times in the past It is recommended to use the tm_gmtoff and tm_zone results from localtime to obtain timezone information See also Module datetime More object oriented interface to dates and times Module locale Internationalization services The locale setting affects the interpretation of many format specifiers in strftime and strptime Module calendar General calendar related functions timegm is the inverse of gmtime from this module Footnotes 1 The use of Z is now deprecated but the z escape that expands to the preferred hour minute offset is not supported by all ANSI C libraries Also a strict reading of the original 1982 RFC 822 standard calls for a two digi
en
null
399
t year y rather than Y but practice moved to 4 digit years long before the year 2000 After that RFC 822 became obsolete and the 4 digit year has been first recommended by RFC 1123 and then mandated by RFC 2822
en
null