doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
class threading.Event Class implementing event objects. An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. The flag is initially false. Changed in version 3.3: changed from a factory function to a class. is_set() Return True if and only if the internal flag is true. set() Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all. clear() Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again. wait(timeout=None) Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). This method returns True if and only if the internal flag has been set to true, either before the wait call or after the wait starts, so it will always return True except if a timeout is given and the operation times out. Changed in version 3.1: Previously, the method always returned None.
python.library.threading#threading.Event
clear() Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.
python.library.threading#threading.Event.clear
is_set() Return True if and only if the internal flag is true.
python.library.threading#threading.Event.is_set
set() Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.
python.library.threading#threading.Event.set
wait(timeout=None) Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). This method returns True if and only if the internal flag has been set to true, either before the wait call or after the wait starts, so it will always return True except if a timeout is given and the operation times out. Changed in version 3.1: Previously, the method always returned None.
python.library.threading#threading.Event.wait
threading.excepthook(args, /) Handle uncaught exception raised by Thread.run(). The args argument has the following attributes: exc_type: Exception type. exc_value: Exception value, can be None. exc_traceback: Exception traceback, can be None. thread: Thread which raised the exception, can be None. If exc_type is SystemExit, the exception is silently ignored. Otherwise, the exception is printed out on sys.stderr. If this function raises an exception, sys.excepthook() is called to handle it. threading.excepthook() can be overridden to control how uncaught exceptions raised by Thread.run() are handled. Storing exc_value using a custom hook can create a reference cycle. It should be cleared explicitly to break the reference cycle when the exception is no longer needed. Storing thread using a custom hook can resurrect it if it is set to an object which is being finalized. Avoid storing thread after the custom hook completes to avoid resurrecting objects. See also sys.excepthook() handles uncaught exceptions. New in version 3.8.
python.library.threading#threading.excepthook
threading.get_ident() Return the ‘thread identifier’ of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created. New in version 3.3.
python.library.threading#threading.get_ident
threading.get_native_id() Return the native integral Thread ID of the current thread assigned by the kernel. This is a non-negative integer. Its value may be used to uniquely identify this particular thread system-wide (until the thread terminates, after which the value may be recycled by the OS). Availability: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX. New in version 3.8.
python.library.threading#threading.get_native_id
class threading.local A class that represents thread-local data. For more details and extensive examples, see the documentation string of the _threading_local module.
python.library.threading#threading.local
class threading.Lock The class implementing primitive lock objects. Once a thread has acquired a lock, subsequent attempts to acquire it block, until it is released; any thread may release it. Note that Lock is actually a factory function which returns an instance of the most efficient version of the concrete Lock class that is supported by the platform. acquire(blocking=True, timeout=-1) Acquire a lock, blocking or non-blocking. When invoked with the blocking argument set to True (the default), block until the lock is unlocked, then set it to locked and return True. When invoked with the blocking argument set to False, do not block. If a call with blocking set to True would block, return False immediately; otherwise, set the lock to locked and return True. When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. A timeout argument of -1 specifies an unbounded wait. It is forbidden to specify a timeout when blocking is false. The return value is True if the lock is acquired successfully, False if not (for example if the timeout expired). Changed in version 3.2: The timeout parameter is new. Changed in version 3.2: Lock acquisition can now be interrupted by signals on POSIX if the underlying threading implementation supports it. release() Release a lock. This can be called from any thread, not only the thread which has acquired the lock. When the lock is locked, reset it to unlocked, and return. If any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. When invoked on an unlocked lock, a RuntimeError is raised. There is no return value. locked() Return true if the lock is acquired.
python.library.threading#threading.Lock
acquire(blocking=True, timeout=-1) Acquire a lock, blocking or non-blocking. When invoked with the blocking argument set to True (the default), block until the lock is unlocked, then set it to locked and return True. When invoked with the blocking argument set to False, do not block. If a call with blocking set to True would block, return False immediately; otherwise, set the lock to locked and return True. When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. A timeout argument of -1 specifies an unbounded wait. It is forbidden to specify a timeout when blocking is false. The return value is True if the lock is acquired successfully, False if not (for example if the timeout expired). Changed in version 3.2: The timeout parameter is new. Changed in version 3.2: Lock acquisition can now be interrupted by signals on POSIX if the underlying threading implementation supports it.
python.library.threading#threading.Lock.acquire
locked() Return true if the lock is acquired.
python.library.threading#threading.Lock.locked
release() Release a lock. This can be called from any thread, not only the thread which has acquired the lock. When the lock is locked, reset it to unlocked, and return. If any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. When invoked on an unlocked lock, a RuntimeError is raised. There is no return value.
python.library.threading#threading.Lock.release
threading.main_thread() Return the main Thread object. In normal conditions, the main thread is the thread from which the Python interpreter was started. New in version 3.4.
python.library.threading#threading.main_thread
class threading.RLock This class implements reentrant lock objects. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. Note that RLock is actually a factory function which returns an instance of the most efficient version of the concrete RLock class that is supported by the platform. acquire(blocking=True, timeout=-1) Acquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case. When invoked with the blocking argument set to true, do the same thing as when called without arguments, and return True. When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True. When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return True if the lock has been acquired, false if the timeout has elapsed. Changed in version 3.2: The timeout parameter is new. release() Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value.
python.library.threading#threading.RLock
acquire(blocking=True, timeout=-1) Acquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case. When invoked with the blocking argument set to true, do the same thing as when called without arguments, and return True. When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True. When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return True if the lock has been acquired, false if the timeout has elapsed. Changed in version 3.2: The timeout parameter is new.
python.library.threading#threading.RLock.acquire
release() Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value.
python.library.threading#threading.RLock.release
class threading.Semaphore(value=1) This class implements semaphore objects. A semaphore manages an atomic counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. The optional argument gives the initial value for the internal counter; it defaults to 1. If the value given is less than 0, ValueError is raised. Changed in version 3.3: changed from a factory function to a class. acquire(blocking=True, timeout=None) Acquire a semaphore. When invoked without arguments: If the internal counter is larger than zero on entry, decrement it by one and return True immediately. If the internal counter is zero on entry, block until awoken by a call to release(). Once awoken (and the counter is greater than 0), decrement the counter by 1 and return True. Exactly one thread will be awoken by each call to release(). The order in which threads are awoken should not be relied on. When invoked with blocking set to false, do not block. If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True. When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return False. Return True otherwise. Changed in version 3.2: The timeout parameter is new. release(n=1) Release a semaphore, incrementing the internal counter by n. When it was zero on entry and other threads are waiting for it to become larger than zero again, wake up n of those threads. Changed in version 3.9: Added the n parameter to release multiple waiting threads at once.
python.library.threading#threading.Semaphore
acquire(blocking=True, timeout=None) Acquire a semaphore. When invoked without arguments: If the internal counter is larger than zero on entry, decrement it by one and return True immediately. If the internal counter is zero on entry, block until awoken by a call to release(). Once awoken (and the counter is greater than 0), decrement the counter by 1 and return True. Exactly one thread will be awoken by each call to release(). The order in which threads are awoken should not be relied on. When invoked with blocking set to false, do not block. If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True. When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return False. Return True otherwise. Changed in version 3.2: The timeout parameter is new.
python.library.threading#threading.Semaphore.acquire
release(n=1) Release a semaphore, incrementing the internal counter by n. When it was zero on entry and other threads are waiting for it to become larger than zero again, wake up n of those threads. Changed in version 3.9: Added the n parameter to release multiple waiting threads at once.
python.library.threading#threading.Semaphore.release
threading.setprofile(func) Set a profile function for all threads started from the threading module. The func will be passed to sys.setprofile() for each thread, before its run() method is called.
python.library.threading#threading.setprofile
threading.settrace(func) Set a trace function for all threads started from the threading module. The func will be passed to sys.settrace() for each thread, before its run() method is called.
python.library.threading#threading.settrace
threading.stack_size([size]) Return the thread stack size used when creating new threads. The optional size argument specifies the stack size to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768 (32 KiB). If size is not specified, 0 is used. If changing the thread stack size is unsupported, a RuntimeError is raised. If the specified stack size is invalid, a ValueError is raised and the stack size is unmodified. 32 KiB is currently the minimum supported stack size value to guarantee sufficient stack space for the interpreter itself. Note that some platforms may have particular restrictions on values for the stack size, such as requiring a minimum stack size > 32 KiB or requiring allocation in multiples of the system memory page size - platform documentation should be referred to for more information (4 KiB pages are common; using multiples of 4096 for the stack size is the suggested approach in the absence of more specific information). Availability: Windows, systems with POSIX threads.
python.library.threading#threading.stack_size
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None) This constructor should always be called with keyword arguments. Arguments are: group should be None; reserved for future extension when a ThreadGroup class is implemented. target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called. name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number. args is the argument tuple for the target invocation. Defaults to (). kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}. If not None, daemon explicitly sets whether the thread is daemonic. If None (the default), the daemonic property is inherited from the current thread. If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. Changed in version 3.3: Added the daemon argument. start() Start the thread’s activity. It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. run() Method representing the thread’s activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with positional and keyword arguments taken from the args and kwargs arguments, respectively. join(timeout=None) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out. When the timeout argument is not present or None, the operation will block until the thread terminates. A thread can be join()ed many times. join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raise the same exception. name A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. getName() setName() Old getter/setter API for name; use it directly as a property instead. ident The ‘thread identifier’ of this thread or None if the thread has not been started. This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited. native_id The native integral thread ID of this thread. This is a non-negative integer, or None if the thread has not been started. See the get_native_id() function. This represents the Thread ID (TID) as assigned to the thread by the OS (kernel). Its value may be used to uniquely identify this particular thread system-wide (until the thread terminates, after which the value may be recycled by the OS). Note Similar to Process IDs, Thread IDs are only valid (guaranteed unique system-wide) from the time the thread is created until the thread has been terminated. Availability: Requires get_native_id() function. New in version 3.8. is_alive() Return whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads. daemon A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False. The entire Python program exits when no alive non-daemon threads are left. isDaemon() setDaemon() Old getter/setter API for daemon; use it directly as a property instead.
python.library.threading#threading.Thread
daemon A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False. The entire Python program exits when no alive non-daemon threads are left.
python.library.threading#threading.Thread.daemon
getName() setName() Old getter/setter API for name; use it directly as a property instead.
python.library.threading#threading.Thread.getName
ident The ‘thread identifier’ of this thread or None if the thread has not been started. This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.
python.library.threading#threading.Thread.ident
isDaemon() setDaemon() Old getter/setter API for daemon; use it directly as a property instead.
python.library.threading#threading.Thread.isDaemon
is_alive() Return whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads.
python.library.threading#threading.Thread.is_alive
join(timeout=None) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out. When the timeout argument is not present or None, the operation will block until the thread terminates. A thread can be join()ed many times. join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raise the same exception.
python.library.threading#threading.Thread.join
name A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.
python.library.threading#threading.Thread.name
native_id The native integral thread ID of this thread. This is a non-negative integer, or None if the thread has not been started. See the get_native_id() function. This represents the Thread ID (TID) as assigned to the thread by the OS (kernel). Its value may be used to uniquely identify this particular thread system-wide (until the thread terminates, after which the value may be recycled by the OS). Note Similar to Process IDs, Thread IDs are only valid (guaranteed unique system-wide) from the time the thread is created until the thread has been terminated. Availability: Requires get_native_id() function. New in version 3.8.
python.library.threading#threading.Thread.native_id
run() Method representing the thread’s activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with positional and keyword arguments taken from the args and kwargs arguments, respectively.
python.library.threading#threading.Thread.run
isDaemon() setDaemon() Old getter/setter API for daemon; use it directly as a property instead.
python.library.threading#threading.Thread.setDaemon
getName() setName() Old getter/setter API for name; use it directly as a property instead.
python.library.threading#threading.Thread.setName
start() Start the thread’s activity. It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object.
python.library.threading#threading.Thread.start
threading.TIMEOUT_MAX The maximum value allowed for the timeout parameter of blocking functions (Lock.acquire(), RLock.acquire(), Condition.wait(), etc.). Specifying a timeout greater than this value will raise an OverflowError. New in version 3.2.
python.library.threading#threading.TIMEOUT_MAX
class threading.Timer(interval, function, args=None, kwargs=None) Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used. Changed in version 3.3: changed from a factory function to a class. cancel() Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.
python.library.threading#threading.Timer
cancel() Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.
python.library.threading#threading.Timer.cancel
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, and is platform dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC). To find out what the epoch is on a given platform, look at time.gmtime(0). 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 time localtime() struct_time in UTC seconds since the epoch calendar.timegm() struct_time in local time seconds since the epoch mktime() 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 information). 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. 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. 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. 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. New in version 3.3. Changed in version 3.5: The function is now always available and always system-wide. time.monotonic_ns() → int Similar to monotonic(), but return time as nanoseconds. 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. New in version 3.3. 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. 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. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. 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). 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]. %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. (1) %S Second as a decimal number [00,61]. (2) %U Week number of the year (Sunday as the first day 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. (3) %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day 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. (3) %x Locale’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]. %Z Time zone name (no characters if no time zone exists). %% A literal '%' character. Notes: 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. The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons. 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_mday range [1, 31] 3 tm_hour range [0, 23] 4 tm_min range [0, 59] 5 tm_sec range [0, 61]; see (2) in strftime() description 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 a floating point number. The specific date of the epoch and the handling of leap seconds is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. This is commonly referred to as Unix time. To find out what the epoch is on a given platform, look at gmtime(0). 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. 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. Availability: Windows, Linux, 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.time_ns() → int Similar to time() but returns time as an integer number of nanoseconds since the epoch. 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: Jn 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. Mm.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’ timezone 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 or later. 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 and newer, macOS 10.12 and newer. 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 or later, 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 or later. 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 and newer. 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-digit 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.
python.library.time
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.
python.library.time#time.altzone
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.
python.library.time#time.asctime
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 or later. New in version 3.7.
python.library.time#time.CLOCK_BOOTTIME
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.
python.library.time#time.clock_getres
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. Availability: Unix. New in version 3.3.
python.library.time#time.clock_gettime
time.clock_gettime_ns(clk_id) → int Similar to clock_gettime() but return time as nanoseconds. Availability: Unix. New in version 3.7.
python.library.time#time.clock_gettime_ns
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.
python.library.time#time.CLOCK_HIGHRES
time.CLOCK_MONOTONIC Clock that cannot be set and represents monotonic time since some unspecified starting point. Availability: Unix. New in version 3.3.
python.library.time#time.CLOCK_MONOTONIC
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 and newer, macOS 10.12 and newer. New in version 3.3.
python.library.time#time.CLOCK_MONOTONIC_RAW
time.CLOCK_PROCESS_CPUTIME_ID High-resolution per-process timer from the CPU. Availability: Unix. New in version 3.3.
python.library.time#time.CLOCK_PROCESS_CPUTIME_ID
time.CLOCK_PROF High-resolution per-process timer from the CPU. Availability: FreeBSD, NetBSD 7 or later, OpenBSD. New in version 3.7.
python.library.time#time.CLOCK_PROF
time.CLOCK_REALTIME System-wide real-time clock. Setting this clock requires appropriate privileges. Availability: Unix. New in version 3.3.
python.library.time#time.CLOCK_REALTIME
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. Availability: Unix. New in version 3.3.
python.library.time#time.clock_settime
time.clock_settime_ns(clk_id, time: int) Similar to clock_settime() but set time with nanoseconds. Availability: Unix. New in version 3.7.
python.library.time#time.clock_settime_ns
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.
python.library.time#time.CLOCK_TAI
time.CLOCK_THREAD_CPUTIME_ID Thread-specific CPU-time clock. Availability: Unix. New in version 3.3.
python.library.time#time.CLOCK_THREAD_CPUTIME_ID
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 or later. New in version 3.7.
python.library.time#time.CLOCK_UPTIME
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 and newer. New in version 3.8.
python.library.time#time.CLOCK_UPTIME_RAW
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().
python.library.time#time.ctime
time.daylight Nonzero if a DST timezone is defined. See note below.
python.library.time#time.daylight
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.
python.library.time#time.get_clock_info
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.
python.library.time#time.gmtime
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.
python.library.time#time.localtime
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.
python.library.time#time.mktime
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. New in version 3.3. Changed in version 3.5: The function is now always available and always system-wide.
python.library.time#time.monotonic
time.monotonic_ns() → int Similar to monotonic(), but return time as nanoseconds. New in version 3.7.
python.library.time#time.monotonic_ns
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. New in version 3.3.
python.library.time#time.perf_counter
time.perf_counter_ns() → int Similar to perf_counter(), but return time as nanoseconds. New in version 3.7.
python.library.time#time.perf_counter_ns
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. New in version 3.3.
python.library.time#time.process_time
time.process_time_ns() → int Similar to process_time() but return time as nanoseconds. New in version 3.7.
python.library.time#time.process_time_ns
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 information). New in version 3.7.
python.library.time#time.pthread_getcpuclockid
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. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. 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).
python.library.time#time.sleep
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]. %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. (1) %S Second as a decimal number [00,61]. (2) %U Week number of the year (Sunday as the first day 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. (3) %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day 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. (3) %x Locale’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]. %Z Time zone name (no characters if no time zone exists). %% A literal '%' character. Notes: 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. The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons. 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.
python.library.time#time.strftime
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.
python.library.time#time.strptime
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_mday range [1, 31] 3 tm_hour range [0, 23] 4 tm_min range [0, 59] 5 tm_sec range [0, 61]; see (2) in strftime() description 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.
python.library.time#time.struct_time
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. Availability: Windows, Linux, Unix systems supporting CLOCK_THREAD_CPUTIME_ID. New in version 3.7.
python.library.time#time.thread_time
time.thread_time_ns() → int Similar to thread_time() but return time as nanoseconds. New in version 3.7.
python.library.time#time.thread_time_ns
time.time() → float Return the time in seconds since the epoch as a floating point number. The specific date of the epoch and the handling of leap seconds is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. This is commonly referred to as Unix time. To find out what the epoch is on a given platform, look at gmtime(0). 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.
python.library.time#time.time
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.
python.library.time#time.timezone
time.time_ns() → int Similar to time() but returns time as an integer number of nanoseconds since the epoch. New in version 3.7.
python.library.time#time.time_ns
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.
python.library.time#time.tzname
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: Jn 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. Mm.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’ timezone 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')
python.library.time#time.tzset
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 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: $ python3 -m timeit '"-".join(str(n) for n in range(100))' 10000 loops, best of 5: 30.2 usec per loop $ python3 -m timeit '"-".join([str(n) for n in range(100)])' 10000 loops, best of 5: 27.5 usec per loop $ python3 -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(). 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, measured in 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 constructor. 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 second. 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] [-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 per loop $ python -m timeit -s 'text = "sample string"; char = "g"' 'text.find(char)' 1000000 loops, best of 5: 0.342 usec per loop >>> 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()))
python.library.timeit
timeit.default_timer() The default timer, which is always time.perf_counter(). Changed in version 3.3: time.perf_counter() is now the default timer.
python.library.timeit#timeit.default_timer
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.
python.library.timeit#timeit.repeat
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.
python.library.timeit#timeit.timeit
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, measured in 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 constructor. 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 second. 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.
python.library.timeit#timeit.Timer
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 second. 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.
python.library.timeit#timeit.Timer.autorange
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.
python.library.timeit#timeit.Timer.print_exc
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.
python.library.timeit#timeit.Timer.repeat
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, measured in 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 constructor. 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()
python.library.timeit#timeit.Timer.timeit
exception TimeoutError Raised when a system function timed out at the system level. Corresponds to errno ETIMEDOUT.
python.library.exceptions#TimeoutError
tkinter — Python interface to Tcl/Tk Source code: Lib/tkinter/__init__.py The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, as well as on Windows systems. (Tk itself is not part of Python; it is maintained at ActiveState.) Running python -m tkinter from the command line should open a window demonstrating a simple Tk interface, letting you know that tkinter is properly installed on your system, and also showing what version of Tcl/Tk is installed, so you can read the Tcl/Tk documentation specific to that version. See also Tkinter documentation: Python Tkinter Resources The Python Tkinter Topic Guide provides a great deal of information on using Tk from Python and links to other sources of information on Tk. TKDocs Extensive tutorial plus friendlier widget pages for some of the widgets. Tkinter 8.5 reference: a GUI for Python On-line reference material. Tkinter docs from effbot Online reference for tkinter supported by effbot.org. Programming Python Book by Mark Lutz, has excellent coverage of Tkinter. Modern Tkinter for Busy Python Developers Book by Mark Roseman about building attractive and modern graphical user interfaces with Python and Tkinter. Python and Tkinter Programming Book by John Grayson (ISBN 1-884777-81-3). Tcl/Tk documentation: Tk commands Most commands are available as tkinter or tkinter.ttk classes. Change ‘8.6’ to match the version of your Tcl/Tk installation. Tcl/Tk recent man pages Recent Tcl/Tk manuals on www.tcl.tk. ActiveState Tcl Home Page The Tk/Tcl development is largely taking place at ActiveState. Tcl and the Tk Toolkit Book by John Ousterhout, the inventor of Tcl. Practical Programming in Tcl and Tk Brent Welch’s encyclopedic book. Tkinter Modules Most of the time, tkinter is all you really need, but a number of additional modules are available as well. The Tk interface is located in a binary module named _tkinter. This module contains the low-level interface to Tk, and should never be used directly by application programmers. It is usually a shared library (or DLL), but might in some cases be statically linked with the Python interpreter. In addition to the Tk interface module, tkinter includes a number of Python modules, tkinter.constants being one of the most important. Importing tkinter will automatically import tkinter.constants, so, usually, to use Tkinter all you need is a simple import statement: import tkinter Or, more often: from tkinter import * class tkinter.Tk(screenName=None, baseName=None, className='Tk', useTk=1) The Tk class is instantiated without arguments. This creates a toplevel widget of Tk which usually is the main window of an application. Each instance has its own associated Tcl interpreter. tkinter.Tcl(screenName=None, baseName=None, className='Tk', useTk=0) The Tcl() function is a factory function which creates an object much like that created by the Tk class, except that it does not initialize the Tk subsystem. This is most often useful when driving the Tcl interpreter in an environment where one doesn’t want to create extraneous toplevel windows, or where one cannot (such as Unix/Linux systems without an X server). An object created by the Tcl() object can have a Toplevel window created (and the Tk subsystem initialized) by calling its loadtk() method. Other modules that provide Tk support include: tkinter.colorchooser Dialog to let the user choose a color. tkinter.commondialog Base class for the dialogs defined in the other modules listed here. tkinter.filedialog Common dialogs to allow the user to specify a file to open or save. tkinter.font Utilities to help work with fonts. tkinter.messagebox Access to standard Tk dialog boxes. tkinter.scrolledtext Text widget with a vertical scroll bar built in. tkinter.simpledialog Basic dialogs and convenience functions. tkinter.dnd Drag-and-drop support for tkinter. This is experimental and should become deprecated when it is replaced with the Tk DND. turtle Turtle graphics in a Tk window. Tkinter Life Preserver This section is not designed to be an exhaustive tutorial on either Tk or Tkinter. Rather, it is intended as a stop gap, providing some introductory orientation on the system. Credits: Tk was written by John Ousterhout while at Berkeley. Tkinter was written by Steen Lumholt and Guido van Rossum. This Life Preserver was written by Matt Conway at the University of Virginia. The HTML rendering, and some liberal editing, was produced from a FrameMaker version by Ken Manheimer. Fredrik Lundh elaborated and revised the class interface descriptions, to get them current with Tk 4.2. Mike Clarkson converted the documentation to LaTeX, and compiled the User Interface chapter of the reference manual. How To Use This Section This section is designed in two parts: the first half (roughly) covers background material, while the second half can be taken to the keyboard as a handy reference. When trying to answer questions of the form “how do I do blah”, it is often best to find out how to do “blah” in straight Tk, and then convert this back into the corresponding tkinter call. Python programmers can often guess at the correct Python command by looking at the Tk documentation. This means that in order to use Tkinter, you will have to know a little bit about Tk. This document can’t fulfill that role, so the best we can do is point you to the best documentation that exists. Here are some hints: The authors strongly suggest getting a copy of the Tk man pages. Specifically, the man pages in the manN directory are most useful. The man3 man pages describe the C interface to the Tk library and thus are not especially helpful for script writers. Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for the novice. The book is not exhaustive, and for many details it defers to the man pages. tkinter/__init__.py is a last resort for most, but can be a good place to go when nothing else makes sense. A Simple Hello World Program import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() def create_widgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello World\n(click me)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") self.quit = tk.Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="bottom") def say_hi(self): print("hi there, everyone!") root = tk.Tk() app = Application(master=root) app.mainloop() A (Very) Quick Look at Tcl/Tk The class hierarchy looks complicated, but in actual practice, application programmers almost always refer to the classes at the very bottom of the hierarchy. Notes: These classes are provided for the purposes of organizing certain functions under one namespace. They aren’t meant to be instantiated independently. The Tk class is meant to be instantiated only once in an application. Application programmers need not instantiate one explicitly, the system creates one whenever any of the other classes are instantiated. The Widget class is not meant to be instantiated, it is meant only for subclassing to make “real” widgets (in C++, this is called an ‘abstract class’). To make use of this reference material, there will be times when you will need to know how to read short passages of Tk and how to identify the various parts of a Tk command. (See section Mapping Basic Tk into Tkinter for the tkinter equivalents of what’s below.) Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists of tokens separated by spaces. A Tk widget is just its class, the options that help configure it, and the actions that make it do useful things. To make a widget in Tk, the command is always of the form: classCommand newPathname options classCommand denotes which kind of widget to make (a button, a label, a menu…) newPathname is the new name for this widget. All names in Tk must be unique. To help enforce this, widgets in Tk are named with pathnames, just like files in a file system. The top level widget, the root, is called . (period) and children are delimited by more periods. For example, .myApp.controlPanel.okButton might be the name of a widget. options configure the widget’s appearance and in some cases, its behavior. The options come in the form of a list of flags and values. Flags are preceded by a ‘-‘, like Unix shell command flags, and values are put in quotes if they are more than one word. For example: button .fred -fg red -text "hi there" ^ ^ \______________________/ | | | class new options command widget (-opt val -opt val ...) Once created, the pathname to the widget becomes a new command. This new widget command is the programmer’s handle for getting the new widget to perform some action. In C, you’d express this as someAction(fred, someOptions), in C++, you would express this as fred.someAction(someOptions), and in Tk, you say: .fred someAction someOptions Note that the object name, .fred, starts with a dot. As you’d expect, the legal values for someAction will depend on the widget’s class: .fred disable works if fred is a button (fred gets greyed out), but does not work if fred is a label (disabling of labels is not supported in Tk). The legal values of someOptions is action dependent. Some actions, like disable, require no arguments, others, like a text-entry box’s delete command, would need arguments to specify what range of text to delete. Mapping Basic Tk into Tkinter Class commands in Tk correspond to class constructors in Tkinter. button .fred =====> fred = Button() The master of an object is implicit in the new name given to it at creation time. In Tkinter, masters are specified explicitly. button .panel.fred =====> fred = Button(panel) The configuration options in Tk are given in lists of hyphened tags followed by values. In Tkinter, options are specified as keyword-arguments in the instance constructor, and keyword-args for configure calls or as instance indices, in dictionary style, for established instances. See section Setting Options on setting options. button .fred -fg red =====> fred = Button(panel, fg="red") .fred configure -fg red =====> fred["fg"] = red OR ==> fred.config(fg="red") In Tk, to perform an action on a widget, use the widget name as a command, and follow it with an action name, possibly with arguments (options). In Tkinter, you call methods on the class instance to invoke actions on the widget. The actions (methods) that a given widget can perform are listed in tkinter/__init__.py. .fred invoke =====> fred.invoke() To give a widget to the packer (geometry manager), you call pack with optional arguments. In Tkinter, the Pack class holds all this functionality, and the various forms of the pack command are implemented as methods. All widgets in tkinter are subclassed from the Packer, and so inherit all the packing methods. See the tkinter.tix module documentation for additional information on the Form geometry manager. pack .fred -side left =====> fred.pack(side="left") How Tk and Tkinter are Related From the top down: Your App Here (Python) A Python application makes a tkinter call. tkinter (Python Package) This call (say, for example, creating a button widget), is implemented in the tkinter package, which is written in Python. This Python function will parse the commands and the arguments and convert them into a form that makes them look as if they had come from a Tk script instead of a Python script. _tkinter (C) These commands and their arguments will be passed to a C function in the _tkinter - note the underscore - extension module. Tk Widgets (C and Tcl) This C function is able to make calls into other C modules, including the C functions that make up the Tk library. Tk is implemented in C and some Tcl. The Tcl part of the Tk widgets is used to bind certain default behaviors to widgets, and is executed once at the point where the Python tkinter package is imported. (The user never sees this stage). Tk (C) The Tk part of the Tk Widgets implement the final mapping to … Xlib (C) the Xlib library to draw graphics on the screen. Handy Reference Setting Options Options control things like the color and border width of a widget. Options can be set in three ways: At object creation time, using keyword arguments fred = Button(self, fg="red", bg="blue") After object creation, treating the option name like a dictionary index fred["fg"] = "red" fred["bg"] = "blue" Use the config() method to update multiple attrs subsequent to object creation fred.config(fg="red", bg="blue") For a complete explanation of a given option and its behavior, see the Tk man pages for the widget in question. Note that the man pages list “STANDARD OPTIONS” and “WIDGET SPECIFIC OPTIONS” for each widget. The former is a list of options that are common to many widgets, the latter are the options that are idiosyncratic to that particular widget. The Standard Options are documented on the options(3) man page. No distinction between standard and widget-specific options is made in this document. Some options don’t apply to some kinds of widgets. Whether a given widget responds to a particular option depends on the class of the widget; buttons have a command option, labels do not. The options supported by a given widget are listed in that widget’s man page, or can be queried at runtime by calling the config() method without arguments, or by calling the keys() method on that widget. The return value of these calls is a dictionary whose key is the name of the option as a string (for example, 'relief') and whose values are 5-tuples. Some options, like bg are synonyms for common options with long names (bg is shorthand for “background”). Passing the config() method the name of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed back will contain the name of the synonym and the “real” option (such as ('bg', 'background')). Index Meaning Example 0 option name 'relief' 1 option name for database lookup 'relief' 2 option class for database lookup 'Relief' 3 default value 'raised' 4 current value 'groove' Example: >>> print(fred.config()) {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')} Of course, the dictionary printed will include all the options available and their values. This is meant only as an example. The Packer The packer is one of Tk’s geometry-management mechanisms. Geometry managers are used to specify the relative positioning of widgets within their container - their mutual master. In contrast to the more cumbersome placer (which is used less commonly, and we do not cover here), the packer takes qualitative relationship specification - above, to the left of, filling, etc - and works everything out to determine the exact placement coordinates for you. The size of any master widget is determined by the size of the “slave widgets” inside. The packer is used to control where slave widgets appear inside the master into which they are packed. You can pack widgets into frames, and frames into other frames, in order to achieve the kind of layout you desire. Additionally, the arrangement is dynamically adjusted to accommodate incremental changes to the configuration, once it is packed. Note that widgets do not appear until they have had their geometry specified with a geometry manager. It’s a common early mistake to leave out the geometry specification, and then be surprised when the widget is created but nothing appears. A widget will appear only after it has had, for example, the packer’s pack() method applied to it. The pack() method can be called with keyword-option/value pairs that control where the widget is to appear within its container, and how it is to behave when the main application window is resized. Here are some examples: fred.pack() # defaults to side = "top" fred.pack(side="left") fred.pack(expand=1) Packer Options For more extensive information on the packer and the options that it can take, see the man pages and page 183 of John Ousterhout’s book. anchor Anchor type. Denotes where the packer is to place each slave in its parcel. expand Boolean, 0 or 1. fill Legal values: 'x', 'y', 'both', 'none'. ipadx and ipady A distance - designating internal padding on each side of the slave widget. padx and pady A distance - designating external padding on each side of the slave widget. side Legal values are: 'left', 'right', 'top', 'bottom'. Coupling Widget Variables The current-value setting of some widgets (like text entry widgets) can be connected directly to application variables by using special options. These options are variable, textvariable, onvalue, offvalue, and value. This connection works both ways: if the variable changes for any reason, the widget it’s connected to will be updated to reflect the new value. Unfortunately, in the current implementation of tkinter it is not possible to hand over an arbitrary Python variable to a widget through a variable or textvariable option. The only kinds of variables for which this works are variables that are subclassed from a class called Variable, defined in tkinter. There are many useful subclasses of Variable already defined: StringVar, IntVar, DoubleVar, and BooleanVar. To read the current value of such a variable, call the get() method on it, and to change its value you call the set() method. If you follow this protocol, the widget will always track the value of the variable, with no further intervention on your part. For example: import tkinter as tk class App(tk.Frame): def __init__(self, master): super().__init__(master) self.pack() self.entrythingy = tk.Entry() self.entrythingy.pack() # Create the application variable. self.contents = tk.StringVar() # Set it to some value. self.contents.set("this is a variable") # Tell the entry widget to watch this variable. self.entrythingy["textvariable"] = self.contents # Define a callback for when the user hits return. # It prints the current value of the variable. self.entrythingy.bind('<Key-Return>', self.print_contents) def print_contents(self, event): print("Hi. The current entry content is:", self.contents.get()) root = tk.Tk() myapp = App(root) myapp.mainloop() The Window Manager In Tk, there is a utility command, wm, for interacting with the window manager. Options to the wm command allow you to control things like titles, placement, icon bitmaps, and the like. In tkinter, these commands have been implemented as methods on the Wm class. Toplevel widgets are subclassed from the Wm class, and so can call the Wm methods directly. To get at the toplevel window that contains a given widget, you can often just refer to the widget’s master. Of course if the widget has been packed inside of a frame, the master won’t represent a toplevel window. To get at the toplevel window that contains an arbitrary widget, you can call the _root() method. This method begins with an underscore to denote the fact that this function is part of the implementation, and not an interface to Tk functionality. Here are some examples of typical usage: import tkinter as tk class App(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() # create the application myapp = App() # # here are method calls to the window manager class # myapp.master.title("My Do-Nothing Application") myapp.master.maxsize(1000, 400) # start the program myapp.mainloop() Tk Option Data Types anchor Legal values are points of the compass: "n", "ne", "e", "se", "s", "sw", "w", "nw", and also "center". bitmap There are eight built-in, named bitmaps: 'error', 'gray25', 'gray50', 'hourglass', 'info', 'questhead', 'question', 'warning'. To specify an X bitmap filename, give the full path to the file, preceded with an @, as in "@/usr/contrib/bitmap/gumby.bit". boolean You can pass integers 0 or 1 or the strings "yes" or "no". callback This is any Python function that takes no arguments. For example: def print_it(): print("hi there") fred["command"] = print_it color Colors can be given as the names of X colors in the rgb.txt file, or as strings representing RGB values in 4 bit: "#RGB", 8 bit: "#RRGGBB", 12 bit” "#RRRGGGBBB", or 16 bit "#RRRRGGGGBBBB" ranges, where R,G,B here represent any legal hex digit. See page 160 of Ousterhout’s book for details. cursor The standard X cursor names from cursorfont.h can be used, without the XC_ prefix. For example to get a hand cursor (XC_hand2), use the string "hand2". You can also specify a bitmap and mask file of your own. See page 179 of Ousterhout’s book. distance Screen distances can be specified in either pixels or absolute distances. Pixels are given as numbers and absolute distances as strings, with the trailing character denoting units: c for centimetres, i for inches, m for millimetres, p for printer’s points. For example, 3.5 inches is expressed as "3.5i". font Tk uses a list font name format, such as {courier 10 bold}. Font sizes with positive numbers are measured in points; sizes with negative numbers are measured in pixels. geometry This is a string of the form widthxheight, where width and height are measured in pixels for most widgets (in characters for widgets displaying text). For example: fred["geometry"] = "200x100". justify Legal values are the strings: "left", "center", "right", and "fill". region This is a string with four space-delimited elements, each of which is a legal distance (see above). For example: "2 3 4 5" and "3i 2i 4.5i 2i" and "3c 2c 4c 10.43c" are all legal regions. relief Determines what the border style of a widget will be. Legal values are: "raised", "sunken", "flat", "groove", and "ridge". scrollcommand This is almost always the set() method of some scrollbar widget, but can be any widget method that takes a single argument. wrap Must be one of: "none", "char", or "word". Bindings and Events The bind method from the widget command allows you to watch for certain events and to have a callback function trigger when that event type occurs. The form of the bind method is: def bind(self, sequence, func, add=''): where: sequence is a string that denotes the target kind of event. (See the bind man page and page 201 of John Ousterhout’s book for details). func is a Python function, taking one argument, to be invoked when the event occurs. An Event instance will be passed as the argument. (Functions deployed this way are commonly known as callbacks.) add is optional, either '' or '+'. Passing an empty string denotes that this binding is to replace any other bindings that this event is associated with. Passing a '+' means that this function is to be added to the list of functions bound to this event type. For example: def turn_red(self, event): event.widget["activeforeground"] = "red" self.button.bind("<Enter>", self.turn_red) Notice how the widget field of the event is being accessed in the turn_red() callback. This field contains the widget that caught the X event. The following table lists the other event fields you can access, and how they are denoted in Tk, which can be useful when referring to the Tk man pages. Tk Tkinter Event Field Tk Tkinter Event Field %f focus %A char %h height %E send_event %k keycode %K keysym %s state %N keysym_num %t time %T type %w width %W widget %x x %X x_root %y y %Y y_root The index Parameter A number of widgets require “index” parameters to be passed. These are used to point at a specific place in a Text widget, or to particular characters in an Entry widget, or to particular menu items in a Menu widget. Entry widget indexes (index, view index, etc.) Entry widgets have options that refer to character positions in the text being displayed. You can use these tkinter functions to access these special points in text widgets: Text widget indexes The index notation for Text widgets is very rich and is best described in the Tk man pages. Menu indexes (menu.invoke(), menu.entryconfig(), etc.) Some options and methods for menus manipulate specific menu entries. Anytime a menu index is needed for an option or a parameter, you may pass in: an integer which refers to the numeric position of the entry in the widget, counted from the top, starting with 0; the string "active", which refers to the menu position that is currently under the cursor; the string "last" which refers to the last menu item; An integer preceded by @, as in @6, where the integer is interpreted as a y pixel coordinate in the menu’s coordinate system; the string "none", which indicates no menu entry at all, most often used with menu.activate() to deactivate all entries, and finally, a text string that is pattern matched against the label of the menu entry, as scanned from the top of the menu to the bottom. Note that this index type is considered after all the others, which means that matches for menu items labelled last, active, or none may be interpreted as the above literals, instead. Images Images of different formats can be created through the corresponding subclass of tkinter.Image: BitmapImage for images in XBM format. PhotoImage for images in PGM, PPM, GIF and PNG formats. The latter is supported starting with Tk 8.6. Either type of image is created through either the file or the data option (other options are available as well). The image object can then be used wherever an image option is supported by some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a reference to the image. When the last Python reference to the image object is deleted, the image data is deleted as well, and Tk will display an empty box wherever the image was used. See also The Pillow package adds support for formats such as BMP, JPEG, TIFF, and WebP, among others. File Handlers Tk allows you to register and unregister a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. Only one handler may be registered per file descriptor. Example code: import tkinter widget = tkinter.Tk() mask = tkinter.READABLE | tkinter.WRITABLE widget.tk.createfilehandler(file, mask, callback) ... widget.tk.deletefilehandler(file) This feature is not available on Windows. Since you don’t know how many bytes are available for reading, you may not want to use the BufferedIOBase or TextIOBase read() or readline() methods, since these will insist on reading a predefined number of bytes. For sockets, the recv() or recvfrom() methods will work fine; for other files, use raw reads or os.read(file.fileno(), maxbytecount). Widget.tk.createfilehandler(file, mask, func) Registers the file handler callback function func. The file argument may either be an object with a fileno() method (such as a file or socket object), or an integer file descriptor. The mask argument is an ORed combination of any of the three constants below. The callback is called as follows: callback(file, mask) Widget.tk.deletefilehandler(file) Unregisters a file handler. tkinter.READABLE tkinter.WRITABLE tkinter.EXCEPTION Constants used in the mask arguments.
python.library.tkinter
tkinter.colorchooser — Color choosing dialog Source code: Lib/tkinter/colorchooser.py The tkinter.colorchooser module provides the Chooser class as an interface to the native color picker dialog. Chooser implements a modal color choosing dialog window. The Chooser class inherits from the Dialog class. class tkinter.colorchooser.Chooser(master=None, **options) tkinter.colorchooser.askcolor(color=None, **options) Create a color choosing dialog. A call to this method will show the window, wait for the user to make a selection, and return the selected color (or None) to the caller. See also Module tkinter.commondialog Tkinter standard dialog module
python.library.tkinter.colorchooser
tkinter.colorchooser.askcolor(color=None, **options) Create a color choosing dialog. A call to this method will show the window, wait for the user to make a selection, and return the selected color (or None) to the caller.
python.library.tkinter.colorchooser#tkinter.colorchooser.askcolor
class tkinter.colorchooser.Chooser(master=None, **options)
python.library.tkinter.colorchooser#tkinter.colorchooser.Chooser
class tkinter.commondialog.Dialog(master=None, **options) show(color=None, **options) Render the Dialog window.
python.library.dialog#tkinter.commondialog.Dialog
show(color=None, **options) Render the Dialog window.
python.library.dialog#tkinter.commondialog.Dialog.show
tkinter.dnd — Drag and drop support Source code: Lib/tkinter/dnd.py Note This is experimental and due to be deprecated when it is replaced with the Tk DND. The tkinter.dnd module provides drag-and-drop support for objects within a single application, within the same window or between windows. To enable an object to be dragged, you must create an event binding for it that starts the drag-and-drop process. Typically, you bind a ButtonPress event to a callback function that you write (see Bindings and Events). The function should call dnd_start(), where ‘source’ is the object to be dragged, and ‘event’ is the event that invoked the call (the argument to your callback function). Selection of a target object occurs as follows: Top-down search of area under mouse for target widget Target widget should have a callable dnd_accept attribute If dnd_accept is not present or returns None, search moves to parent widget If no target widget is found, then the target object is None Call to <old_target>.dnd_leave(source, event) Call to <new_target>.dnd_enter(source, event) Call to <target>.dnd_commit(source, event) to notify of drop Call to <source>.dnd_end(target, event) to signal end of drag-and-drop class tkinter.dnd.DndHandler(source, event) The DndHandler class handles drag-and-drop events tracking Motion and ButtonRelease events on the root of the event widget. cancel(event=None) Cancel the drag-and-drop process. finish(event, commit=0) Execute end of drag-and-drop functions. on_motion(event) Inspect area below mouse for target objects while drag is performed. on_release(event) Signal end of drag when the release pattern is triggered. tkinter.dnd.dnd_start(source, event) Factory function for drag-and-drop process. See also Bindings and Events
python.library.tkinter.dnd
class tkinter.dnd.DndHandler(source, event) The DndHandler class handles drag-and-drop events tracking Motion and ButtonRelease events on the root of the event widget. cancel(event=None) Cancel the drag-and-drop process. finish(event, commit=0) Execute end of drag-and-drop functions. on_motion(event) Inspect area below mouse for target objects while drag is performed. on_release(event) Signal end of drag when the release pattern is triggered.
python.library.tkinter.dnd#tkinter.dnd.DndHandler