Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/pip/http-v2/5/5/9/a/2/559a28d2d50a6d0988e3c56e5d0d411789da84005e4420f1a26bb23eAdded
- .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/_monitor.pyAdded+104
- .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/_tqdm_pandas.pyAdded+24
- .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/contrib/concurrent.pyAdded+105
- .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/contrib/utils_worker.pyAdded+38
- .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/std.pyAdded+1525
- .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/utils.pyAdded+325
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/METADATAAdded+38
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/RECORDAdded+19
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/licenses/LICENSEAdded+21
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_async_read_write.pyAdded+207
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_error.pyAdded+28
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft.pyAdded+227
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/__init__.pyAdded+12
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/_async.pyAdded+213
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/_sync.pyAdded+849
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_unix.pyAdded+116
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_windows.pyAdded+111
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/py.typedAdded
- .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/version.pyAdded+24
- .cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions-4.15.0.dist-info/METADATAAdded+72
- .cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions-4.15.0.dist-info/WHEELAdded+4
- .cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions.pyAdded
- .cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc-0.0.4.dist-info/RECORDAdded+8
- .cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc-0.0.4.dist-info/WHEELAdded+4
- .cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc/__init__.pyAdded+3
- .cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc/main.pyAdded+36
- .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/METADATAAdded+202
- .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/RECORDAdded+17
- .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/top_level.txtAdded+1
- .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11/_abnf.pyAdded+132
- .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11/_state.pyAdded+365
- .cache/uv/archive-v0/YlYoCgs7J-Rpy5AtSN3P_/httpcore/_exceptions.pyAdded+81
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/LICENSEAdded+13
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/RECORDAdded+13
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/WHEELAdded+6
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/top_level.txtAdded+1
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/zip-safeAdded+1
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/__init__.pyAdded+23
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/_core.pyAdded+11
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/nt.pyAdded+163
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/_core.pyAdded+3
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/proc.pyAdded+83
- .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/ps.pyAdded+51
- .cache/uv/archive-v0/mZts5W47V4a3dXgJR251L/idna/uts46data.pyAdded
- .cache/uv/simple-v18/pypi/certifi.rkyvAdded
- .cache/uv/simple-v18/pypi/h11.rkyvAdded
- .cache/uv/simple-v18/pypi/httpcore.rkyvAdded
- .cache/uv/simple-v18/pypi/markdown-it-py.rkyvAdded
- .cache/uv/simple-v18/pypi/mdurl.rkyvAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import atexitfrom threading import Event, Thread, current_threadfrom time import timefrom warnings import warn
__all__ = ["TMonitor", "TqdmSynchronisationWarning"]
class TqdmSynchronisationWarning(RuntimeWarning): """ tqdm multi-thread/-process errors which may cause incorrect nesting but otherwise no adverse effects """
class TMonitor(Thread): """ Monitoring thread for tqdm bars. Monitors if tqdm bars are taking too much time to display and readjusts miniters automatically if necessary.
Parameters ---------- tqdm_cls : class tqdm class to use (can be core tqdm or a submodule). sleep_interval : float Time to sleep between monitoring checks. """ _test = {} # internal vars for unit testing
def __init__(self, tqdm_cls, sleep_interval): Thread.__init__(self, name="tqdm_monitor") self.daemon = True # kill thread when main killed (KeyboardInterrupt) self.woken = 0 # last time woken up, to sync with monitor self.tqdm_cls = tqdm_cls self.sleep_interval = sleep_interval self._time = self._test.get("time", time) self.was_killed = self._test.get("Event", Event)() atexit.register(self._atexit_signal) self.start()
def _atexit_signal(self): """ Non-joining shutdown signal. Avoids deadlocks at interpreter exit from other threads, dead forks, etc. This daemon thread is auto-reaped on shutdown without needing a join. """ self.was_killed.set()
def exit(self): self.was_killed.set() if self is not current_thread(): self.join() return self.report()
def get_instances(self): # returns a copy of started `tqdm_cls` instances return [i for i in self.tqdm_cls._instances.copy() # Avoid race by checking that the instance started if hasattr(i, 'start_t')]
def run(self): cur_t = self._time() while True: # After processing and before sleeping, notify that we woke # Need to be done just before sleeping self.woken = cur_t # Sleep some time... self.was_killed.wait(self.sleep_interval) # Quit if killed if self.was_killed.is_set(): return # Then monitor! # Acquire lock (to access _instances) with self.tqdm_cls.get_lock(): cur_t = self._time() # Check tqdm instances are waiting too long to print instances = self.get_instances() for instance in instances: # Check event in loop to reduce blocking time on exit if self.was_killed.is_set(): return # Only if mininterval > 1 (else iterations are just slow) # and last refresh exceeded maxinterval if ( instance.miniters > 1 and (cur_t - instance.last_print_t) >= instance.maxinterval ): # force bypassing miniters on next iteration # (dynamic_miniters adjusts mininterval automatically) instance.miniters = 1 # Refresh now! (works only for manual tqdm) instance.refresh(nolock=True) # Remove accidental long-lived strong reference del instance if instances != self.get_instances(): # pragma: nocover warn("Set changed size during iteration" + " (see https://github.com/tqdm/tqdm/issues/481)", TqdmSynchronisationWarning, stacklevel=2) # Remove accidental long-lived strong references del instances
def report(self): return not self.was_killed.is_set()123456789101112131415161718192021222324import sys
__author__ = "github.com/casperdcl"__all__ = ['tqdm_pandas']
def tqdm_pandas(tclass, **tqdm_kwargs): """ Registers the given `tqdm` instance with `pandas.core.groupby.DataFrameGroupBy.progress_apply`. """ from tqdm import TqdmDeprecationWarning
if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith( 'tqdm_')): # delayed adapter case TqdmDeprecationWarning( "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.", fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write)) tclass.pandas(**tqdm_kwargs) else: TqdmDeprecationWarning( "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.", fp_write=getattr(tclass.fp, 'write', sys.stderr.write)) type(tclass).pandas(deprecated_t=tclass)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""Thin wrappers around `concurrent.futures`."""from contextlib import contextmanagerfrom operator import length_hintfrom os import cpu_count
from ..auto import tqdm as tqdm_autofrom ..std import TqdmWarning
__author__ = {"github.com/": ["casperdcl"]}__all__ = ['thread_map', 'process_map']
@contextmanagerdef ensure_lock(tqdm_class, lock_name=""): """get (create if necessary) and then restore `tqdm_class`'s lock""" old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock lock = old_lock or tqdm_class.get_lock() # maybe create a new lock lock = getattr(lock, lock_name, lock) # maybe subtype tqdm_class.set_lock(lock) yield lock if old_lock is None: del tqdm_class._lock else: tqdm_class.set_lock(old_lock)
def _executor_map(PoolExecutor, fn, *iterables, **tqdm_kwargs): """ Implementation of `thread_map` and `process_map`.
Parameters ---------- tqdm_class : [default: tqdm.auto.tqdm]. max_workers : [default: min(32, cpu_count() + 4)]. chunksize : [default: 1]. lock_name : [default: "":str]. """ kwargs = tqdm_kwargs.copy() if "total" not in kwargs: kwargs["total"] = length_hint(iterables[0]) tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) max_workers = kwargs.pop("max_workers", min(32, cpu_count() + 4)) chunksize = kwargs.pop("chunksize", 1) lock_name = kwargs.pop("lock_name", "") with ensure_lock(tqdm_class, lock_name=lock_name) as lk: # share lock in case workers are already using `tqdm` with PoolExecutor(max_workers=max_workers, initializer=tqdm_class.set_lock, initargs=(lk,)) as ex: return list(tqdm_class(ex.map(fn, *iterables, chunksize=chunksize), **kwargs))
def thread_map(fn, *iterables, **tqdm_kwargs): """ Equivalent of `list(map(fn, *iterables))` driven by `concurrent.futures.ThreadPoolExecutor`.
Parameters ---------- tqdm_class : optional `tqdm` class to use for bars [default: tqdm.auto.tqdm]. max_workers : int, optional Maximum number of workers to spawn; passed to `concurrent.futures.ThreadPoolExecutor.__init__`. [default: max(32, cpu_count() + 4)]. """ from concurrent.futures import ThreadPoolExecutor return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs)
def process_map(fn, *iterables, **tqdm_kwargs): """ Equivalent of `list(map(fn, *iterables))` driven by `concurrent.futures.ProcessPoolExecutor`.
Parameters ---------- tqdm_class : optional `tqdm` class to use for bars [default: tqdm.auto.tqdm]. max_workers : int, optional Maximum number of workers to spawn; passed to `concurrent.futures.ProcessPoolExecutor.__init__`. [default: min(32, cpu_count() + 4)]. chunksize : int, optional Size of chunks sent to worker processes; passed to `concurrent.futures.ProcessPoolExecutor.map`. [default: 1]. lock_name : str, optional Member of `tqdm_class.get_lock()` to use [default: mp_lock]. """ from concurrent.futures import ProcessPoolExecutor if iterables and "chunksize" not in tqdm_kwargs: # default `chunksize=1` has poor performance for large iterables # (most time spent dispatching items to workers). longest_iterable_len = max(map(length_hint, iterables)) if longest_iterable_len > 1000: from warnings import warn warn("Iterable length %d > 1000 but `chunksize` is not set." " This may seriously degrade multiprocess performance." " Set `chunksize=1` or more." % longest_iterable_len, TqdmWarning, stacklevel=2) if "lock_name" not in tqdm_kwargs: tqdm_kwargs = tqdm_kwargs.copy() tqdm_kwargs["lock_name"] = "mp_lock" return _executor_map(ProcessPoolExecutor, fn, *iterables, **tqdm_kwargs)1234567891011121314151617181920212223242526272829303132333435363738"""IO/concurrency helpers for `tqdm.contrib`."""from collections import dequefrom concurrent.futures import ThreadPoolExecutor
from ..auto import tqdm as tqdm_auto
__author__ = {"github.com/": ["casperdcl"]}__all__ = ['MonoWorker']
class MonoWorker: """ Supports one running task and one waiting task. The waiting task is the most recent submitted (others are discarded). """ def __init__(self): self.pool = ThreadPoolExecutor(max_workers=1) self.futures = deque([], 2)
def submit(self, func, *args, **kwargs): """`func(*args, **kwargs)` may replace currently waiting task.""" futures = self.futures if len(futures) == futures.maxlen: running = futures.popleft() if not running.done(): if len(futures): # clear waiting waiting = futures.pop() waiting.cancel() futures.appendleft(running) # re-insert running try: waiting = self.pool.submit(func, *args, **kwargs) except Exception as e: tqdm_auto.write(str(e)) else: futures.append(waiting) return waiting1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525"""Customisable progressbar decorator for iterators.Includes a default `range` iterator printing to `stderr`.
Usage:>>> from tqdm import trange, tqdm>>> for i in trange(10):... ..."""import sysfrom collections import OrderedDict, defaultdictfrom contextlib import contextmanagerfrom datetime import datetime, timedelta, timezonefrom numbers import Numberfrom time import timefrom warnings import warnfrom weakref import WeakSet
from ._monitor import TMonitorfrom .utils import ( CallbackIOWrapper, Comparable, DisableOnWriteError, FormatReplace, SimpleTextIOWrapper, _is_ascii, _screen_shape_wrapper, _supports_unicode, _term_move_up, disp_len, disp_trim, envwrap)
__author__ = "https://github.com/tqdm/tqdm#contributions"__all__ = ['tqdm', 'trange', 'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning', 'TqdmExperimentalWarning', 'TqdmDeprecationWarning', 'TqdmMonitorWarning']
class TqdmTypeError(TypeError): pass
class TqdmKeyError(KeyError): pass
class TqdmWarning(Warning): """base class for all tqdm warnings.
Used for non-external-code-breaking errors, such as garbled printing. """ def __init__(self, msg, fp_write=None): # noqa: B042 if fp_write is not None: fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n') else: super().__init__(msg)
class TqdmExperimentalWarning(TqdmWarning, FutureWarning): """beta feature, unstable API and behaviour"""
class TqdmDeprecationWarning(TqdmWarning, DeprecationWarning): """may be removed in a future release""" # not suppressed if raised
class TqdmMonitorWarning(TqdmWarning, RuntimeWarning): """tqdm monitor errors which do not affect external functionality"""
def TRLock(*args, **kwargs): """threading RLock""" try: from threading import RLock return RLock(*args, **kwargs) except (ImportError, OSError): # pragma: no cover pass
class TqdmDefaultWriteLock: """ Provide a default write lock for thread and multiprocessing safety. Works only on platforms supporting `fork` (so Windows is excluded). You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance before forking in order for the write lock to work. On Windows, you need to supply the lock from the parent to the children as an argument to joblib or the parallelism lib you use. """ # global thread lock so no setup required for multithreading. # NB: Do not create multiprocessing lock as it sets the multiprocessing # context, disallowing `spawn()`/`forkserver()` th_lock = TRLock()
def __init__(self): # Create global parallelism locks to avoid racing issues with parallel # bars works only if fork available (Linux/MacOSX, but not Windows) cls = type(self) root_lock = cls.th_lock if root_lock is not None: root_lock.acquire() cls.create_mp_lock() self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None] if root_lock is not None: root_lock.release()
def acquire(self, *a, **k): for lock in self.locks: lock.acquire(*a, **k)
def release(self): for lock in self.locks[::-1]: # Release in inverse order of acquisition lock.release()
def __enter__(self): self.acquire()
def __exit__(self, *exc): self.release()
@classmethod def create_mp_lock(cls): if not hasattr(cls, 'mp_lock'): try: from multiprocessing import RLock cls.mp_lock = RLock() except (ImportError, OSError): # pragma: no cover cls.mp_lock = None
@classmethod def create_th_lock(cls): assert hasattr(cls, 'th_lock') warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2)
class Bar: """ `str.format`-able bar with format specifiers: `[width][type]`
- `width` + unspecified (default): use `self.default_len` + `int >= 0`: overrides `self.default_len` + `int < 0`: subtract from `self.default_len` - `type` + `a`: ascii (`charset=self.ASCII` override) + `u`: unicode (`charset=self.UTF` override) + `b`: blank (`charset=" "` override) """ ASCII = " 123456789#" UTF = " " + ''.join(map(chr, range(0x258F, 0x2587, -1))) BLANK = " " COLOUR_RESET = '\x1b[0m' COLOUR_RGB = '\x1b[38;2;%d;%d;%dm' COLOURS = {'BLACK': '\x1b[30m', 'RED': '\x1b[31m', 'GREEN': '\x1b[32m', 'YELLOW': '\x1b[33m', 'BLUE': '\x1b[34m', 'MAGENTA': '\x1b[35m', 'CYAN': '\x1b[36m', 'WHITE': '\x1b[37m'}
def __init__(self, frac, default_len=10, charset=UTF, colour=None): if not 0 <= frac <= 1: warn("clamping frac to range [0, 1]", TqdmWarning, stacklevel=2) frac = max(0, min(1, frac)) assert default_len > 0 self.frac = frac self.default_len = default_len self.charset = charset self.colour = colour
@property def colour(self): return self._colour
@colour.setter def colour(self, value): if not value: self._colour = None return try: if value.upper() in self.COLOURS: self._colour = self.COLOURS[value.upper()] elif value[0] == '#' and len(value) == 7: self._colour = self.COLOUR_RGB % tuple( int(i, 16) for i in (value[1:3], value[3:5], value[5:7])) else: raise KeyError except (KeyError, AttributeError): warn(f"Unknown colour ({value}); valid choices:" f" [hex (#00ff00), {', '.join(self.COLOURS)}]", TqdmWarning, stacklevel=2) self._colour = None
def __format__(self, format_spec): if format_spec: _type = format_spec[-1].lower() try: charset = {'a': self.ASCII, 'u': self.UTF, 'b': self.BLANK}[_type] except KeyError: charset = self.charset else: format_spec = format_spec[:-1] if format_spec: N_BARS = int(format_spec) if N_BARS < 0: N_BARS += self.default_len else: N_BARS = self.default_len else: charset = self.charset N_BARS = self.default_len
nsyms = len(charset) - 1 bar_length, frac_bar_length = divmod(int(self.frac * N_BARS * nsyms), nsyms)
res = charset[-1] * bar_length if bar_length < N_BARS: # whitespace padding res = res + charset[frac_bar_length] + charset[0] * (N_BARS - bar_length - 1) return self.colour + res + self.COLOUR_RESET if self.colour else res
class EMA: """ Exponential moving average: smoothing to give progressively lower weights to older values.
Parameters ---------- smoothing : float, optional Smoothing factor in range [0, 1], [default: 0.3]. Increase to give more weight to recent values. Ranges from 0 (yields old value) to 1 (yields new value). """ def __init__(self, smoothing=0.3): self.alpha = smoothing self.last = 0 self.calls = 0
def __call__(self, x=None): """ Parameters ---------- x : float New value to include in EMA. """ beta = 1 - self.alpha if x is not None: self.last = self.alpha * x + beta * self.last self.calls += 1 return self.last / (1 - beta ** self.calls) if self.calls else self.last
class tqdm(Comparable): """ Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progressbar every time a value is requested.
Parameters ---------- iterable : iterable, optional Iterable to decorate with a progressbar. Leave blank to manually manage the updates. desc : str, optional Prefix for the progressbar. total : int or float, optional The number of expected iterations. If unspecified, len(iterable) is used if possible. If float("inf") or as a last resort, only basic progress statistics are displayed (no ETA, no progressbar). If `gui` is True and this parameter needs subsequent updating, specify an initial arbitrary large positive number, e.g. 9e9. leave : bool, optional If [default: True], keeps all traces of the progressbar upon termination of iteration. If `None`, will leave only if `position` is `0`. file : `io.TextIOWrapper` or `io.StringIO`, optional Specifies where to output the progress messages (default: sys.stderr). Uses `file.write(str)` and `file.flush()` methods. For encoding, see `write_bytes`. ncols : int, optional The width of the entire output message. If specified, dynamically resizes the progressbar to stay within this bound. If unspecified, attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats). mininterval : float, optional Minimum progress display update interval [default: 0.1] seconds. maxinterval : float, optional Maximum progress display update interval [default: 10] seconds. Automatically adjusts `miniters` to correspond to `mininterval` after long display update lag. Only works if `dynamic_miniters` or monitor thread is enabled. miniters : int or float, optional Minimum progress display update interval, in iterations. If 0 and `dynamic_miniters`, will automatically adjust to equal `mininterval` (more CPU efficient, good for tight loops). If > 0, will skip display of specified number of iterations. Tweak this and `mininterval` to get very efficient loops. If your progress is erratic with both fast and slow iterations (network, skipping items, etc) you should set miniters=1. ascii : bool or str, optional If unspecified or False, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters " 123456789#". disable : bool, optional Whether to disable the entire progressbar wrapper [default: False]. If set to None, disable on non-TTY. unit : str, optional String that will be used to define the unit of each iteration [default: it]. unit_scale : bool or int or float, optional If 1 or True, the number of iterations will be reduced/scaled automatically and a metric prefix following the International System of Units standard will be added (kilo, mega, etc.) [default: False]. If any other non-zero number, will scale `total` and `n`. dynamic_ncols : bool, optional If set, constantly alters `ncols` and `nrows` to the environment (allowing for window resizes) [default: False]. smoothing : float, optional Exponential moving average smoothing factor for speed estimates (ignored in GUI mode). Ranges from 0 (average speed) to 1 (current/instantaneous speed) [default: 0.3]. bar_format : str, optional Specify a custom bar string formatting. May impact performance. [default: '{l_bar}{bar}{r_bar}'], where l_bar='{desc}: {percentage:3.0f}%|' and r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' '{rate_fmt}{postfix}]' Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta. Note that a trailing ": " is automatically removed after {desc} if the latter is empty. initial : int or float, optional The initial counter value. Useful when restarting a progress bar [default: 0]. If using float, consider specifying `{n:.3f}` or similar in `bar_format`, or specifying `unit_scale`. position : int, optional Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads). postfix : dict or *, optional Specify additional stats to display at the end of the bar. Calls `set_postfix(**postfix)` if possible (dict). unit_divisor : float, optional [default: 1000], ignored unless `unit_scale` is True. write_bytes : bool, optional Whether to write bytes. If (default: False) will write unicode. lock_args : tuple, optional Passed to `refresh` for intermediate output (initialisation, iterating, and updating). nrows : int, optional The screen height. If specified, hides nested bars outside this bound. If unspecified, attempts to use environment height. The fallback is 20. colour : str, optional Bar colour (e.g. 'green', '#00ff00'). delay : float, optional Don't display until [default: 0] seconds have elapsed. gui : bool, optional WARNING: internal parameter - do not use. Use tqdm.gui.tqdm(...) instead. If set, will attempt to use matplotlib animations for a graphical output [default: False].
Returns ------- out : decorated iterator. """
monitor_interval = 10 # set to 0 to disable the thread monitor = None _instances = WeakSet()
@staticmethod def format_sizeof(num, suffix='', divisor=1000): """ Formats a number (greater than unity) with SI Order of Magnitude prefixes.
Parameters ---------- num : float Number ( >= 1) to format. suffix : str, optional Post-postfix [default: '']. divisor : float, optional Divisor between prefixes [default: 1000].
Returns ------- out : str Number with Order of Magnitude SI unit postfix. """ for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 999.5: if abs(num) < 99.95: if abs(num) < 9.995: return f'{num:1.2f}{unit}{suffix}' return f'{num:2.1f}{unit}{suffix}' return f'{num:3.0f}{unit}{suffix}' num /= divisor return f'{num:3.1f}Y{suffix}'
@staticmethod def format_interval(t): """ Formats a number of seconds as a clock time, [H:]MM:SS
Parameters ---------- t : int Number of seconds.
Returns ------- out : str [H:]MM:SS """ sign = '-' if t < 0 else '' mins, s = divmod(abs(int(t)), 60) h, m = divmod(mins, 60) return f'{sign}{h:d}:{m:02d}:{s:02d}' if h else f'{sign}{m:02d}:{s:02d}'
@staticmethod def format_num(n): """ Intelligent scientific notation (.3g).
Parameters ---------- n : int or float or Numeric A Number.
Returns ------- out : str Formatted number. """ f = f'{n:.3g}'.replace('e+0', 'e+').replace('e-0', 'e-') n = str(n) return f if len(f) < len(n) else n
@staticmethod def status_printer(file): """ Manage the printing and in-place updating of a line of characters. Note that if the string is longer than a line, then in-place updating may not work (it will print a new line at each refresh). """ fp = file fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover if fp in (sys.stderr, sys.stdout): getattr(sys.stderr, 'flush', lambda: None)() getattr(sys.stdout, 'flush', lambda: None)()
def fp_write(s): fp.write(str(s)) fp_flush()
last_len = [0]
def print_status(s): len_s = disp_len(s) fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0))) last_len[0] = len_s
return print_status
@staticmethod def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, # pylint: disable=redefined-builtin unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000, initial=0, colour=None, **extra_kwargs): """ Return a string-based progress bar given some parameters
Parameters ---------- n : int or float Number of finished iterations. total : int or float The expected total number of iterations. If meaningless (None), only basic progress statistics are displayed (no ETA). elapsed : float Number of seconds passed since start. ncols : int, optional The width of the entire output message. If specified, dynamically resizes `{bar}` to stay within this bound [default: None]. If `0`, will not print any bar (only stats). The fallback is `{bar:10}`. prefix : str, optional Prefix message (included in total width) [default: '']. Use as {desc} in bar_format string. ascii : bool, optional or str, optional If not set, use unicode (smooth blocks) to fill the meter [default: False]. The fallback is to use ASCII characters " 123456789#". unit : str, optional The iteration unit [default: 'it']. unit_scale : bool or int or float, optional If 1 or True, the number of iterations will be printed with an appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) [default: False]. If any other non-zero number, will scale `total` and `n`. rate : float, optional Manual override for iteration rate. If [default: None], uses n/elapsed. bar_format : str, optional Specify a custom bar string formatting. May impact performance. [default: '{l_bar}{bar}{r_bar}'], where l_bar='{desc}: {percentage:3.0f}%|' and r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' '{rate_fmt}{postfix}]' Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta. Note that a trailing ": " is automatically removed after {desc} if the latter is empty. postfix : *, optional Similar to `prefix`, but placed at the end (e.g. for additional stats). Note: postfix is usually a string (not a dict) for this method, and will if possible be set to postfix = ', ' + postfix. However other types are supported (#382). unit_divisor : float, optional [default: 1000], ignored unless `unit_scale` is True. initial : int or float, optional The initial counter value [default: 0]. colour : str, optional Bar colour (e.g. 'green', '#00ff00').
Returns ------- out : Formatted meter and stats, ready to display. """
# sanity check: total if total and n >= (total + 0.5): # allow float imprecision (#849) total = None
# apply custom scale if necessary if unit_scale and unit_scale not in (True, 1): if total: total *= unit_scale n *= unit_scale if rate: rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt unit_scale = False
elapsed_str = tqdm.format_interval(elapsed)
# if unspecified, attempt to use rate = average speed # (we allow manual override since predicting time is an arcane art) if rate is None and elapsed: rate = (n - initial) / elapsed inv_rate = 1 / rate if rate else None format_sizeof = tqdm.format_sizeof rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else f'{rate:5.2f}') if rate else '?') + unit + '/s' rate_inv_fmt = ( (format_sizeof(inv_rate) if unit_scale else f'{inv_rate:5.2f}') if inv_rate else '?') + 's/' + unit rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt
if unit_scale: n_fmt = format_sizeof(n, divisor=unit_divisor) total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?' else: n_fmt = str(n) total_fmt = str(total) if total is not None else '?'
try: postfix = ', ' + postfix if postfix else '' except TypeError: pass
remaining = (total - n) / rate if rate and total else 0 remaining_str = tqdm.format_interval(remaining) if rate else '?' try: eta_dt = (datetime.now() + timedelta(seconds=remaining) if rate and total else datetime.fromtimestamp(0, timezone.utc)) except OverflowError: eta_dt = datetime.max
# format the stats displayed to the left and right sides of the bar if prefix: # old prefix setup work around bool_prefix_colon_already = (prefix[-2:] == ": ") l_bar = prefix if bool_prefix_colon_already else prefix + ": " else: l_bar = ''
r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]'
# Custom bar formatting # Populate a dict with all available progress indicators format_dict = { # slight extension of self.format_dict 'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt, 'elapsed': elapsed_str, 'elapsed_s': elapsed, 'ncols': ncols, 'desc': prefix or '', 'unit': unit, 'rate': inv_rate if inv_rate and inv_rate > 1 else rate, 'rate_fmt': rate_fmt, 'rate_noinv': rate, 'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate, 'rate_inv_fmt': rate_inv_fmt, 'postfix': postfix, 'unit_divisor': unit_divisor, 'colour': colour, # plus more useful definitions 'remaining': remaining_str, 'remaining_s': remaining, 'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt, **extra_kwargs}
# total is known: we can predict some stats if total: # fractional and percentage progress frac = n / total percentage = frac * 100
l_bar += f'{percentage:3.0f}%|'
if ncols == 0: return l_bar[:-1] + r_bar[1:]
format_dict.update(l_bar=l_bar) if bar_format: format_dict.update(percentage=percentage)
# auto-remove colon for empty `{desc}` if not prefix: bar_format = bar_format.replace("{desc}: ", '') else: bar_format = "{l_bar}{bar}{r_bar}"
full_bar = FormatReplace() nobar = bar_format.format(bar=full_bar, **format_dict) if not full_bar.format_called: return nobar # no `{bar}`; nothing else to do
# Formatting progress bar space available for bar's display full_bar = Bar(frac, max(1, ncols - disp_len(nobar)) if ncols else 10, charset=Bar.ASCII if ascii is True else ascii or Bar.UTF, colour=colour) if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): bar_format = str(bar_format) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res
elif bar_format: # user-specified bar_format but no total l_bar += '|' format_dict.update(l_bar=l_bar, percentage=0) full_bar = FormatReplace() nobar = bar_format.format(bar=full_bar, **format_dict) if not full_bar.format_called: return nobar full_bar = Bar(0, max(1, ncols - disp_len(nobar)) if ncols else 10, charset=Bar.BLANK, colour=colour) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res else: # no total: no progressbar, ETA, just progress stats return (f'{(prefix + ": ") if prefix else ""}' f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]')
def __new__(cls, *_, **__): instance = object.__new__(cls) with cls.get_lock(): # also constructs lock if non-existent cls._instances.add(instance) # create monitoring thread if cls.monitor_interval and (cls.monitor is None or not cls.monitor.report()): try: cls.monitor = TMonitor(cls, cls.monitor_interval) except Exception as e: # pragma: nocover warn("tqdm:disabling monitor support" " (monitor_interval = 0) due to:\n" + str(e), TqdmMonitorWarning, stacklevel=2) cls.monitor_interval = 0 return instance
@classmethod def _get_free_pos(cls, instance=None): """Skips specified instance.""" positions = {abs(inst.pos) for inst in cls._instances if inst is not instance and hasattr(inst, "pos")} return min(set(range(len(positions) + 1)).difference(positions))
@classmethod def _decr_instances(cls, instance): """ Remove from list and reposition another unfixed bar to fill the new gap.
This means that by default (where all nested bars are unfixed), order is not maintained but screen flicker/blank space is minimised. (tqdm<=4.44.1 moved ALL subsequent unfixed bars up.) """ with cls._lock: try: cls._instances.remove(instance) except KeyError: # if not instance.gui: # pragma: no cover # raise pass # py2: maybe magically removed already # else: if not instance.gui: last = (instance.nrows or 20) - 1 # find unfixed (`pos >= 0`) overflow (`pos >= nrows - 1`) instances = list(filter( lambda i: hasattr(i, "pos") and last <= i.pos, cls._instances)) # set first found to current `pos` if instances: inst = min(instances, key=lambda i: i.pos) inst.clear(nolock=True) inst.pos = abs(instance.pos)
@classmethod def write(cls, s, file=None, end="\n", nolock=False): """Print a message via tqdm (without overlap with bars).""" fp = file if file is not None else sys.stdout with cls.external_write_mode(file=file, nolock=nolock): # Write the message fp.write(s) fp.write(end)
@classmethod @contextmanager def external_write_mode(cls, file=None, nolock=False): """ Disable tqdm within context and refresh tqdm when exits. Useful when writing to standard output stream """ fp = file if file is not None else sys.stdout
try: if not nolock: cls.get_lock().acquire() # Clear all bars inst_cleared = [] for inst in getattr(cls, '_instances', []): # Clear instance if in the target output file # or if write output + tqdm output are both either # sys.stdout or sys.stderr (because both are mixed in terminal) if hasattr(inst, "start_t") and (inst.fp == fp or all( f in (sys.stdout, sys.stderr) for f in (fp, inst.fp))): inst.clear(nolock=True) inst_cleared.append(inst) yield # Force refresh display of bars we cleared for inst in inst_cleared: inst.refresh(nolock=True) finally: if not nolock: cls._lock.release()
@classmethod def set_lock(cls, lock): """Set the global lock.""" cls._lock = lock
@classmethod def get_lock(cls): """Get the global lock. Construct it if it does not exist.""" if not hasattr(cls, '_lock'): cls._lock = TqdmDefaultWriteLock() return cls._lock
@classmethod def pandas(cls, **tqdm_kwargs): """ Registers the current `tqdm` class with pandas.core. ( frame.DataFrame | series.Series | groupby.(generic.)DataFrameGroupBy | groupby.(generic.)SeriesGroupBy ).progress_apply
A new instance will be created every time `progress_apply` is called, and each instance will automatically `close()` upon completion.
Parameters ---------- tqdm_kwargs : arguments for the tqdm instance
Examples -------- >>> import pandas as pd >>> import numpy as np >>> from tqdm import tqdm >>> from tqdm.gui import tqdm as tqdm_gui >>> >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6))) >>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc >>> # Now you can use `progress_apply` instead of `apply` >>> df.groupby(0).progress_apply(lambda x: x**2)
References ---------- <https://stackoverflow.com/questions/18603270/\ progress-indicator-during-pandas-operations-python> """ from warnings import catch_warnings, simplefilter
from pandas.core.frame import DataFrame from pandas.core.series import Series try: with catch_warnings(): simplefilter("ignore", category=FutureWarning) from pandas import Panel except ImportError: # pandas>=1.2.0 Panel = None Rolling, Expanding = None, None try: # pandas>=1.0.0 from pandas.core.window.rolling import _Rolling_and_Expanding except ImportError: try: # pandas>=0.18.0 from pandas.core.window import _Rolling_and_Expanding except ImportError: # pandas>=1.2.0 try: # pandas>=1.2.0 from pandas.core.window.expanding import Expanding from pandas.core.window.rolling import Rolling _Rolling_and_Expanding = Rolling, Expanding except ImportError: # pragma: no cover _Rolling_and_Expanding = None try: # pandas>=0.25.0 from pandas.core.groupby.generic import SeriesGroupBy # , NDFrameGroupBy from pandas.core.groupby.generic import DataFrameGroupBy except ImportError: # pragma: no cover try: # pandas>=0.23.0 from pandas.core.groupby.groupby import DataFrameGroupBy, SeriesGroupBy except ImportError: from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy try: # pandas>=0.23.0 from pandas.core.groupby.groupby import GroupBy except ImportError: # pragma: no cover from pandas.core.groupby import GroupBy
try: # pandas>=0.23.0 from pandas.core.groupby.groupby import PanelGroupBy except ImportError: try: from pandas.core.groupby import PanelGroupBy except ImportError: # pandas>=0.25.0 PanelGroupBy = None
tqdm_kwargs = tqdm_kwargs.copy() deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)]
def inner_generator(df_function='apply'): def inner(df, func, *args, **kwargs): """ Parameters ---------- df : (DataFrame|Series)[GroupBy] Data (may be grouped). func : function To be applied on the (grouped) data. **kwargs : optional Transmitted to `df.apply()`. """
# Precompute total iterations total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None)) if total is None: # not grouped if df_function == 'applymap': total = df.size elif isinstance(df, Series): total = len(df) elif (_Rolling_and_Expanding is None or not isinstance(df, _Rolling_and_Expanding)): # DataFrame or Panel axis = kwargs.get('axis', 0) if axis == 'index': axis = 0 elif axis == 'columns': axis = 1 # when axis=0, total is shape[axis1] total = df.size // df.shape[axis]
# Init bar if deprecated_t[0] is not None: t = deprecated_t[0] deprecated_t[0] = None else: t = cls(total=total, **tqdm_kwargs)
if len(args) > 0: # *args intentionally not supported (see #244, #299) TqdmDeprecationWarning( "Except func, normal arguments are intentionally" + " not supported by" + " `(DataFrame|Series|GroupBy).progress_apply`." + " Use keyword arguments instead.", fp_write=getattr(t.fp, 'write', sys.stderr.write))
try: # pandas>=1.3.0,<3.0 from pandas.core.common import is_builtin_func except ImportError: # pandas<1.3.0 is_builtin_func = getattr(df, '_is_builtin_func', lambda f: f) try: func = is_builtin_func(func) except TypeError: pass
# Define bar updating wrapper def wrapper(*args, **kwargs): # update tbar correctly # it seems `pandas apply` calls `func` twice # on the first column/row to decide whether it can # take a fast or slow code path; so stop when t.total==t.n t.update(n=1 if not t.total or t.n < t.total else 0) return func(*args, **kwargs)
# Apply the provided function (in **kwargs) # on the df using our wrapper (which provides bar updating) try: return getattr(df, df_function)(wrapper, **kwargs) finally: t.close()
return inner
# Monkeypatch pandas to provide easy methods # Enable custom tqdm progress in pandas! Series.progress_apply = inner_generator() SeriesGroupBy.progress_apply = inner_generator() Series.progress_map = inner_generator('map') SeriesGroupBy.progress_map = inner_generator('map')
DataFrame.progress_apply = inner_generator() DataFrameGroupBy.progress_apply = inner_generator() DataFrame.progress_applymap = inner_generator('applymap') DataFrame.progress_map = inner_generator('map') DataFrameGroupBy.progress_map = inner_generator('map')
if Panel is not None: Panel.progress_apply = inner_generator() if PanelGroupBy is not None: PanelGroupBy.progress_apply = inner_generator()
GroupBy.progress_apply = inner_generator() GroupBy.progress_aggregate = inner_generator('aggregate') GroupBy.progress_transform = inner_generator('transform')
if Rolling is not None and Expanding is not None: Rolling.progress_apply = inner_generator() Expanding.progress_apply = inner_generator() elif _Rolling_and_Expanding is not None: _Rolling_and_Expanding.progress_apply = inner_generator()
# override defaults via env vars @envwrap("tqdm", is_method=True, types={'total': float, 'ncols': int, 'miniters': float, 'position': int, 'nrows': int}) def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=False, # pylint: disable=redefined-builtin disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, write_bytes=False, lock_args=None, nrows=None, colour=None, delay=0.0, gui=False, **kwargs): """see tqdm.tqdm for arguments""" if file is None: file = sys.stderr
if write_bytes: # Despite coercing unicode into bytes, py2 sys.std* streams # should have bytes written to them. file = SimpleTextIOWrapper( file, encoding=getattr(file, 'encoding', None) or 'utf-8')
file = DisableOnWriteError(file, tqdm_instance=self)
if disable is None and hasattr(file, "isatty") and not file.isatty(): disable = True
if total is None and iterable is not None: try: total = len(iterable) except (TypeError, AttributeError): total = None if total == float("inf"): # Infinite iterations, behave same as unknown total = None
if disable: self.iterable = iterable self.disable = disable with self._lock: self.pos = self._get_free_pos(self) self._instances.remove(self) self.n = initial self.total = total self.leave = leave return
if kwargs: self.disable = True with self._lock: self.pos = self._get_free_pos(self) self._instances.remove(self) raise ( TqdmDeprecationWarning( "`nested` is deprecated and automated.\n" "Use `position` instead for manual control.\n", fp_write=getattr(file, 'write', sys.stderr.write)) if "nested" in kwargs else TqdmKeyError("Unknown argument(s): " + str(kwargs)))
# Preprocess the arguments if ( (ncols is None or nrows is None) and (file in (sys.stderr, sys.stdout)) ) or dynamic_ncols: # pragma: no cover if dynamic_ncols: dynamic_ncols = _screen_shape_wrapper() if dynamic_ncols: ncols, nrows = dynamic_ncols(file) else: _dynamic_ncols = _screen_shape_wrapper() if _dynamic_ncols: _ncols, _nrows = _dynamic_ncols(file) if ncols is None: ncols = _ncols if nrows is None: nrows = _nrows
if miniters is None: miniters = 0 dynamic_miniters = True else: dynamic_miniters = False
if mininterval is None: mininterval = 0
if maxinterval is None: maxinterval = 0
if ascii is None: ascii = not _supports_unicode(file)
if bar_format and ascii is not True and not _is_ascii(ascii): # Convert bar format into unicode since terminal uses unicode bar_format = str(bar_format)
if smoothing is None: smoothing = 0
# Store the arguments self.iterable = iterable self.desc = desc or '' self.total = total self.leave = leave self.fp = file self.ncols = ncols self.nrows = nrows self.mininterval = mininterval self.maxinterval = maxinterval self.miniters = miniters self.dynamic_miniters = dynamic_miniters self.ascii = ascii self.disable = disable self.unit = unit self.unit_scale = unit_scale self.unit_divisor = unit_divisor self.initial = initial self.lock_args = lock_args self.delay = delay self.gui = gui self.dynamic_ncols = dynamic_ncols self.smoothing = smoothing self._ema_dn = EMA(smoothing) self._ema_dt = EMA(smoothing) self._ema_miniters = EMA(smoothing) self.bar_format = bar_format self.postfix = None self.colour = colour self._time = time if postfix: try: self.set_postfix(refresh=False, **postfix) except TypeError: self.postfix = postfix
# Init the iterations counters self.last_print_n = initial self.n = initial
# if nested, at initial sp() call we replace '\r' by '\n' to # not overwrite the outer progress bar with self._lock: # mark fixed positions as negative self.pos = self._get_free_pos(self) if position is None else -position
if not gui: # Initialize the screen printer self.sp = self.status_printer(self.fp) if delay <= 0: self.refresh(lock_args=self.lock_args)
# Init the time counter self.last_print_t = self._time() # NB: Avoid race conditions by setting start_t at the very end of init self.start_t = self.last_print_t
def __bool__(self): if self.total is not None: return self.total > 0 if self.iterable is None: raise TypeError('bool() undefined when iterable == total == None') return bool(self.iterable)
def __len__(self): return ( self.total if self.iterable is None else self.iterable.shape[0] if hasattr(self.iterable, "shape") else len(self.iterable) if hasattr(self.iterable, "__len__") else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__") else getattr(self, "total", None))
def __reversed__(self): try: orig = self.iterable except AttributeError: raise TypeError("'tqdm' object is not reversible") else: self.iterable = reversed(self.iterable) return self.__iter__() finally: self.iterable = orig
def __contains__(self, item): contains = getattr(self.iterable, '__contains__', None) return (contains(item) if contains is not None # pylint: disable=not-callable else item in self.__iter__())
def __enter__(self): return self
def __exit__(self, exc_type, exc_value, traceback): try: self.close() except AttributeError: # maybe eager thread cleanup upon external error if (exc_type, exc_value, traceback) == (None, None, None): raise warn("AttributeError ignored", TqdmWarning, stacklevel=2)
def __del__(self): self.close()
def __str__(self): return self.format_meter(**self.format_dict)
@property def _comparable(self): return abs(getattr(self, "pos", 1 << 31))
def __hash__(self): return id(self)
def __iter__(self): """Backward-compatibility to use: for x in tqdm(iterable)"""
# Inlining instance variables as locals (speed optimisation) iterable = self.iterable
# If the bar is disabled, then just walk the iterable # (note: keep this check outside the loop for performance) if self.disable: for obj in iterable: yield obj return
mininterval = self.mininterval last_print_t = self.last_print_t last_print_n = self.last_print_n min_start_t = self.start_t + self.delay n = self.n time = self._time
try: for obj in iterable: yield obj # Update and possibly print the progressbar. # Note: does not call self.update(1) for speed optimisation. n += 1
if n - last_print_n >= self.miniters: cur_t = time() dt = cur_t - last_print_t if dt >= mininterval and cur_t >= min_start_t: self.update(n - last_print_n) last_print_n = self.last_print_n last_print_t = self.last_print_t finally: self.n = n self.close()
def update(self, n=1): """ Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: ... ... ... t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if `t.update()` will be called in such a way that `filesize` will be exactly reached and printed.
Parameters ---------- n : int or float, optional Increment to add to the internal counter of iterations [default: 1]. If using float, consider specifying `{n:.3f}` or similar in `bar_format`, or specifying `unit_scale`.
Returns ------- out : bool or None True if a `display()` was triggered. """ if self.disable: return
if n < 0: self.last_print_n += n # for auto-refresh logic to work self.n += n
# check counter first to reduce calls to time() if self.n - self.last_print_n >= self.miniters: cur_t = self._time() dt = cur_t - self.last_print_t if dt >= self.mininterval and cur_t >= self.start_t + self.delay: cur_t = self._time() dn = self.n - self.last_print_n # >= n if self.smoothing and dt and dn: # EMA (not just overall average) self._ema_dn(dn) self._ema_dt(dt) self.refresh(lock_args=self.lock_args) if self.dynamic_miniters: # If no `miniters` was specified, adjust automatically to the # maximum iteration rate seen so far between two prints. # e.g.: After running `tqdm.update(5)`, subsequent # calls to `tqdm.update()` will only cause an update after # at least 5 more iterations. if self.maxinterval and dt >= self.maxinterval: self.miniters = dn * (self.mininterval or self.maxinterval) / dt elif self.smoothing: # EMA miniters update self.miniters = self._ema_miniters( dn * (self.mininterval / dt if self.mininterval and dt else 1)) else: # max iters between two prints self.miniters = max(self.miniters, dn)
# Store old values for next call self.last_print_n = self.n self.last_print_t = cur_t return True
def close(self): """Cleanup and (if leave=False) close the progressbar.""" if self.disable: return
# Prevent multiple closures self.disable = True
# decrement instance pos and remove from internal set pos = abs(self.pos) self._decr_instances(self)
if self.last_print_t < self.start_t + self.delay: # haven't ever displayed; nothing to clear return
# GUI mode if getattr(self, 'sp', None) is None: return
# annoyingly, _supports_unicode isn't good enough def fp_write(s): self.fp.write(str(s))
try: fp_write('') except ValueError as e: if 'closed' in str(e): return raise # pragma: no cover
leave = pos == 0 if self.leave is None else self.leave
with self._lock: if leave: # stats for overall rate (no weighted average) self._ema_dt = lambda: None self.display(pos=0) fp_write('\n') else: # clear previous display if self.display(msg='', pos=pos) and not pos: fp_write('\r')
def clear(self, nolock=False): """Clear current bar display.""" if self.disable: return
if not nolock: self._lock.acquire() pos = abs(self.pos) if pos < (self.nrows or 20): self.moveto(pos) self.sp('') self.fp.write('\r') # place cursor back at the beginning of line self.moveto(-pos) if not nolock: self._lock.release()
def refresh(self, nolock=False, lock_args=None): """ Force refresh the display of this bar.
Parameters ---------- nolock : bool, optional If `True`, does not lock. If [default: `False`]: calls `acquire()` on internal lock. lock_args : tuple, optional Passed to internal lock's `acquire()`. If specified, will only `display()` if `acquire()` returns `True`. """ if self.disable: return
if not nolock: if lock_args: if not self._lock.acquire(*lock_args): return False else: self._lock.acquire() self.display() if not nolock: self._lock.release() return True
def unpause(self): """Restart tqdm timer from last print time.""" if self.disable: return cur_t = self._time() self.start_t += cur_t - self.last_print_t self.last_print_t = cur_t
def reset(self, total=None): """ Resets to 0 iterations for repeated use.
Consider combining with `leave=True`.
Parameters ---------- total : int or float, optional. Total to use for the new bar. """ self.n = 0 if total is not None: self.total = total if self.disable: return self.last_print_n = 0 self.last_print_t = self.start_t = self._time() self._ema_dn = EMA(self.smoothing) self._ema_dt = EMA(self.smoothing) self._ema_miniters = EMA(self.smoothing) self.refresh()
def set_description(self, desc=None, refresh=True): """ Set/modify description of the progress bar.
Parameters ---------- desc : str, optional refresh : bool, optional Forces refresh [default: True]. """ self.desc = desc + ': ' if desc else '' if refresh: self.refresh()
def set_description_str(self, desc=None, refresh=True): """Set/modify description without ': ' appended.""" self.desc = desc or '' if refresh: self.refresh()
def set_postfix(self, ordered_dict=None, refresh=True, **kwargs): """ Set/modify postfix (additional stats) with automatic formatting based on datatype.
Parameters ---------- ordered_dict : dict or OrderedDict, optional refresh : bool, optional Forces refresh [default: True]. kwargs : dict, optional """ # Sort in alphabetical order to be more deterministic postfix = OrderedDict([] if ordered_dict is None else ordered_dict) for key in sorted(kwargs.keys()): postfix[key] = kwargs[key] # Preprocess stats according to datatype for key in postfix.keys(): # Number: limit the length of the string if isinstance(postfix[key], Number): postfix[key] = self.format_num(postfix[key]) # Else for any other type, try to get the string conversion elif not isinstance(postfix[key], str): postfix[key] = str(postfix[key]) # Else if it's a string, don't need to preprocess anything # Stitch together to get the final postfix self.postfix = ', '.join(key + '=' + postfix[key].strip() for key in postfix.keys()) if refresh: self.refresh()
def set_postfix_str(self, s='', refresh=True): """ Postfix without dictionary expansion, similar to prefix handling. """ self.postfix = str(s) if refresh: self.refresh()
def moveto(self, n): # TODO: private method self.fp.write('\n' * n + _term_move_up() * -n) getattr(self.fp, 'flush', lambda: None)()
@property def format_dict(self): """Public API for read-only member access.""" if self.disable and not hasattr(self, 'unit'): return defaultdict(lambda: None, { 'n': self.n, 'total': self.total, 'elapsed': 0, 'unit': 'it'}) if self.dynamic_ncols: self.ncols, self.nrows = self.dynamic_ncols(self.fp) return { 'n': self.n, 'total': self.total, 'elapsed': self._time() - self.start_t if hasattr(self, 'start_t') else 0, 'ncols': self.ncols, 'nrows': self.nrows, 'prefix': self.desc, 'ascii': self.ascii, 'unit': self.unit, 'unit_scale': self.unit_scale, 'rate': self._ema_dn() / self._ema_dt() if self._ema_dt() else None, 'bar_format': self.bar_format, 'postfix': self.postfix, 'unit_divisor': self.unit_divisor, 'initial': self.initial, 'colour': self.colour}
def display(self, msg=None, pos=None): """ Use `self.sp` to display `msg` in the specified `pos`.
Consider overloading this function when inheriting to use e.g.: `self.some_frontend(**self.format_dict)` instead of `self.sp`.
Parameters ---------- msg : str, optional. What to display (default: `repr(self)`). pos : int, optional. Position to `moveto` (default: `abs(self.pos)`). """ if pos is None: pos = abs(self.pos)
nrows = self.nrows or 20 if pos >= nrows - 1: if pos >= nrows: return False if msg or msg is None: # override at `nrows - 1` msg = " ... (more hidden) ..."
if not hasattr(self, "sp"): raise TqdmDeprecationWarning( "Please use `tqdm.gui.tqdm(...)`" " instead of `tqdm(..., gui=True)`\n", fp_write=getattr(self.fp, 'write', sys.stderr.write))
if pos: self.moveto(pos) self.sp(self.__str__() if msg is None else msg) if pos: self.moveto(-pos) return True
@classmethod @contextmanager def wrapattr(cls, stream, method, total=None, bytes=True, # pylint: disable=redefined-builtin **tqdm_kwargs): """ stream : file-like object. method : str, "read" or "write". The result of `read()` and the first argument of `write()` should have a `len()`.
>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj: ... while True: ... chunk = fobj.read(chunk_size) ... if not chunk: ... break """ with cls(total=total, **tqdm_kwargs) as t: if bytes: t.unit = "B" t.unit_scale = True t.unit_divisor = 1024 yield CallbackIOWrapper(t.update, stream, method)
def trange(*args, **kwargs): """Shortcut for tqdm(range(*args), **kwargs).""" return tqdm(range(*args), **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325"""General helpers required for `tqdm.std`."""import osimport reimport sysfrom functools import partial, partialmethod, wrapsfrom inspect import signature# TODO consider using wcswidth third-party package for 0-width charactersfrom unicodedata import east_asian_widthfrom warnings import warnfrom weakref import proxy
_range, _unich, _unicode, _basestring = range, chr, str, strCUR_OS = sys.platformIS_WIN = any(CUR_OS.startswith(i) for i in ['win32', 'cygwin'])IS_NIX = any(CUR_OS.startswith(i) for i in ['aix', 'linux', 'darwin', 'freebsd'])RE_ANSI = re.compile(r"\x1b\[[;\d]*[A-Za-z]")
try: if IS_WIN: import colorama else: raise ImportErrorexcept ImportError: colorama = Noneelse: try: colorama.init(strip=False) except TypeError: colorama.init()
try: from envwrap import envwrap # pylint: disable=unused-importexcept ModuleNotFoundError: def envwrap(name, app="", types=None, is_method=False): """ Basic (env-var-only) version of `envwrap <https://github.com/tqdm/envwrap>`_. Install ``envwrap`` for config file support. """ if types is None: types = {} if name[-1] == "_": name = name[:-1] warn("Trailing underscore in `name` is automatic", DeprecationWarning, stacklevel=2) prefixes = (name, f"{name}_{app}") if app else (name,) env_overrides = {} for prefix in prefixes: prefix = prefix.upper() + "_" i = len(prefix) env_overrides.update( (k[i:].lower(), v) for k, v in os.environ.items() if k.startswith(prefix)) part = partialmethod if is_method else partial
def wrap(func): params = signature(func).parameters # ignore unknown env vars overrides = {k: v for k, v in env_overrides.items() if k in params} # infer overrides' `type`s for k in overrides: param = params[k] if param.annotation is not param.empty: # typehints for typ in getattr(param.annotation, '__args__', (param.annotation,)): try: overrides[k] = typ(overrides[k]) except Exception: pass else: break elif param.default is not None: # type of default value overrides[k] = type(param.default)(overrides[k]) else: try: # `types` fallback overrides[k] = types[k](overrides[k]) except KeyError: # keep unconverted (`str`) pass return part(func, **overrides) return wrap
class FormatReplace: """ >>> a = FormatReplace('something') >>> f"{a:5d}" 'something' """ # NOQA: P102 def __init__(self, replace=''): self.replace = replace self.format_called = 0
def __format__(self, _): self.format_called += 1 return self.replace
class Comparable: """Assumes child has self._comparable attr/@property""" def __lt__(self, other): return self._comparable < other._comparable
def __le__(self, other): return (self < other) or (self == other)
def __eq__(self, other): return self._comparable == other._comparable
def __ne__(self, other): return not self == other
def __gt__(self, other): return not self <= other
def __ge__(self, other): return not self < other
class ObjectWrapper: def __getattr__(self, name): return getattr(self._wrapped, name)
def __setattr__(self, name, value): return setattr(self._wrapped, name, value)
def wrapper_getattr(self, name): """Actual `self.getattr` rather than self._wrapped.getattr""" try: return object.__getattr__(self, name) except AttributeError: # py2 return getattr(self, name)
def wrapper_setattr(self, name, value): """Actual `self.setattr` rather than self._wrapped.setattr""" return object.__setattr__(self, name, value)
def __init__(self, wrapped): """ Thin wrapper around a given object """ self.wrapper_setattr('_wrapped', wrapped)
class SimpleTextIOWrapper(ObjectWrapper): """ Change only `.write()` of the wrapped object by encoding the passed value and passing the result to the wrapped object's `.write()` method. """ # pylint: disable=too-few-public-methods def __init__(self, wrapped, encoding): super().__init__(wrapped) self.wrapper_setattr('encoding', encoding)
def write(self, s): """ Encode `s` and pass to the wrapped object's `.write()` method. """ return self._wrapped.write(s.encode(self.wrapper_getattr('encoding')))
def __eq__(self, other): return self._wrapped == getattr(other, '_wrapped', other)
class DisableOnWriteError(ObjectWrapper): """ Disable the given `tqdm_instance` upon `write()` or `flush()` errors. """ @staticmethod def disable_on_exception(tqdm_instance, func): """ Quietly set `tqdm_instance.miniters=inf` if `func` raises `errno=5`. """ tqdm_instance = proxy(tqdm_instance)
def inner(*args, **kwargs): try: return func(*args, **kwargs) except OSError as e: if e.errno != 5: raise try: tqdm_instance.miniters = float('inf') except ReferenceError: pass except ValueError as e: if 'closed' not in str(e): raise try: tqdm_instance.miniters = float('inf') except ReferenceError: pass return inner
def __init__(self, wrapped, tqdm_instance): # noqa: B042 super().__init__(wrapped) if hasattr(wrapped, 'write'): self.wrapper_setattr( 'write', self.disable_on_exception(tqdm_instance, wrapped.write)) if hasattr(wrapped, 'flush'): self.wrapper_setattr( 'flush', self.disable_on_exception(tqdm_instance, wrapped.flush))
def __eq__(self, other): return self._wrapped == getattr(other, '_wrapped', other)
class CallbackIOWrapper(ObjectWrapper): def __init__(self, callback, stream, method="read"): """ Wrap a given `file`-like object's `read()` or `write()` to report lengths to the given `callback` """ super().__init__(stream) func = getattr(stream, method) if method == "write": @wraps(func) def write(data, *args, **kwargs): res = func(data, *args, **kwargs) callback(len(data)) return res self.wrapper_setattr('write', write) elif method == "read": @wraps(func) def read(*args, **kwargs): data = func(*args, **kwargs) callback(len(data)) return data self.wrapper_setattr('read', read) else: raise KeyError("Can only wrap read/write methods")
def _is_utf(encoding): try: '\u2588\u2589'.encode(encoding) except UnicodeEncodeError: return False except Exception: try: return encoding.lower().startswith('utf-') or ('U8' == encoding) except Exception: return False else: return True
def _supports_unicode(fp): try: return _is_utf(fp.encoding) except AttributeError: return False
def _is_ascii(s): if isinstance(s, str): for c in s: if ord(c) > 255: return False return True return _supports_unicode(s)
def _screen_shape_wrapper(): # pragma: no cover """ Return a function which returns console dimensions (width, height). Supported: linux, osx, windows, cygwin. """ from os import get_terminal_size
def inner(fp): try: cols, lines = get_terminal_size(getattr(fp, 'fileno', lambda: None)()) return cols - 1, lines - 1 except Exception: return None, None
return inner
def _environ_cols_wrapper(): # pragma: no cover """ Return a function which returns console width. Supported: linux, osx, windows, cygwin. """ warn("Use `_screen_shape_wrapper()(file)[0]` instead of" " `_environ_cols_wrapper()(file)`", DeprecationWarning, stacklevel=2) shape = _screen_shape_wrapper() if not shape: return None
@wraps(shape) def inner(fp): return shape(fp)[0]
return inner
def _term_move_up(): # pragma: no cover return '' if (os.name == 'nt') and (colorama is None) else '\x1b[A'
def _text_width(s): return sum(2 if east_asian_width(ch) in 'FW' else 1 for ch in str(s))
def disp_len(data): """ Returns the real on-screen length of a string which may contain ANSI control codes and wide chars. """ return _text_width(RE_ANSI.sub('', data))
def disp_trim(data, length): """ Trim a string which may contain ANSI control characters. """ if len(data) == disp_len(data): return data[:length]
ansi_present = bool(RE_ANSI.search(data)) while disp_len(data) > length: # carefully delete one char at a time data = data[:-1] if ansi_present and bool(RE_ANSI.search(data)): # assume ANSI reset is required return data if data.endswith("\033[0m") else data + "\033[0m" return data1234567891011121314151617181920212223242526272829303132333435363738Metadata-Version: 2.4Name: filelockVersion: 3.29.1Summary: A platform independent file lock.Project-URL: Documentation, https://py-filelock.readthedocs.ioProject-URL: Homepage, https://github.com/tox-dev/py-filelockProject-URL: Source, https://github.com/tox-dev/py-filelockProject-URL: Tracker, https://github.com/tox-dev/py-filelock/issuesMaintainer-email: Bernát Gábor <gaborjbernat@gmail.com>License-Expression: MITLicense-File: LICENSEKeywords: application,cache,directory,log,userClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: InternetClassifier: Topic :: Software Development :: LibrariesClassifier: Topic :: SystemRequires-Python: >=3.10Description-Content-Type: text/markdown
# filelock
[](https://pypi.org/project/filelock/)[](https://pypi.org/project/filelock/)[](https://py-filelock.readthedocs.io/en/latest/?badge=latest)[](https://pepy.tech/project/filelock)[](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml)
For more information checkout the [official documentation](https://py-filelock.readthedocs.io/en/latest/index.html).12345678910111213141516171819filelock/__init__.py,sha256=Ig_QNvsAVtctz2-fkq9EUCgXmW6M5PDudiOC85szmis,2612filelock/_api.py,sha256=mgN9X_i6b3bDG9gd8qxwrrRnwU5FeBSJw78jTTvU7ZI,22377filelock/_async_read_write.py,sha256=C_cRi4sZ7_CWcqdEf0pcA5sdJ2m3EI_2tAW6kS_5P6I,7759filelock/_error.py,sha256=amqJaDkEv4DhjelOhJ3xm12kVtgakSZLnVAyzAL2IYU,775filelock/_read_write.py,sha256=TjTDsYO0Lwe6yVb7oCiWHmNRc0MiJHWwKHUpYeafmlA,15693filelock/_soft.py,sha256=kllCdsXp2Su5n7D71wKeUxIxNqrDqKqdZyNffIX7EF0,8683filelock/_unix.py,sha256=pbTsIi29Qv8zBtLsXqc3PzlS3wz2db53M1MIqVo9790,4579filelock/_util.py,sha256=wPf-LvzmdHWHw4DinDeVJlB0GNVOYGNUeNKSnHBQuUU,1716filelock/_windows.py,sha256=kJFOenaffOP6Qza2b3-yxgiPiDcyroWnzz9STGkCrgM,3943filelock/asyncio.py,sha256=z6yRl3od9BLEvtwXqvPLzaamoliXL-onelc7rmKGUlA,15558filelock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0filelock/version.py,sha256=C4a-gV3Z3ywHMJ4kTeBPRZksDETbu7qRoFc4RK8KzkY,522filelock/_soft_rw/__init__.py,sha256=_ktpGmVObzrvL0K1_EAV3LF7B9JarYxW-mx_eyGPhT0,370filelock/_soft_rw/_async.py,sha256=3MdgJN0SBM-9-Msslt4HeikJtz2cc1tbeN1sWK9NV60,8704filelock/_soft_rw/_sync.py,sha256=jhCNoZ18umc4UId4YtzGD-qv3oWaVWjPpA1xfbSd--o,34976filelock-3.29.1.dist-info/METADATA,sha256=p3_JjhhlHGrca1NbxoftieI5aUQzuYYPDazMzQWBdYM,1977filelock-3.29.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87filelock-3.29.1.dist-info/licenses/LICENSE,sha256=YIyJ1QYK6ZIa3M8yNmlbxlSplG4SMj72wCHfoE4pTUg,1088filelock-3.29.1.dist-info/RECORD,,123456789101112131415161718192021MIT License
Copyright (c) 2025 Bernát Gábor and contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207"""Async wrapper around :class:`ReadWriteLock` for use with ``asyncio``."""
from __future__ import annotations
import asyncioimport functoolsfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanagerfrom typing import TYPE_CHECKING
from ._read_write import ReadWriteLock
if TYPE_CHECKING: import os from collections.abc import AsyncGenerator, Callable from concurrent import futures from types import TracebackType
class AsyncAcquireReadWriteReturnProxy: """Context-aware object that releases the async read/write lock on exit."""
def __init__(self, lock: AsyncReadWriteLock) -> None: self.lock = lock
async def __aenter__(self) -> AsyncReadWriteLock: return self.lock
async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: await self.lock.release()
class AsyncReadWriteLock: """ Async wrapper around :class:`ReadWriteLock` for use in ``asyncio`` applications.
Because Python's :mod:`sqlite3` module has no async API, all blocking SQLite operations are dispatched to a thread pool via ``loop.run_in_executor()``. Reentrancy, upgrade/downgrade rules, and singleton behavior are delegated to the underlying :class:`ReadWriteLock`.
:param lock_file: path to the SQLite database file used as the lock :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable :param is_singleton: if ``True``, reuse existing :class:`ReadWriteLock` instances for the same resolved path :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop :param executor: executor for ``run_in_executor``; ``None`` uses the default executor
.. versionadded:: 3.21.0
"""
def __init__( # noqa: PLR0913 self, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, loop: asyncio.AbstractEventLoop | None = None, executor: futures.Executor | None = None, ) -> None: self._lock = ReadWriteLock(lock_file, timeout, blocking=blocking, is_singleton=is_singleton) self._loop = loop self._owns_executor = executor is None self._executor = executor or ThreadPoolExecutor(max_workers=1)
@property def lock_file(self) -> str: """:returns: the path to the lock file.""" return self._lock.lock_file
@property def timeout(self) -> float: """:returns: the default timeout.""" return self._lock.timeout
@property def blocking(self) -> bool: """:returns: whether blocking is enabled by default.""" return self._lock.blocking
@property def loop(self) -> asyncio.AbstractEventLoop | None: """:returns: the event loop (or ``None`` for the running loop).""" return self._loop
@property def executor(self) -> futures.Executor | None: """:returns: the executor (or ``None`` for the default).""" return self._executor
async def _run(self, func: Callable[..., object], *args: object, **kwargs: object) -> object: loop = self._loop or asyncio.get_running_loop() return await loop.run_in_executor(self._executor, functools.partial(func, *args, **kwargs))
async def acquire_read(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy: """ Acquire a shared read lock.
See :meth:`ReadWriteLock.acquire_read` for full semantics.
:param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
:returns: a proxy that can be used as an async context manager to release the lock
:raises RuntimeError: if a write lock is already held on this instance :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self._run(self._lock.acquire_read, timeout, blocking=blocking) return AsyncAcquireReadWriteReturnProxy(lock=self)
async def acquire_write(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy: """ Acquire an exclusive write lock.
See :meth:`ReadWriteLock.acquire_write` for full semantics.
:param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
:returns: a proxy that can be used as an async context manager to release the lock
:raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self._run(self._lock.acquire_write, timeout, blocking=blocking) return AsyncAcquireReadWriteReturnProxy(lock=self)
async def release(self, *, force: bool = False) -> None: """ Release one level of the current lock.
See :meth:`ReadWriteLock.release` for full semantics.
:param force: if ``True``, release the lock completely regardless of the current lock level
:raises RuntimeError: if no lock is currently held and *force* is ``False``
""" await self._run(self._lock.release, force=force)
@asynccontextmanager async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: """ Async context manager that acquires and releases a shared read lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
""" if timeout is None: timeout = self._lock.timeout if blocking is None: blocking = self._lock.blocking await self.acquire_read(timeout, blocking=blocking) try: yield finally: await self.release()
@asynccontextmanager async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: """ Async context manager that acquires and releases an exclusive write lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
""" if timeout is None: timeout = self._lock.timeout if blocking is None: blocking = self._lock.blocking await self.acquire_write(timeout, blocking=blocking) try: yield finally: await self.release()
async def close(self) -> None: """ Release the lock (if held) and close the underlying SQLite connection.
After calling this method, the lock instance is no longer usable.
""" await self._run(self._lock.close) if self._owns_executor: self._executor.shutdown(wait=False)
__all__ = [ "AsyncAcquireReadWriteReturnProxy", "AsyncReadWriteLock",]12345678910111213141516171819202122232425262728from __future__ import annotations
class Timeout(TimeoutError): # noqa: N818 """Raised when the lock could not be acquired in *timeout* seconds."""
def __init__(self, lock_file: str) -> None: super().__init__() self._lock_file = lock_file
def __reduce__(self) -> tuple[type[Timeout], tuple[str]]: return self.__class__, (self._lock_file,) # Properly pickle the exception
def __str__(self) -> str: return f"The file lock '{self._lock_file}' could not be acquired."
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.lock_file!r})"
@property def lock_file(self) -> str: """:returns: The path of the file lock.""" return self._lock_file
__all__ = [ "Timeout",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227from __future__ import annotations
import osimport socketimport sysimport timefrom contextlib import suppressfrom errno import EACCES, EEXIST, EPERM, ESRCHfrom pathlib import Path
from ._api import BaseFileLockfrom ._util import ensure_directory_exists, raise_on_not_writable_file
_WIN_SYNCHRONIZE = 0x100000_WIN_ERROR_INVALID_PARAMETER = 87_WIN_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000_MALFORMED_LOCK_AGE_THRESHOLD = 2.0_MAX_LOCK_FILE_SIZE = 1024
class SoftFileLock(BaseFileLock): """ Portable file lock based on file existence.
Unlike :class:`UnixFileLock <filelock.UnixFileLock>` and :class:`WindowsFileLock <filelock.WindowsFileLock>`, this lock does not use OS-level locking primitives. Instead, it creates the lock file with ``O_CREAT | O_EXCL`` and treats its existence as the lock indicator. This makes it work on any filesystem but leaves stale lock files behind if the process crashes without releasing the lock.
To mitigate stale locks, the lock file contains the PID and hostname of the holding process. On contention, if the holder is on the same host and its PID no longer exists, the stale lock is broken automatically.
"""
def _acquire(self) -> None: raise_on_not_writable_file(self.lock_file) ensure_directory_exists(self.lock_file) flags = ( os.O_WRONLY # open for writing only | os.O_CREAT | os.O_EXCL # together with above raise EEXIST if the file specified by filename exists | os.O_TRUNC # truncate the file to zero byte ) if (o_nofollow := getattr(os, "O_NOFOLLOW", None)) is not None: flags |= o_nofollow try: file_handler = os.open(self.lock_file, flags, self._open_mode()) except OSError as exception: if not ( exception.errno == EEXIST or (exception.errno == EACCES and sys.platform == "win32") ): # pragma: win32 no cover raise self._try_break_stale_lock() else: self._write_lock_info(file_handler) self._context.lock_file_fd = file_handler
def _try_break_stale_lock(self) -> None: with suppress(OSError, ValueError): content, mtime = _read_lock_file(self.lock_file) lines = content.strip().splitlines() if content else []
if len(lines) not in {2, 3}: if time.time() - mtime >= _MALFORMED_LOCK_AGE_THRESHOLD: self._evict_lock_file() return
pid_str, hostname = lines[0], lines[1] creation_time_str = lines[2] if len(lines) == 3 else None # noqa: PLR2004
if hostname != socket.gethostname(): return
pid = int(pid_str)
if self._is_process_alive(pid): if sys.platform == "win32" and creation_time_str is not None: # pragma: win32 cover stored = int(creation_time_str) actual = self._get_process_creation_time(pid) if actual is not None and actual != stored: pass # PID recycled, fall through to evict else: return # same process or can't verify — don't evict else: return
self._evict_lock_file()
def _evict_lock_file(self) -> None: break_path = f"{self.lock_file}.break.{os.getpid()}" Path(self.lock_file).rename(break_path) Path(break_path).unlink()
@staticmethod def _is_process_alive(pid: int) -> bool: if sys.platform == "win32": # pragma: win32 cover import ctypes # noqa: PLC0415
kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(_WIN_SYNCHRONIZE, 0, pid) if handle: kernel32.CloseHandle(handle) return True return kernel32.GetLastError() != _WIN_ERROR_INVALID_PARAMETER try: os.kill(pid, 0) except OSError as exc: if exc.errno == ESRCH: return False if exc.errno == EPERM: return True raise return True
@staticmethod def _get_process_creation_time(pid: int) -> int | None: """Return the process creation FILETIME as an integer on Windows, ``None`` otherwise.""" if sys.platform != "win32": # pragma: win32 no cover return None import ctypes # pragma: win32 cover # noqa: PLC0415 from ctypes import wintypes # noqa: PLC0415
kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(_WIN_PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) if not handle: return None try: creation = wintypes.FILETIME() exit_time = wintypes.FILETIME() kernel_time = wintypes.FILETIME() user_time = wintypes.FILETIME() if not kernel32.GetProcessTimes( handle, ctypes.byref(creation), ctypes.byref(exit_time), ctypes.byref(kernel_time), ctypes.byref(user_time), ): return None finally: kernel32.CloseHandle(handle) return (creation.dwHighDateTime << 32) | creation.dwLowDateTime
@staticmethod def _write_lock_info(fd: int) -> None: with suppress(OSError): info = f"{os.getpid()}\n{socket.gethostname()}\n" if sys.platform == "win32" and (ct := SoftFileLock._get_process_creation_time(os.getpid())) is not None: info += f"{ct}\n" os.write(fd, info.encode())
@property def pid(self) -> int | None: """ The PID of the process holding this lock, read from the lock file.
:returns: the PID as an integer, or ``None`` if the lock file does not exist or cannot be parsed
""" with suppress(OSError, ValueError): content, _ = _read_lock_file(self.lock_file) if content and (lines := content.strip().splitlines()): return int(lines[0]) return None
@property def is_lock_held_by_us(self) -> bool: """ Whether this lock is held by the current process.
:returns: ``True`` if the lock file exists and contains the current process's PID
""" return self.pid == os.getpid()
def break_lock(self) -> None: """Forcibly break the lock by removing the lock file, regardless of who holds it.""" with suppress(OSError): Path(self.lock_file).unlink()
def _release(self) -> None: assert self._context.lock_file_fd is not None # noqa: S101 os.close(self._context.lock_file_fd) self._context.lock_file_fd = None if sys.platform == "win32": self._windows_unlink_with_retry() else: with suppress(OSError): Path(self.lock_file).unlink()
def _windows_unlink_with_retry(self) -> None: max_retries = 10 retry_delay = 0.001 for attempt in range(max_retries): # Windows doesn't immediately release file handles after close, causing EACCES/EPERM on unlink try: Path(self.lock_file).unlink() except OSError as exc: # noqa: PERF203 if exc.errno not in {EACCES, EPERM}: return if attempt < max_retries - 1: time.sleep(retry_delay) retry_delay *= 2 else: return
def _read_lock_file(path: str) -> tuple[str | None, float]: # The lock file is created with O_EXCL | O_NOFOLLOW, so a symlink here is a hostile replacement and must # not be followed. O_NONBLOCK keeps an attacker-placed FIFO from stalling the open (O_NOFOLLOW alone only # rejects a symlink, not a real FIFO at the path), and the capped read stops a huge file (e.g. /dev/zero) # from exhausting memory. Content is None when the file is too large or not UTF-8, but the mtime still # flows back so the caller can evict it as a stale, malformed lock. fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) try: mtime, data = os.fstat(fd).st_mtime, os.read(fd, _MAX_LOCK_FILE_SIZE + 1) finally: os.close(fd) if len(data) <= _MAX_LOCK_FILE_SIZE: with suppress(UnicodeDecodeError): return data.decode("utf-8"), mtime return None, mtime
__all__ = [ "SoftFileLock",]123456789101112"""Cross-process and cross-host reader/writer lock on :class:`~filelock.SoftFileLock` primitives."""
from __future__ import annotations
from ._async import AsyncAcquireSoftReadWriteReturnProxy, AsyncSoftReadWriteLockfrom ._sync import SoftReadWriteLock
__all__ = [ "AsyncAcquireSoftReadWriteReturnProxy", "AsyncSoftReadWriteLock", "SoftReadWriteLock",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213"""Async wrapper around :class:`SoftReadWriteLock` for use with ``asyncio``."""
from __future__ import annotations
import asyncioimport functoolsfrom contextlib import asynccontextmanagerfrom typing import TYPE_CHECKING
from ._sync import SoftReadWriteLock
if TYPE_CHECKING: import os from collections.abc import AsyncGenerator, Callable from concurrent import futures from types import TracebackType
class AsyncAcquireSoftReadWriteReturnProxy: """Async context-aware object that releases an :class:`AsyncSoftReadWriteLock` on exit."""
def __init__(self, lock: AsyncSoftReadWriteLock) -> None: self.lock = lock
async def __aenter__(self) -> AsyncSoftReadWriteLock: return self.lock
async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: await self.lock.release()
class AsyncSoftReadWriteLock: """ Async wrapper around :class:`SoftReadWriteLock` for ``asyncio`` applications.
The sync class's blocking filesystem operations run on a thread pool via ``loop.run_in_executor()``. Reentrancy, upgrade/downgrade rules, fork handling, heartbeat and TTL stale detection, and singleton behavior are delegated to the underlying :class:`SoftReadWriteLock`.
:param lock_file: path to the lock file; sidecar state/write/readers live next to it :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention :param is_singleton: if ``True``, reuse existing :class:`SoftReadWriteLock` instances per resolved path :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s :param stale_threshold: seconds of mtime inactivity before a marker is stale; defaults to ``3 * heartbeat_interval`` :param poll_interval: seconds between acquire retries under contention; default 0.25 s :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop :param executor: executor for ``run_in_executor``; ``None`` uses the default executor
.. versionadded:: 3.27.0
"""
def __init__( # noqa: PLR0913 self, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, heartbeat_interval: float = 30.0, stale_threshold: float | None = None, poll_interval: float = 0.25, loop: asyncio.AbstractEventLoop | None = None, executor: futures.Executor | None = None, ) -> None: self._lock = SoftReadWriteLock( lock_file, timeout, blocking=blocking, is_singleton=is_singleton, heartbeat_interval=heartbeat_interval, stale_threshold=stale_threshold, poll_interval=poll_interval, ) self._loop = loop self._executor = executor
@property def lock_file(self) -> str: """:returns: the path to the lock file passed to the constructor.""" return self._lock.lock_file
@property def timeout(self) -> float: """:returns: the default timeout applied when ``acquire_read`` / ``acquire_write`` is called without one.""" return self._lock.timeout
@property def blocking(self) -> bool: """:returns: whether ``acquire_*`` defaults to blocking; ``False`` makes contention raise immediately.""" return self._lock.blocking
@property def loop(self) -> asyncio.AbstractEventLoop | None: """:returns: the event loop used for ``run_in_executor``, or ``None`` for the running loop.""" return self._loop
@property def executor(self) -> futures.Executor | None: """:returns: the executor used for ``run_in_executor``, or ``None`` for the default executor.""" return self._executor
async def acquire_read( self, timeout: float | None = None, *, blocking: bool | None = None ) -> AsyncAcquireSoftReadWriteReturnProxy: """ Acquire a shared read lock.
See :meth:`SoftReadWriteLock.acquire_read` for the full reentrancy / upgrade / fork semantics. The blocking work runs inside ``run_in_executor`` so other coroutines on the same loop continue to progress while this call waits.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:returns: a proxy usable as an async context manager to release the lock
:raises RuntimeError: if a write lock is already held, if this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self._run(self._lock.acquire_read, timeout, blocking=blocking) return AsyncAcquireSoftReadWriteReturnProxy(lock=self)
async def acquire_write( self, timeout: float | None = None, *, blocking: bool | None = None ) -> AsyncAcquireSoftReadWriteReturnProxy: """ Acquire an exclusive write lock.
See :meth:`SoftReadWriteLock.acquire_write` for the two-phase writer-preferring semantics. The blocking work runs inside ``run_in_executor``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:returns: a proxy usable as an async context manager to release the lock
:raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self._run(self._lock.acquire_write, timeout, blocking=blocking) return AsyncAcquireSoftReadWriteReturnProxy(lock=self)
async def release(self, *, force: bool = False) -> None: """ Release one level of the current lock.
:param force: if ``True``, release the lock completely regardless of the current lock level
:raises RuntimeError: if no lock is currently held and *force* is ``False``
""" await self._run(self._lock.release, force=force)
@asynccontextmanager async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: """ Async context manager that acquires and releases a shared read lock.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:raises RuntimeError: if a write lock is already held on this instance :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self.acquire_read(timeout, blocking=blocking) try: yield finally: await self.release()
@asynccontextmanager async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: """ Async context manager that acquires and releases an exclusive write lock.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" await self.acquire_write(timeout, blocking=blocking) try: yield finally: await self.release()
async def close(self) -> None: """Release any held lock and release the underlying filesystem resources. Idempotent.""" await self._run(self._lock.close)
async def _run(self, func: Callable[..., object], *args: object, **kwargs: object) -> object: loop = self._loop or asyncio.get_running_loop() return await loop.run_in_executor(self._executor, functools.partial(func, *args, **kwargs))
__all__ = [ "AsyncAcquireSoftReadWriteReturnProxy", "AsyncSoftReadWriteLock",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849"""Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives."""
from __future__ import annotations
import atexitimport hmacimport osimport reimport secretsimport socketimport statimport sysimport threadingimport timeimport uuidfrom contextlib import contextmanager, suppressfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING, Literalfrom weakref import WeakValueDictionary
from filelock._api import AcquireReturnProxyfrom filelock._error import Timeoutfrom filelock._soft import SoftFileLockfrom filelock._util import ensure_directory_exists
if TYPE_CHECKING: from collections.abc import Callable, Generator
_Mode = Literal["read", "write"]_BREAK_SUFFIX = ".break"_MAX_MARKER_SIZE = 1024_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)# dirfd-relative I/O is a Unix-only optimization; Windows cannot ``os.open()`` a directory at all, and# its ``os`` module skips dir_fd support entirely. When disabled, callers fall back to full-path ops._SUPPORTS_DIR_FD = sys.platform != "win32" and os.open in os.supports_dir_fd
_all_instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary()_all_instances_lock = threading.Lock()_atexit_registered = False_fork_registered = False
@dataclass(frozen=True)class _Paths: state: str write: str readers: str
@dataclassclass _Locks: internal: threading.Lock transaction: threading.Lock state: SoftFileLock
@dataclass(frozen=True)class _MarkerInfo: token: str pid: int hostname: str
@dataclassclass _Hold: """Everything that exists only while a lock is held; ``None`` when the instance has no lock."""
level: int mode: _Mode write_thread_id: int | None marker_name: str is_reader: bool token: str heartbeat_thread: _HeartbeatThread heartbeat_stop: threading.Event
class _SoftRWMeta(type): _instances: WeakValueDictionary[Path, SoftReadWriteLock] _instances_lock: threading.Lock
def __call__( # noqa: PLR0913 cls, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, heartbeat_interval: float = 30.0, stale_threshold: float | None = None, poll_interval: float = 0.25, ) -> SoftReadWriteLock: if not is_singleton: return super().__call__( lock_file, timeout, blocking=blocking, is_singleton=is_singleton, heartbeat_interval=heartbeat_interval, stale_threshold=stale_threshold, poll_interval=poll_interval, )
normalized = Path(lock_file).resolve() with cls._instances_lock: instance = cls._instances.get(normalized) if instance is None: instance = super().__call__( lock_file, timeout, blocking=blocking, is_singleton=is_singleton, heartbeat_interval=heartbeat_interval, stale_threshold=stale_threshold, poll_interval=poll_interval, ) cls._instances[normalized] = instance elif instance.timeout != timeout or instance.blocking != blocking: msg = ( f"Singleton lock created with timeout={instance.timeout}, blocking={instance.blocking}," f" cannot be changed to timeout={timeout}, blocking={blocking}" ) raise ValueError(msg) return instance
class SoftReadWriteLock(metaclass=_SoftRWMeta): """ Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives.
Use this class instead of :class:`~filelock.ReadWriteLock` when the lock file lives on a network filesystem (NFS, Lustre with ``-o flock``, HPC cluster shared storage). ``ReadWriteLock`` is backed by SQLite and cannot run on NFS because SQLite's ``fcntl`` locking is unreliable there.
Layout on disk for a lock at ``foo.lock``:
- ``foo.lock.state`` — a :class:`SoftFileLock` taken only during state transitions (microseconds). - ``foo.lock.write`` — writer marker; its presence means a writer is claiming or holding the lock. - ``foo.lock.readers/<host>.<pid>.<uuid>`` — one file per reader.
Each marker stores a random token (``secrets.token_hex(16)``), the holder's pid, and the holder's hostname. A daemon heartbeat thread refreshes ``mtime`` on every held marker. A marker whose mtime has not advanced in ``stale_threshold`` seconds may be evicted by any process on any host, giving correct behavior when a compute node crashes with a lock held.
Writer acquire is two-phase and writer-preferring: phase 1 claims ``.write`` (blocking any new reader), phase 2 waits for existing readers to drain. Writer starvation is impossible.
Reentrancy, upgrade/downgrade rules, thread pinning, and singleton caching by resolved path match :class:`~filelock.ReadWriteLock`.
Forking while holding a lock invalidates the inherited instance in the child so the child cannot double-own the lock with its parent; ``release()`` on a fork-invalidated instance is a no-op, and the child must re-acquire if it needs a lock.
Trust boundary: protects against same-UID non-cooperating processes (one host or cross-host) and same-host different-UID users via ``0o600`` / ``0o700`` permissions. Does not protect against root compromise, NTP tampering on same-UID cross-host nodes, or multi-tenant mounts where hostile co-tenants share the UID.
:param lock_file: path to the lock file; sidecar state/write/readers live next to it :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention :param is_singleton: if ``True``, reuse existing instances for the same resolved path :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s :param stale_threshold: seconds of ``mtime`` inactivity before a marker is stale; defaults to ``3 * heartbeat_interval``, matching etcd's ``LeaseKeepAlive`` convention :param poll_interval: seconds between acquire retries under contention; default 0.25 s
.. versionadded:: 3.27.0
"""
_instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary() _instances_lock = threading.Lock()
def __init__( # noqa: PLR0913 self, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, is_singleton: bool = True, # noqa: ARG002 heartbeat_interval: float = 30.0, stale_threshold: float | None = None, poll_interval: float = 0.25, ) -> None: if heartbeat_interval <= 0: msg = f"heartbeat_interval must be positive, got {heartbeat_interval}" raise ValueError(msg) if stale_threshold is None: stale_threshold = heartbeat_interval * 3 if stale_threshold <= heartbeat_interval: msg = f"stale_threshold must exceed heartbeat_interval ({stale_threshold} <= {heartbeat_interval})" raise ValueError(msg) if poll_interval <= 0: msg = f"poll_interval must be positive, got {poll_interval}" raise ValueError(msg)
self.lock_file: str = os.fspath(lock_file) self.timeout: float = timeout self.blocking: bool = blocking self.heartbeat_interval: float = heartbeat_interval self.stale_threshold: float = stale_threshold self.poll_interval: float = poll_interval
self._paths = _Paths( state=f"{self.lock_file}.state", write=f"{self.lock_file}.write", readers=f"{self.lock_file}.readers", ) ensure_directory_exists(self.lock_file) self._locks = _Locks( internal=threading.Lock(), transaction=threading.Lock(), state=SoftFileLock(self._paths.state, timeout=-1), ) self._readers_dir_fd: int | None = None self._hold: _Hold | None = None self._fork_invalidated: bool = False self._closed: bool = False
with _all_instances_lock: _all_instances[Path(self.lock_file).resolve()] = self _register_hooks()
@contextmanager def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: """ Context manager that acquires and releases a shared read lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:raises RuntimeError: if a write lock is already held on this instance :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" self.acquire_read(timeout, blocking=blocking) try: yield finally: self.release()
@contextmanager def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: """ Context manager that acquires and releases an exclusive write lock.
Falls back to instance defaults for *timeout* and *blocking* when ``None``.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
:raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" self.acquire_write(timeout, blocking=blocking) try: yield finally: self.release()
def acquire_read(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: """ Acquire a shared read lock.
If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a read lock while holding a write lock raises :class:`RuntimeError` (downgrade not allowed). On the 0→1 transition a daemon heartbeat thread is started that refreshes the reader marker's ``mtime`` every ``heartbeat_interval`` seconds so peers on other hosts do not evict the marker as stale.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; ``None`` uses the instance default
:returns: a proxy that can be used as a context manager to release the lock
:raises RuntimeError: if a write lock is already held on this instance, if this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" return self._acquire("read", timeout, blocking=blocking)
def acquire_write(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: """ Acquire an exclusive write lock.
If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant). Attempting to acquire a write lock while holding a read lock raises :class:`RuntimeError` (upgrade not allowed). Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raises :class:`RuntimeError`.
Writer acquisition runs in two phases. Phase 1 atomically claims ``<path>.write`` via ``O_CREAT | O_EXCL``, which immediately blocks any new reader on any host. Phase 2 waits for existing readers to drain. Writer starvation is impossible: new readers see ``<path>.write`` during phase 2 and wait behind the pending writer.
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; ``None`` uses the instance default
:returns: a proxy that can be used as a context manager to release the lock
:raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called :raises Timeout: if the lock cannot be acquired within *timeout* seconds
""" return self._acquire("write", timeout, blocking=blocking)
def close(self) -> None: """ Release any held lock and release internal filesystem resources.
Idempotent. After calling this method the instance can no longer acquire locks — subsequent acquires raise :class:`RuntimeError`. A fork-invalidated instance is closed without raising. """ self.release(force=True) with self._locks.internal: if self._closed: return self._closed = True if self._readers_dir_fd is not None: with suppress(OSError): os.close(self._readers_dir_fd) self._readers_dir_fd = None
def release(self, *, force: bool = False) -> None: """ Release one level of the current lock.
When the lock level reaches zero the heartbeat thread is stopped and the held marker file is unlinked. On a fork-invalidated instance (that is, the child of a :func:`os.fork` call made while the parent held a lock) this method is a no-op so inherited ``with`` blocks can unwind cleanly in the child.
:param force: if ``True``, release the lock completely regardless of the current lock level
:raises RuntimeError: if no lock is currently held and *force* is ``False``
""" with self._locks.internal: if self._fork_invalidated: # Inherited state from the parent is meaningless in the child; clear any counters and return. self._hold = None return hold = self._hold if hold is None: if force: return msg = f"Cannot release a lock on {self.lock_file} (lock id: {id(self)}) that is not held" raise RuntimeError(msg) if force: hold.level = 0 else: hold.level -= 1 if hold.level > 0: return self._hold = None
# Order matters: signal → join → unlink. A late tick on a deleted marker is harmless, and the # token check in the heartbeat callback would catch any re-acquisition race, but joining first # removes even that theoretical race. hold.heartbeat_stop.set() hold.heartbeat_thread.join(timeout=self.heartbeat_interval + 1.0) if hold.is_reader: _unlink(hold.marker_name, dir_fd=self._readers_dir_fd) else: _unlink(hold.marker_name)
@classmethod def get_lock( cls, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True, ) -> SoftReadWriteLock: """ Return the singleton :class:`SoftReadWriteLock` for *lock_file*.
:param lock_file: path to the lock file; sidecar state/write/readers live next to it :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
:returns: the singleton lock instance
:raises ValueError: if an instance already exists for this path with different *timeout* or *blocking* values
""" return cls(lock_file, timeout, blocking=blocking)
def _acquire( self, mode: _Mode, timeout: float | None, *, blocking: bool | None, ) -> AcquireReturnProxy: effective_timeout = self.timeout if timeout is None else timeout blocking = self.blocking if blocking is None else blocking
with self._locks.internal: if self._fork_invalidated: msg = f"SoftReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance" raise RuntimeError(msg) if self._closed: msg = f"SoftReadWriteLock on {self.lock_file} has been closed" raise RuntimeError(msg) if self._hold is not None: return self._validate_reentrant(mode)
start = time.perf_counter() if not blocking: acquired = self._locks.transaction.acquire(blocking=False) elif effective_timeout == -1: acquired = self._locks.transaction.acquire(blocking=True) else: acquired = self._locks.transaction.acquire(blocking=True, timeout=effective_timeout) if not acquired: raise Timeout(self.lock_file) from None try: return self._do_acquire_inner(mode, effective_timeout, start, blocking=blocking) finally: self._locks.transaction.release()
def _do_acquire_inner( self, mode: _Mode, effective_timeout: float, start: float, *, blocking: bool, ) -> AcquireReturnProxy: with self._locks.internal: if self._hold is not None: return self._validate_reentrant(mode) deadline = None if effective_timeout == -1 else start + effective_timeout token = secrets.token_hex(16) if mode == "write": marker_name, is_reader = self._acquire_writer_slot(token, deadline=deadline, blocking=blocking) else: marker_name, is_reader = self._acquire_reader_slot(token, deadline=deadline, blocking=blocking) stop_event = threading.Event() heartbeat = _HeartbeatThread( refresh=self._refresh_marker, interval=self.heartbeat_interval, stop_event=stop_event, name=f"filelock-heartbeat-{id(self):x}", ) with self._locks.internal: self._hold = _Hold( level=1, mode=mode, write_thread_id=threading.get_ident() if mode == "write" else None, marker_name=marker_name, is_reader=is_reader, token=token, heartbeat_thread=heartbeat, heartbeat_stop=stop_event, ) heartbeat.start() return AcquireReturnProxy(lock=self)
def _validate_reentrant(self, mode: _Mode) -> AcquireReturnProxy: hold = self._hold assert hold is not None # noqa: S101 if hold.mode != mode: opposite = "write" if mode == "read" else "read" direction = "downgrade" if mode == "read" else "upgrade" msg = ( f"Cannot acquire {mode} lock on {self.lock_file} (lock id: {id(self)}): " f"already holding a {opposite} lock ({direction} not allowed)" ) raise RuntimeError(msg) if mode == "write" and (cur := threading.get_ident()) != hold.write_thread_id: msg = ( f"Cannot acquire write lock on {self.lock_file} (lock id: {id(self)}) " f"from thread {cur} while it is held by thread {hold.write_thread_id}" ) raise RuntimeError(msg) hold.level += 1 return AcquireReturnProxy(lock=self)
def _acquire_writer_slot( self, token: str, *, deadline: float | None, blocking: bool, ) -> tuple[str, bool]: # Phase 2 scans readers/ via dirfd (where supported), so we need it open even though writers never # create files inside. self._open_readers_dir()
def try_claim_writer() -> bool: with self._locks.state: _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time()) if _file_exists(self._paths.write): return False try: _atomic_create_marker(self._paths.write, token) except FileExistsError: return False return True
def readers_drained_touching() -> bool: with self._locks.state: # Refresh our writer marker on every scan iteration. Otherwise phase 2 can exceed # ``stale_threshold`` under contention and a peer would treat us as stale and evict us. with suppress(OSError): _touch(self._paths.write) self._break_stale_readers(time.time()) return not self._any_readers()
self._wait_for(try_claim_writer, deadline=deadline, blocking=blocking) try: self._wait_for(readers_drained_touching, deadline=deadline, blocking=blocking) except Timeout: # Give up our writer claim so readers can make progress again. _unlink(self._paths.write) raise return self._paths.write, False
def _acquire_reader_slot( self, token: str, *, deadline: float | None, blocking: bool, ) -> tuple[str, bool]: self._open_readers_dir() reader_name = f"{uuid.uuid4().hex}.{os.getpid()}" dir_fd = self._readers_dir_fd full_reader_path = str(Path(self._paths.readers) / reader_name)
def try_claim_reader() -> bool: with self._locks.state: _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time()) if _file_exists(self._paths.write): return False if dir_fd is not None: _atomic_create_marker(reader_name, token, dir_fd=dir_fd) else: # pragma: win32 cover _atomic_create_marker(full_reader_path, token) return True
self._wait_for(try_claim_reader, deadline=deadline, blocking=blocking) return (reader_name if dir_fd is not None else full_reader_path), True
def _wait_for( self, predicate: Callable[[], bool], *, deadline: float | None, blocking: bool, ) -> None: while True: if predicate(): return now = time.perf_counter() if not blocking: raise Timeout(self.lock_file) if deadline is not None and now >= deadline: raise Timeout(self.lock_file) sleep_for = self.poll_interval if deadline is not None: sleep_for = min(sleep_for, max(deadline - now, 0.0)) time.sleep(sleep_for)
def _open_readers_dir(self) -> None: readers_path = Path(self._paths.readers) with suppress(FileExistsError): readers_path.mkdir(mode=0o700) # mkdir has no O_NOFOLLOW, so verify via lstat that we did not land on an attacker-placed symlink # or a regular file before we open or scan inside. st = os.lstat(self._paths.readers) if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode): msg = f"{self._paths.readers} exists but is not a directory or is a symlink; refusing to use it" raise RuntimeError(msg) if self._readers_dir_fd is None and _SUPPORTS_DIR_FD: flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | _O_NOFOLLOW self._readers_dir_fd = os.open(self._paths.readers, flags)
def _any_readers(self) -> bool: for _ in self._iter_reader_entries(): return True return False
def _iter_reader_entries(self) -> Generator[tuple[str, bool]]: """ Yield ``(name, dirfd_relative)`` pairs for every live reader marker.
``dirfd_relative`` is ``True`` when *name* should be passed to ``dir_fd=``-aware syscalls; ``False`` when *name* is a full path because dirfd-relative I/O is unavailable on this platform. """ if self._readers_dir_fd is not None: with os.scandir(self._readers_dir_fd) as it: for entry in it: if not _is_housekeeping_name(entry.name): yield entry.name, True return readers_path = Path(self._paths.readers) # pragma: win32 cover with os.scandir(readers_path) as it: # pragma: win32 cover for entry in it: # pragma: win32 cover if not _is_housekeeping_name(entry.name): # pragma: win32 cover yield str(readers_path / entry.name), False # pragma: win32 cover
def _break_stale_readers(self, now: float) -> None: names: list[tuple[str, int | None]] = [] try: for name, dirfd_relative in self._iter_reader_entries(): names.append((name, self._readers_dir_fd if dirfd_relative else None)) except OSError: # pragma: no cover - transient NFS scandir hiccup return for name, fd in names: _break_stale_marker(name, stale_threshold=self.stale_threshold, now=now, dir_fd=fd)
def _refresh_marker(self) -> bool: with self._locks.internal: hold = self._hold if hold is None: # pragma: no cover - race between stop_event.set and join return False marker_name = hold.marker_name token = hold.token dir_fd = self._readers_dir_fd if hold.is_reader else None
read_result = _read_marker(marker_name, dir_fd=dir_fd) if read_result is None: return False info, _mtime = read_result # Token mismatch means another process already evicted our marker and created its own; stop the # thread so it does not touch a stranger's file. if info is None or not hmac.compare_digest(info.token, token): return False try: _touch(marker_name, dir_fd=dir_fd) except FileNotFoundError: # pragma: no cover - race between successful read and touch return False return True
def _reset_after_fork_in_child(self) -> None: # pragma: no cover - fork child not tracked # Replace every lock this instance owns with a fresh one; the inherited locks may still be held # by threads that no longer exist in the child. The readers dirfd and the SoftFileLock state # mutex both get dropped for the same reason — the child re-creates them on its next acquire. self._locks = _Locks( internal=threading.Lock(), transaction=threading.Lock(), state=SoftFileLock(self._paths.state, timeout=-1), ) self._hold = None self._readers_dir_fd = None self._fork_invalidated = True
class _HeartbeatThread(threading.Thread): def __init__( self, refresh: Callable[[], bool], interval: float, stop_event: threading.Event, name: str, ) -> None: super().__init__(name=name, daemon=True) self._refresh = refresh self._interval = interval self._stop_event = stop_event
def run(self) -> None: while not self._stop_event.wait(self._interval): if not self._refresh(): self._stop_event.set() return
def _atomic_create_marker(name: str, token: str, *, dir_fd: int | None = None) -> None: # O_NOFOLLOW blocks the symlink-overwrite attack where an attacker pre-creates the marker path as a # symlink pointing at a victim file. Mode 0o600 keeps the token unreadable to other users. flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | _O_NOFOLLOW if _SUPPORTS_DIR_FD and dir_fd is not None: fd = os.open(name, flags, 0o600, dir_fd=dir_fd) else: fd = os.open(name, flags, 0o600) try: content = f"{token}\n{os.getpid()}\n{socket.gethostname()}\n".encode("ascii") os.write(fd, content) finally: os.close(fd)
def _read_marker(name: str, *, dir_fd: int | None = None) -> tuple[_MarkerInfo | None, float] | None: # O_NOFOLLOW is defense in depth: we already created this file, but a hostile replacement by symlink # between create and read would be caught here. flags = os.O_RDONLY | _O_NOFOLLOW try: fd = os.open(name, flags, dir_fd=dir_fd) if _SUPPORTS_DIR_FD and dir_fd is not None else os.open(name, flags) except OSError: return None try: try: st = os.fstat(fd) data = os.read(fd, _MAX_MARKER_SIZE + 1) except OSError: # pragma: no cover - fstat/read after a successful open is hard to provoke return None finally: os.close(fd) return _parse_marker_bytes(data), st.st_mtime
def _parse_marker_bytes(data: bytes) -> _MarkerInfo | None: # Trust nothing about attacker-controlled markers; any deviation returns None so callers fall through # to stale cleanup. ``re.match`` caches compiled patterns internally, so the regex is built only once # despite being defined inline. if not data or len(data) > _MAX_MARKER_SIZE: return None try: text = data.decode("ascii") except UnicodeDecodeError: return None match = re.match( r""" \A # start of string (?P<token> [0-9a-f]{32} ) \n # 128-bit hex token (?P<pid> [1-9][0-9]{0,9} ) \n # decimal pid: no leading zero, ≤ 10 digits (?P<hostname> [\x21-\x7e]{1,253}) # printable non-whitespace ASCII (RFC 1123 hostname limit) \n* # tolerate sloppy writers that append extra newlines \Z # end of string """, text, re.VERBOSE, ) if match is None: return None pid = int(match["pid"], 10) if pid > 2**31 - 1: return None return _MarkerInfo(token=match["token"], pid=pid, hostname=match["hostname"])
def _break_stale_marker( # noqa: PLR0911 name: str, *, stale_threshold: float, now: float, dir_fd: int | None = None,) -> bool: # Atomic break pattern: read → rename to unique break-name → re-verify → unlink. The rename gives us a # private name nobody else can touch; if the re-verify sees a newer mtime or a different token, the # legitimate holder's heartbeat fired between read and rename and we must abort (leaving the .break.* # file behind rather than rollback-renaming, because rollback is itself racy). read_result = _read_marker(name, dir_fd=dir_fd) if read_result is None: return False info_before, mtime_before = read_result if now - mtime_before <= stale_threshold: return False if info_before is None: _unlink(name, dir_fd=dir_fd) return True
break_name = f"{name}{_BREAK_SUFFIX}.{os.getpid()}.{secrets.token_hex(16)}" try: if _SUPPORTS_DIR_FD and dir_fd is not None: os.rename(name, break_name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) else: Path(name).rename(break_name) except OSError: # pragma: no cover - race where the marker vanishes between read and rename return False
read_after = _read_marker(break_name, dir_fd=dir_fd) if read_after is None: # pragma: no cover - race where a peer unlinks the break-name file return False info_after, mtime_after = read_after if info_after is None: # pragma: no cover - content replaced post-rename by a racing peer _unlink(break_name, dir_fd=dir_fd) return True if not hmac.compare_digest(info_before.token, info_after.token): # pragma: no cover - race only return False if mtime_after > mtime_before: # pragma: no cover - heartbeat raced our rename return False _unlink(break_name, dir_fd=dir_fd) return True
def _unlink(name: str, *, dir_fd: int | None = None) -> None: with suppress(FileNotFoundError): if _SUPPORTS_DIR_FD and dir_fd is not None: # Path.unlink has no dir_fd support, so we stay on os.unlink for the dirfd path. os.unlink(name, dir_fd=dir_fd) else: Path(name).unlink()
def _touch(name: str, *, dir_fd: int | None = None) -> None: if _SUPPORTS_DIR_FD and dir_fd is not None: os.utime(name, None, dir_fd=dir_fd) else: os.utime(name, None)
def _file_exists(path: str) -> bool: try: st = os.lstat(path) except FileNotFoundError: return False return stat.S_ISREG(st.st_mode)
def _is_housekeeping_name(name: str) -> bool: return name.startswith(".") or _BREAK_SUFFIX in name
def _reset_all_after_fork() -> None: # pragma: no cover - fork child, not tracked by coverage global _all_instances_lock # noqa: PLW0603 # User-created threading locks do not auto-reset across fork: any lock held by a parent thread stays # locked in the child with no owner to release it. Replace the module-level lock and every instance's # locks with fresh ones; the child is single-threaded at this point so no synchronization is needed. _all_instances_lock = threading.Lock() for instance in list(_all_instances.values()): instance._reset_after_fork_in_child() # noqa: SLF001
def _cleanup_all_instances() -> None: # pragma: no cover - runs from atexit at interpreter shutdown for instance in list(_all_instances.values()): with suppress(Exception): instance.release(force=True)
def _register_hooks() -> None: global _atexit_registered, _fork_registered # noqa: PLW0603 if not _atexit_registered: atexit.register(_cleanup_all_instances) _atexit_registered = True # after_in_child replaces inherited state so the child cannot double-own any lock the parent held. if not _fork_registered and hasattr(os, "register_at_fork"): os.register_at_fork(after_in_child=_reset_all_after_fork) _fork_registered = True
__all__ = [ "SoftReadWriteLock",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116from __future__ import annotations
import osimport sysimport warningsfrom contextlib import suppressfrom errno import EAGAIN, ENOSYS, EWOULDBLOCKfrom pathlib import Pathfrom typing import cast
from ._api import BaseFileLockfrom ._util import ensure_directory_exists
#: a flag to indicate if the fcntl API is availablehas_fcntl = Falseif sys.platform == "win32": # pragma: win32 cover
class UnixFileLock(BaseFileLock): """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
def _acquire(self) -> None: raise NotImplementedError
def _release(self) -> None: raise NotImplementedError
else: # pragma: win32 no cover try: import fcntl
_ = (fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_NB, fcntl.LOCK_UN) except (ImportError, AttributeError): pass else: has_fcntl = True
class UnixFileLock(BaseFileLock): """ Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems.
Lock file cleanup: Unix and macOS delete the lock file reliably after release, even in multi-threaded scenarios. Unlike Windows, Unix allows unlinking files that other processes have open. """
def _acquire(self) -> None: # noqa: C901, PLR0912 ensure_directory_exists(self.lock_file) open_flags = os.O_RDWR | os.O_TRUNC o_nofollow = getattr(os, "O_NOFOLLOW", None) if o_nofollow is not None: open_flags |= o_nofollow open_flags |= os.O_CREAT open_mode = self._open_mode() try: fd = os.open(self.lock_file, open_flags, open_mode) except FileNotFoundError: # On FUSE/NFS, os.open(O_CREAT) is not atomic: LOOKUP + CREATE can be split, allowing a concurrent # unlink() to delete the file between them. For valid paths, treat ENOENT as transient contention. # For invalid paths (e.g., empty string), re-raise to avoid infinite retry loops. if self.lock_file and Path(self.lock_file).parent.exists(): return raise except PermissionError: # Sticky-bit dirs (e.g. /tmp): O_CREAT fails if the file is owned by another user (#317). # Fall back to opening the existing file without O_CREAT. if not Path(self.lock_file).exists(): raise try: fd = os.open(self.lock_file, open_flags & ~os.O_CREAT, open_mode) except FileNotFoundError: return if self.has_explicit_mode: with suppress(PermissionError): os.fchmod(fd, self._context.mode) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError as exception: os.close(fd) if exception.errno == ENOSYS: with suppress(OSError): Path(self.lock_file).unlink() self._fallback_to_soft_lock() self._acquire() return if exception.errno not in {EAGAIN, EWOULDBLOCK}: raise else: # The file may have been unlinked by a concurrent _release() between our open() and flock(). # A lock on an unlinked inode is useless — discard and let the retry loop start fresh. if os.fstat(fd).st_nlink == 0: os.close(fd) else: self._context.lock_file_fd = fd
def _fallback_to_soft_lock(self) -> None: from ._soft import SoftFileLock # noqa: PLC0415
warnings.warn("flock not supported on this filesystem, falling back to SoftFileLock", stacklevel=2) from .asyncio import AsyncSoftFileLock, BaseAsyncFileLock # noqa: PLC0415
self.__class__ = AsyncSoftFileLock if isinstance(self, BaseAsyncFileLock) else SoftFileLock
def _release(self) -> None: fd = cast("int", self._context.lock_file_fd) self._context.lock_file_fd = None with suppress(OSError): Path(self.lock_file).unlink() fcntl.flock(fd, fcntl.LOCK_UN) with suppress(OSError): # close can raise EIO on FUSE/Docker bind-mount filesystems after unlink os.close(fd)
__all__ = [ "UnixFileLock", "has_fcntl",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111from __future__ import annotations
import osimport sysfrom contextlib import suppressfrom errno import EACCESfrom pathlib import Pathfrom typing import cast
from ._api import BaseFileLockfrom ._util import ensure_directory_exists, raise_on_not_writable_file
if sys.platform == "win32": # pragma: win32 cover import ctypes import msvcrt from ctypes import wintypes
# Windows API constants for reparse point detection FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400 INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
# Load kernel32.dll _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) _kernel32.GetFileAttributesW.argtypes = [wintypes.LPCWSTR] _kernel32.GetFileAttributesW.restype = wintypes.DWORD
def _is_reparse_point(path: str) -> bool: """ Check if a path is a reparse point (symlink, junction, etc.) on Windows.
:param path: Path to check
:returns: True if path is a reparse point, False otherwise
:raises OSError: If GetFileAttributesW fails for reasons other than file-not-found
""" attrs = _kernel32.GetFileAttributesW(path) if attrs == INVALID_FILE_ATTRIBUTES: # File doesn't exist yet - that's fine, we'll create it err = ctypes.get_last_error() if err == 2: # noqa: PLR2004 # ERROR_FILE_NOT_FOUND return False if err == 3: # noqa: PLR2004 # ERROR_PATH_NOT_FOUND return False # Some other error - let caller handle it return False return bool(attrs & FILE_ATTRIBUTE_REPARSE_POINT)
class WindowsFileLock(BaseFileLock): """ Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems.
Lock file cleanup: Windows attempts to delete the lock file after release, but deletion is not guaranteed in multi-threaded scenarios where another thread holds an open handle. The lock file may persist on disk, which does not affect lock correctness. """
def _acquire(self) -> None: raise_on_not_writable_file(self.lock_file) ensure_directory_exists(self.lock_file)
# Security check: Refuse to open reparse points (symlinks, junctions) # This prevents TOCTOU symlink attacks (CVE-TBD) if _is_reparse_point(self.lock_file): msg = f"Lock file is a reparse point (symlink/junction): {self.lock_file}" raise OSError(msg)
flags = ( os.O_RDWR # open for read and write | os.O_CREAT # create file if not exists ) try: fd = os.open(self.lock_file, flags, self._open_mode()) except OSError as exception: if exception.errno != EACCES: # has no access to this lock raise else: try: msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) except OSError as exception: os.close(fd) # close file first if exception.errno != EACCES: # file is already locked raise else: self._context.lock_file_fd = fd
def _release(self) -> None: fd = cast("int", self._context.lock_file_fd) self._context.lock_file_fd = None msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) os.close(fd)
with suppress(OSError): Path(self.lock_file).unlink()
else: # pragma: win32 no cover
class WindowsFileLock(BaseFileLock): """Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems."""
def _acquire(self) -> None: raise NotImplementedError
def _release(self) -> None: raise NotImplementedError
__all__ = [ "WindowsFileLock",]123456789101112131415161718192021222324# file generated by vcs-versioning# don't change, don't track in version controlfrom __future__ import annotations
__all__ = [ "__version__", "__version_tuple__", "version", "version_tuple", "__commit_id__", "commit_id",]
version: str__version__: str__version_tuple__: tuple[int | str, ...]version_tuple: tuple[int | str, ...]commit_id: str | None__commit_id__: str | None
__version__ = version = '3.29.1'__version_tuple__ = version_tuple = (3, 29, 1)
__commit_id__ = commit_id = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172Metadata-Version: 2.4Name: typing_extensionsVersion: 4.15.0Summary: Backported and Experimental Type Hints for Python 3.9+Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typingAuthor-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" <levkivskyi@gmail.com>Requires-Python: >=3.9Description-Content-Type: text/markdownLicense-Expression: PSF-2.0Classifier: Development Status :: 5 - Production/StableClassifier: Environment :: ConsoleClassifier: Intended Audience :: DevelopersClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Software DevelopmentLicense-File: LICENSEProject-URL: Bug Tracker, https://github.com/python/typing_extensions/issuesProject-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.mdProject-URL: Documentation, https://typing-extensions.readthedocs.io/Project-URL: Home, https://github.com/python/typing_extensionsProject-URL: Q & A, https://github.com/python/typing/discussionsProject-URL: Repository, https://github.com/python/typing_extensions
# Typing Extensions
[](https://gitter.im/python/typing)
[Documentation](https://typing-extensions.readthedocs.io/en/latest/#) –[PyPI](https://pypi.org/project/typing-extensions/)
## Overview
The `typing_extensions` module serves two related purposes:
- Enable use of new type system features on older Python versions. For example, `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows users on previous Python versions to use it too.- Enable experimentation with new type system PEPs before they are accepted and added to the `typing` module.
`typing_extensions` is treated specially by static type checkers such asmypy and pyright. Objects defined in `typing_extensions` are treated the sameway as equivalent forms in `typing`.
`typing_extensions` uses[Semantic Versioning](https://semver.org/). Themajor version will be incremented only for backwards-incompatible changes.Therefore, it's safe to dependon `typing_extensions` like this: `typing_extensions ~=x.y`,where `x.y` is the first version that includes all features you need.[This](https://packaging.python.org/en/latest/specifications/version-specifiers/#compatible-release)is equivalent to `typing_extensions >=x.y, <(x+1)`. Do not depend on `~= x.y.z`unless you really know what you're doing; that defeats the purpose ofsemantic versioning.
## Included items
See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for acomplete listing of module contents.
## Contributing
See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md)for how to contribute to `typing_extensions`.
1234Wheel-Version: 1.0Generator: flit 3.12.0Root-Is-Purelib: trueTag: py3-none-any12345678annotated_doc-0.0.4.dist-info/METADATA,sha256=Irm5KJua33dY2qKKAjJ-OhKaVBVIfwFGej_dSe3Z1TU,6566annotated_doc-0.0.4.dist-info/WHEEL,sha256=9P2ygRxDrTJz3gsagc0Z96ukrxjr-LFBGOgv3AuKlCA,90annotated_doc-0.0.4.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34annotated_doc-0.0.4.dist-info/licenses/LICENSE,sha256=__Fwd5pqy_ZavbQFwIfxzuF4ZpHkqWpANFF-SlBKDN8,1086annotated_doc/__init__.py,sha256=VuyxxUe80kfEyWnOrCx_Bk8hybo3aKo6RYBlkBBYW8k,52annotated_doc/main.py,sha256=5Zfvxv80SwwLqpRW73AZyZyiM4bWma9QWRbp_cgD20s,1075annotated_doc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0annotated_doc-0.0.4.dist-info/RECORD,,1234Wheel-Version: 1.0Generator: pdm-backend (2.4.5)Root-Is-Purelib: trueTag: py3-none-any123from .main import Doc as Doc
__version__ = "0.0.4"123456789101112131415161718192021222324252627282930313233343536class Doc: """Define the documentation of a type annotation using `Annotated`, to be used in class attributes, function and method parameters, return values, and variables.
The value should be a positional-only string literal to allow static tools like editors and documentation generators to use it.
This complements docstrings.
The string value passed is available in the attribute `documentation`.
Example:
```Python from typing import Annotated from annotated_doc import Doc
def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None: print(f"Hi, {name}!") ``` """
def __init__(self, documentation: str, /) -> None: self.documentation = documentation
def __repr__(self) -> str: return f"Doc({self.documentation!r})"
def __hash__(self) -> int: return hash(self.documentation)
def __eq__(self, other: object) -> bool: if not isinstance(other, Doc): return NotImplemented return self.documentation == other.documentation123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202Metadata-Version: 2.4Name: h11Version: 0.16.0Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1Home-page: https://github.com/python-hyper/h11Author: Nathaniel J. SmithAuthor-email: njs@pobox.comLicense: MITClassifier: Development Status :: 3 - AlphaClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Topic :: Internet :: WWW/HTTPClassifier: Topic :: System :: NetworkingRequires-Python: >=3.8License-File: LICENSE.txtDynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: home-pageDynamic: licenseDynamic: license-fileDynamic: requires-pythonDynamic: summary
h11===
.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master :target: https://travis-ci.org/python-hyper/h11 :alt: Automated test status
.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-hyper/h11 :alt: Test coverage
.. image:: https://readthedocs.org/projects/h11/badge/?version=latest :target: http://h11.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status
This is a little HTTP/1.1 library written from scratch in Python,heavily inspired by `hyper-h2 <https://hyper-h2.readthedocs.io/>`_.
It's a "bring-your-own-I/O" library; h11 contains no IO codewhatsoever. This means you can hook h11 up to your favorite networkAPI, and that could be anything you want: synchronous, threaded,asynchronous, or your own implementation of `RFC 6214<https://tools.ietf.org/html/rfc6214>`_ -- h11 won't judge you.(Compare this to the current state of the art, where every time a `newnetwork API <https://trio.readthedocs.io/>`_ comes along then someonegets to start over reimplementing the entire HTTP protocol fromscratch.) Cory Benfield made an `excellent blog post describing thebenefits of this approach<https://lukasa.co.uk/2015/10/The_New_Hyper/>`_, or if you like videothen here's his `PyCon 2016 talk on the same theme<https://www.youtube.com/watch?v=7cC3_jGwl_U>`_.
This also means that h11 is not immediately useful out of the box:it's a toolkit for building programs that speak HTTP, not somethingthat could directly replace ``requests`` or ``twisted.web`` orwhatever. But h11 makes it much easier to implement something like``requests`` or ``twisted.web``.
At a high level, working with h11 goes like this:
1) First, create an ``h11.Connection`` object to track the state of a single HTTP/1.1 connection.
2) When you read data off the network, pass it to ``conn.receive_data(...)``; you'll get back a list of objects representing high-level HTTP "events".
3) When you want to send a high-level HTTP event, create the corresponding "event" object and pass it to ``conn.send(...)``; this will give you back some bytes that you can then push out through the network.
For example, a client might instantiate and then send a``h11.Request`` object, then zero or more ``h11.Data`` objects for therequest body (e.g., if this is a POST), and then a``h11.EndOfMessage`` to indicate the end of the message. Then theserver would then send back a ``h11.Response``, some ``h11.Data``, andits own ``h11.EndOfMessage``. If either side violates the protocol,you'll get a ``h11.ProtocolError`` exception.
h11 is suitable for implementing both servers and clients, and has apleasantly symmetric API: the events you send as a client are exactlythe ones that you receive as a server and vice-versa.
`Here's an example of a tiny HTTP client<https://github.com/python-hyper/h11/blob/master/examples/basic-client.py>`_
It also has `a fine manual <https://h11.readthedocs.io/>`_.
FAQ---
*Whyyyyy?*
I wanted to play with HTTP in `Curio<https://curio.readthedocs.io/en/latest/tutorial.html>`__ and `Trio<https://trio.readthedocs.io>`__, which at the time didn't have anyHTTP libraries. So I thought, no big deal, Python has, like, a dozendifferent implementations of HTTP, surely I can find one that'sreusable. I didn't find one, but I did find Cory's call-to-armsblog-post. So I figured, well, fine, if I have to implement HTTP fromscratch, at least I can make sure no-one *else* has to ever again.
*Should I use it?*
Maybe. You should be aware that it's a very young project. But, it'sfeature complete and has an exhaustive test-suite and complete docs,so the next step is for people to try using it and see how it goes:-). If you do then please let us know -- if nothing else we'll wantto talk to you before making any incompatible changes!
*What are the features/limitations?*
Roughly speaking, it's trying to be a robust, complete, and non-hackyimplementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230:HTTP/1.1 Message Syntax and Routing<https://tools.ietf.org/html/rfc7230>`_. That is, it mostly focuses onimplementing HTTP at the level of taking bytes on and off the wire,and the headers related to that, and tries to be anal about specconformance. It doesn't know about higher-level concerns like URLrouting, conditional GETs, cross-origin cookie policies, or contentnegotiation. But it does know how to take care of framing,cross-version differences in keep-alive handling, and the "obsoleteline folding" rule, so you can focus your energies on the hard /interesting parts for your application, and it tries to support thefull specification in the sense that any useful HTTP/1.1 conformantapplication should be able to use h11.
It's pure Python, and has no dependencies outside of the standardlibrary.
It has a test suite with 100.0% coverage for both statements andbranches.
Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3.The last Python 2-compatible version was h11 0.11.x.(Originally it had a Cython wrapper for `http-parser<https://github.com/nodejs/http-parser>`_ and a beautiful nested statemachine implemented with ``yield from`` to postprocess the output. ButI had to take these out -- the new *parser* needs fewer lines-of-codethan the old *parser wrapper*, is written in pure Python, uses noexotic language syntax, and has more features. It's sad, really; thatold state machine was really slick. I just need a few sentences hereto mourn that.)
I don't know how fast it is. I haven't benchmarked or profiled it yet,so it's probably got a few pointless hot spots, and I've been tryingto err on the side of simplicity and robustness instead ofmicro-optimization. But at the architectural level I tried hard toavoid fundamentally bad decisions, e.g., I believe that all theparsing algorithms remain linear-time even in the face of pathologicalinput like slowloris, and there are no byte-by-byte loops. (I alsobelieve that it maintains bounded memory usage in the face ofarbitrary/pathological input.)
The whole library is ~800 lines-of-code. You can read and understandthe whole thing in less than an hour. Most of the energy invested inthis so far has been spent on trying to keep things simple byminimizing special-cases and ad hoc state manipulation; even though itis now quite small and simple, I'm still annoyed that I haven'tfigured out how to make it even smaller and simpler. (Unfortunately,HTTP does not lend itself to simplicity.)
The API is ~feature complete and I don't expect the general outlinesto change much, but you can't judge an API's ergonomics until youactually document and use it, so I'd expect some changes in thedetails.
*How do I try it?*
.. code-block:: sh
$ pip install h11 $ git clone git@github.com:python-hyper/h11 $ cd h11/examples $ python basic-client.py
and go from there.
*License?*
MIT
*Code of conduct?*
Contributors are requested to follow our `code of conduct<https://github.com/python-hyper/h11/blob/master/CODE_OF_CONDUCT.md>`_ inall project spaces.1234567891011121314151617h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4h11-0.16.0.dist-info/RECORD,,1h11123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# We use native strings for all the re patterns, to take advantage of string# formatting, and then convert to bytestrings when compiling the final re# objects.
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace# OWS = *( SP / HTAB )# ; optional whitespaceOWS = r"[ \t]*"
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators# token = 1*tchar## tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"# / DIGIT / ALPHA# ; any VCHAR, except delimiterstoken = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+"
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields# field-name = tokenfield_name = token
# The standard says:## field-value = *( field-content / obs-fold )# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]# field-vchar = VCHAR / obs-text# obs-fold = CRLF 1*( SP / HTAB )# ; obsolete line folding# ; see Section 3.2.4## https://tools.ietf.org/html/rfc5234#appendix-B.1## VCHAR = %x21-7E# ; visible (printing) characters## https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string# obs-text = %x80-FF## However, the standard definition of field-content is WRONG! It disallows# fields containing a single visible character surrounded by whitespace,# e.g. "foo a bar".## See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189## So our definition of field_content attempts to fix it up...## Also, we allow lots of control characters, because apparently people assume# that they're legal in practice (e.g., google analytics makes cookies with# \x01 in them!):# https://github.com/python-hyper/h11/issues/57# We still don't allow NUL or whitespace, because those are often treated as# meta-characters and letting them through can lead to nasty issues like SSRF.vchar = r"[\x21-\x7e]"vchar_or_obs_text = r"[^\x00\s]"field_vchar = vchar_or_obs_textfield_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals())
# We handle obs-fold at a different level, and our fixed-up field_content# already grows to swallow the whole value, so ? instead of *field_value = r"({field_content})?".format(**globals())
# header-field = field-name ":" OWS field-value OWSheader_field = ( r"(?P<field_name>{field_name})" r":" r"{OWS}" r"(?P<field_value>{field_value})" r"{OWS}".format(**globals()))
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line## request-line = method SP request-target SP HTTP-version CRLF# method = token# HTTP-version = HTTP-name "/" DIGIT "." DIGIT# HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive## request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full# URL, host+port (for connect), or even "*", but in any case we are guaranteed# that it contists of the visible printing characters.method = tokenrequest_target = r"{vchar}+".format(**globals())http_version = r"HTTP/(?P<http_version>[0-9]\.[0-9])"request_line = ( r"(?P<method>{method})" r" " r"(?P<target>{request_target})" r" " r"{http_version}".format(**globals()))
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line## status-line = HTTP-version SP status-code SP reason-phrase CRLF# status-code = 3DIGIT# reason-phrase = *( HTAB / SP / VCHAR / obs-text )status_code = r"[0-9]{3}"reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals())status_line = ( r"{http_version}" r" " r"(?P<status_code>{status_code})" # However, there are apparently a few too many servers out there that just # leave out the reason phrase: # https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036 # https://github.com/seanmonstar/httparse/issues/29 # so make it optional. ?: is a non-capturing group. r"(?: (?P<reason>{reason_phrase}))?".format(**globals()))
HEXDIG = r"[0-9A-Fa-f]"# Actually## chunk-size = 1*HEXDIG## but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20chunk_size = r"({HEXDIG}){{1,20}}".format(**globals())# Actually## chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )## but we aren't parsing the things so we don't really care.chunk_ext = r";.*"chunk_header = ( r"(?P<chunk_size>{chunk_size})" r"(?P<chunk_ext>{chunk_ext})?" r"{OWS}\r\n".format( **globals() ) # Even though the specification does not allow for extra whitespaces, # we are lenient with trailing whitespaces because some servers on the wild use it.)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365################################################################# The core state machine################################################################## Rule 1: everything that affects the state machine and state transitions must# live here in this file. As much as possible goes into the table-based# representation, but for the bits that don't quite fit, the actual code and# state must nonetheless live here.## Rule 2: this file does not know about what role we're playing; it only knows# about HTTP request/response cycles in the abstract. This ensures that we# don't cheat and apply different rules to local and remote parties.### Theory of operation# ===================## Possibly the simplest way to think about this is that we actually have 5# different state machines here. Yes, 5. These are:## 1) The client state, with its complicated automaton (see the docs)# 2) The server state, with its complicated automaton (see the docs)# 3) The keep-alive state, with possible states {True, False}# 4) The SWITCH_CONNECT state, with possible states {False, True}# 5) The SWITCH_UPGRADE state, with possible states {False, True}## For (3)-(5), the first state listed is the initial state.## (1)-(3) are stored explicitly in member variables. The last# two are stored implicitly in the pending_switch_proposals set as:# (state of 4) == (_SWITCH_CONNECT in pending_switch_proposals)# (state of 5) == (_SWITCH_UPGRADE in pending_switch_proposals)## And each of these machines has two different kinds of transitions:## a) Event-triggered# b) State-triggered## Event triggered is the obvious thing that you'd think it is: some event# happens, and if it's the right event at the right time then a transition# happens. But there are somewhat complicated rules for which machines can# "see" which events. (As a rule of thumb, if a machine "sees" an event, this# means two things: the event can affect the machine, and if the machine is# not in a state where it expects that event then it's an error.) These rules# are:## 1) The client machine sees all h11.events objects emitted by the client.## 2) The server machine sees all h11.events objects emitted by the server.## It also sees the client's Request event.## And sometimes, server events are annotated with a _SWITCH_* event. For# example, we can have a (Response, _SWITCH_CONNECT) event, which is# different from a regular Response event.## 3) The keep-alive machine sees the process_keep_alive_disabled() event# (which is derived from Request/Response events), and this event# transitions it from True -> False, or from False -> False. There's no way# to transition back.## 4&5) The _SWITCH_* machines transition from False->True when we get a# Request that proposes the relevant type of switch (via# process_client_switch_proposals), and they go from True->False when we# get a Response that has no _SWITCH_* annotation.## So that's event-triggered transitions.## State-triggered transitions are less standard. What they do here is couple# the machines together. The way this works is, when certain *joint*# configurations of states are achieved, then we automatically transition to a# new *joint* state. So, for example, if we're ever in a joint state with## client: DONE# keep-alive: False## then the client state immediately transitions to:## client: MUST_CLOSE## This is fundamentally different from an event-based transition, because it# doesn't matter how we arrived at the {client: DONE, keep-alive: False} state# -- maybe the client transitioned SEND_BODY -> DONE, or keep-alive# transitioned True -> False. Either way, once this precondition is satisfied,# this transition is immediately triggered.## What if two conflicting state-based transitions get enabled at the same# time? In practice there's only one case where this arises (client DONE -># MIGHT_SWITCH_PROTOCOL versus DONE -> MUST_CLOSE), and we resolve it by# explicitly prioritizing the DONE -> MIGHT_SWITCH_PROTOCOL transition.## Implementation# --------------## The event-triggered transitions for the server and client machines are all# stored explicitly in a table. Ditto for the state-triggered transitions that# involve just the server and client state.## The transitions for the other machines, and the state-triggered transitions# that involve the other machines, are written out as explicit Python code.## It'd be nice if there were some cleaner way to do all this. This isn't# *too* terrible, but I feel like it could probably be better.## WARNING# -------## The script that generates the state machine diagrams for the docs knows how# to read out the EVENT_TRIGGERED_TRANSITIONS and STATE_TRIGGERED_TRANSITIONS# tables. But it can't automatically read the transitions that are written# directly in Python code. So if you touch those, you need to also update the# script to keep it in sync!from typing import cast, Dict, Optional, Set, Tuple, Type, Union
from ._events import *from ._util import LocalProtocolError, Sentinel
# Everything in __all__ gets re-exported as part of the h11 public API.__all__ = [ "CLIENT", "SERVER", "IDLE", "SEND_RESPONSE", "SEND_BODY", "DONE", "MUST_CLOSE", "CLOSED", "MIGHT_SWITCH_PROTOCOL", "SWITCHED_PROTOCOL", "ERROR",]
class CLIENT(Sentinel, metaclass=Sentinel): pass
class SERVER(Sentinel, metaclass=Sentinel): pass
# Statesclass IDLE(Sentinel, metaclass=Sentinel): pass
class SEND_RESPONSE(Sentinel, metaclass=Sentinel): pass
class SEND_BODY(Sentinel, metaclass=Sentinel): pass
class DONE(Sentinel, metaclass=Sentinel): pass
class MUST_CLOSE(Sentinel, metaclass=Sentinel): pass
class CLOSED(Sentinel, metaclass=Sentinel): pass
class ERROR(Sentinel, metaclass=Sentinel): pass
# Switch typesclass MIGHT_SWITCH_PROTOCOL(Sentinel, metaclass=Sentinel): pass
class SWITCHED_PROTOCOL(Sentinel, metaclass=Sentinel): pass
class _SWITCH_UPGRADE(Sentinel, metaclass=Sentinel): pass
class _SWITCH_CONNECT(Sentinel, metaclass=Sentinel): pass
EventTransitionType = Dict[ Type[Sentinel], Dict[ Type[Sentinel], Dict[Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], Type[Sentinel]], ],]
EVENT_TRIGGERED_TRANSITIONS: EventTransitionType = { CLIENT: { IDLE: {Request: SEND_BODY, ConnectionClosed: CLOSED}, SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, DONE: {ConnectionClosed: CLOSED}, MUST_CLOSE: {ConnectionClosed: CLOSED}, CLOSED: {ConnectionClosed: CLOSED}, MIGHT_SWITCH_PROTOCOL: {}, SWITCHED_PROTOCOL: {}, ERROR: {}, }, SERVER: { IDLE: { ConnectionClosed: CLOSED, Response: SEND_BODY, # Special case: server sees client Request events, in this form (Request, CLIENT): SEND_RESPONSE, }, SEND_RESPONSE: { InformationalResponse: SEND_RESPONSE, Response: SEND_BODY, (InformationalResponse, _SWITCH_UPGRADE): SWITCHED_PROTOCOL, (Response, _SWITCH_CONNECT): SWITCHED_PROTOCOL, }, SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, DONE: {ConnectionClosed: CLOSED}, MUST_CLOSE: {ConnectionClosed: CLOSED}, CLOSED: {ConnectionClosed: CLOSED}, SWITCHED_PROTOCOL: {}, ERROR: {}, },}
StateTransitionType = Dict[ Tuple[Type[Sentinel], Type[Sentinel]], Dict[Type[Sentinel], Type[Sentinel]]]
# NB: there are also some special-case state-triggered transitions hard-coded# into _fire_state_triggered_transitions below.STATE_TRIGGERED_TRANSITIONS: StateTransitionType = { # (Client state, Server state) -> new states # Protocol negotiation (MIGHT_SWITCH_PROTOCOL, SWITCHED_PROTOCOL): {CLIENT: SWITCHED_PROTOCOL}, # Socket shutdown (CLOSED, DONE): {SERVER: MUST_CLOSE}, (CLOSED, IDLE): {SERVER: MUST_CLOSE}, (ERROR, DONE): {SERVER: MUST_CLOSE}, (DONE, CLOSED): {CLIENT: MUST_CLOSE}, (IDLE, CLOSED): {CLIENT: MUST_CLOSE}, (DONE, ERROR): {CLIENT: MUST_CLOSE},}
class ConnectionState: def __init__(self) -> None: # Extra bits of state that don't quite fit into the state model.
# If this is False then it enables the automatic DONE -> MUST_CLOSE # transition. Don't set this directly; call .keep_alive_disabled() self.keep_alive = True
# This is a subset of {UPGRADE, CONNECT}, containing the proposals # made by the client for switching protocols. self.pending_switch_proposals: Set[Type[Sentinel]] = set()
self.states: Dict[Type[Sentinel], Type[Sentinel]] = {CLIENT: IDLE, SERVER: IDLE}
def process_error(self, role: Type[Sentinel]) -> None: self.states[role] = ERROR self._fire_state_triggered_transitions()
def process_keep_alive_disabled(self) -> None: self.keep_alive = False self._fire_state_triggered_transitions()
def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None: self.pending_switch_proposals.add(switch_event) self._fire_state_triggered_transitions()
def process_event( self, role: Type[Sentinel], event_type: Type[Event], server_switch_event: Optional[Type[Sentinel]] = None, ) -> None: _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type if server_switch_event is not None: assert role is SERVER if server_switch_event not in self.pending_switch_proposals: raise LocalProtocolError( "Received server _SWITCH_UPGRADE event without a pending proposal" ) _event_type = (event_type, server_switch_event) if server_switch_event is None and _event_type is Response: self.pending_switch_proposals = set() self._fire_event_triggered_transitions(role, _event_type) # Special case: the server state does get to see Request # events. if _event_type is Request: assert role is CLIENT self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) self._fire_state_triggered_transitions()
def _fire_event_triggered_transitions( self, role: Type[Sentinel], event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], ) -> None: state = self.states[role] try: new_state = EVENT_TRIGGERED_TRANSITIONS[role][state][event_type] except KeyError: event_type = cast(Type[Event], event_type) raise LocalProtocolError( "can't handle event type {} when role={} and state={}".format( event_type.__name__, role, self.states[role] ) ) from None self.states[role] = new_state
def _fire_state_triggered_transitions(self) -> None: # We apply these rules repeatedly until converging on a fixed point while True: start_states = dict(self.states)
# It could happen that both these special-case transitions are # enabled at the same time: # # DONE -> MIGHT_SWITCH_PROTOCOL # DONE -> MUST_CLOSE # # For example, this will always be true of a HTTP/1.0 client # requesting CONNECT. If this happens, the protocol switch takes # priority. From there the client will either go to # SWITCHED_PROTOCOL, in which case it's none of our business when # they close the connection, or else the server will deny the # request, in which case the client will go back to DONE and then # from there to MUST_CLOSE. if self.pending_switch_proposals: if self.states[CLIENT] is DONE: self.states[CLIENT] = MIGHT_SWITCH_PROTOCOL
if not self.pending_switch_proposals: if self.states[CLIENT] is MIGHT_SWITCH_PROTOCOL: self.states[CLIENT] = DONE
if not self.keep_alive: for role in (CLIENT, SERVER): if self.states[role] is DONE: self.states[role] = MUST_CLOSE
# Tabular state-triggered transitions joint_state = (self.states[CLIENT], self.states[SERVER]) changes = STATE_TRIGGERED_TRANSITIONS.get(joint_state, {}) self.states.update(changes)
if self.states == start_states: # Fixed point reached return
def start_next_cycle(self) -> None: if self.states != {CLIENT: DONE, SERVER: DONE}: raise LocalProtocolError( f"not in a reusable state. self.states={self.states}" ) # Can't reach DONE/DONE with any of these active, but still, let's be # sure. assert self.keep_alive assert not self.pending_switch_proposals self.states = {CLIENT: IDLE, SERVER: IDLE}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import contextlibimport typing
ExceptionMapping = typing.Mapping[typing.Type[Exception], typing.Type[Exception]]
@contextlib.contextmanagerdef map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]: try: yield except Exception as exc: # noqa: PIE786 for from_exc, to_exc in map.items(): if isinstance(exc, from_exc): raise to_exc(exc) from exc raise # pragma: nocover
class ConnectionNotAvailable(Exception): pass
class ProxyError(Exception): pass
class UnsupportedProtocol(Exception): pass
class ProtocolError(Exception): pass
class RemoteProtocolError(ProtocolError): pass
class LocalProtocolError(ProtocolError): pass
# Timeout errors
class TimeoutException(Exception): pass
class PoolTimeout(TimeoutException): pass
class ConnectTimeout(TimeoutException): pass
class ReadTimeout(TimeoutException): pass
class WriteTimeout(TimeoutException): pass
# Network errors
class NetworkError(Exception): pass
class ConnectError(NetworkError): pass
class ReadError(NetworkError): pass
class WriteError(NetworkError): pass12345678910111213Copyright (c) 2018, Tzu-ping Chung <uranusjr@gmail.com>
Permission to use, copy, modify, and distribute this software for anypurpose with or without fee is hereby granted, provided that the abovecopyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIESWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OFMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FORANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGESWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN ANACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OFOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.12345678910111213shellingham/__init__.py,sha256=pAKXUPKUdwyErC0ZjS-5w-fRdSbmdcfvnpt_x1yWqtA,635shellingham/_core.py,sha256=v-CTr_7F7cJAtNnzpa1N_Hl8afkY5yiDA4joGmsUBu0,300shellingham/nt.py,sha256=m6J6SuwyqVVlxXT9Bc-9F_1x-T5u0gCFFrRAF2LIkeg,4516shellingham/posix/__init__.py,sha256=pB69qtvZJ_yIf48nl4-ZfS3wLwwuXuknXOZhBnC2T1o,3129shellingham/posix/_core.py,sha256=_v18UaXbzr4muNhr3-mH1FdSdjZ_dOXQrtUyomIbKYQ,81shellingham/posix/proc.py,sha256=nSUxIuQSotvaDW76i0oTQAM9aZ9PXBLFAEktWljSKCo,2659shellingham/posix/ps.py,sha256=NGmDKCukhNp0lahwYCaMXphBYaVbhbiR9BtE0OkT8qU,1770shellingham-1.5.4.dist-info/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751shellingham-1.5.4.dist-info/METADATA,sha256=GD2AIgo3STJieVc53TV8xbs_Sb05DMkZjVGA5UUaB_o,3461shellingham-1.5.4.dist-info/WHEEL,sha256=iYlv5fX357PQyRT2o6tw1bN-YcKFFHKqB_LwHO5wP-g,110shellingham-1.5.4.dist-info/top_level.txt,sha256=uKMQL5AKxPi4O9_Rbd838QeEs4ImpGQKNbEDZYqgBgk,12shellingham-1.5.4.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1shellingham-1.5.4.dist-info/RECORD,,123456Wheel-Version: 1.0Generator: bdist_wheel (0.41.2)Root-Is-Purelib: trueTag: py2-none-anyTag: py3-none-any
1shellingham1
1234567891011121314151617181920212223import importlibimport os
from ._core import ShellDetectionFailure
__version__ = "1.5.4"
def detect_shell(pid=None, max_depth=10): name = os.name try: impl = importlib.import_module(".{}".format(name), __name__) except ImportError: message = "Shell detection not implemented for {0!r}".format(name) raise RuntimeError(message) try: get_shell = impl.get_shell except AttributeError: raise RuntimeError("get_shell not implemented for {0!r}".format(name)) shell = get_shell(pid, max_depth=max_depth) if shell: return shell raise ShellDetectionFailure()1234567891011SHELL_NAMES = ( {"sh", "bash", "dash", "ash"} # Bourne. | {"csh", "tcsh"} # C. | {"ksh", "zsh", "fish"} # Common alternatives. | {"cmd", "powershell", "pwsh"} # Microsoft. | {"elvish", "xonsh", "nu"} # More exotic.)
class ShellDetectionFailure(EnvironmentError): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163import contextlibimport ctypesimport os
from ctypes.wintypes import ( BOOL, CHAR, DWORD, HANDLE, LONG, LPWSTR, MAX_PATH, PDWORD, ULONG,)
from shellingham._core import SHELL_NAMES
INVALID_HANDLE_VALUE = HANDLE(-1).valueERROR_NO_MORE_FILES = 18ERROR_INSUFFICIENT_BUFFER = 122TH32CS_SNAPPROCESS = 2PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
kernel32 = ctypes.windll.kernel32
def _check_handle(error_val=0): def check(ret, func, args): if ret == error_val: raise ctypes.WinError() return ret
return check
def _check_expected(expected): def check(ret, func, args): if ret: return True code = ctypes.GetLastError() if code == expected: return False raise ctypes.WinError(code)
return check
class ProcessEntry32(ctypes.Structure): _fields_ = ( ("dwSize", DWORD), ("cntUsage", DWORD), ("th32ProcessID", DWORD), ("th32DefaultHeapID", ctypes.POINTER(ULONG)), ("th32ModuleID", DWORD), ("cntThreads", DWORD), ("th32ParentProcessID", DWORD), ("pcPriClassBase", LONG), ("dwFlags", DWORD), ("szExeFile", CHAR * MAX_PATH), )
kernel32.CloseHandle.argtypes = [HANDLE]kernel32.CloseHandle.restype = BOOL
kernel32.CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD]kernel32.CreateToolhelp32Snapshot.restype = HANDLEkernel32.CreateToolhelp32Snapshot.errcheck = _check_handle( # type: ignore INVALID_HANDLE_VALUE,)
kernel32.Process32First.argtypes = [HANDLE, ctypes.POINTER(ProcessEntry32)]kernel32.Process32First.restype = BOOLkernel32.Process32First.errcheck = _check_expected( # type: ignore ERROR_NO_MORE_FILES,)
kernel32.Process32Next.argtypes = [HANDLE, ctypes.POINTER(ProcessEntry32)]kernel32.Process32Next.restype = BOOLkernel32.Process32Next.errcheck = _check_expected( # type: ignore ERROR_NO_MORE_FILES,)
kernel32.GetCurrentProcessId.argtypes = []kernel32.GetCurrentProcessId.restype = DWORD
kernel32.OpenProcess.argtypes = [DWORD, BOOL, DWORD]kernel32.OpenProcess.restype = HANDLEkernel32.OpenProcess.errcheck = _check_handle( # type: ignore INVALID_HANDLE_VALUE,)
kernel32.QueryFullProcessImageNameW.argtypes = [HANDLE, DWORD, LPWSTR, PDWORD]kernel32.QueryFullProcessImageNameW.restype = BOOLkernel32.QueryFullProcessImageNameW.errcheck = _check_expected( # type: ignore ERROR_INSUFFICIENT_BUFFER,)
@contextlib.contextmanagerdef _handle(f, *args, **kwargs): handle = f(*args, **kwargs) try: yield handle finally: kernel32.CloseHandle(handle)
def _iter_processes(): f = kernel32.CreateToolhelp32Snapshot with _handle(f, TH32CS_SNAPPROCESS, 0) as snap: entry = ProcessEntry32() entry.dwSize = ctypes.sizeof(entry) ret = kernel32.Process32First(snap, entry) while ret: yield entry ret = kernel32.Process32Next(snap, entry)
def _get_full_path(proch): size = DWORD(MAX_PATH) while True: path_buff = ctypes.create_unicode_buffer("", size.value) if kernel32.QueryFullProcessImageNameW(proch, 0, path_buff, size): return path_buff.value size.value *= 2
def get_shell(pid=None, max_depth=10): proc_map = { proc.th32ProcessID: (proc.th32ParentProcessID, proc.szExeFile) for proc in _iter_processes() } pid = pid or os.getpid()
for _ in range(0, max_depth + 1): try: ppid, executable = proc_map[pid] except KeyError: # No such process? Give up. break
# The executable name would be encoded with the current code page if # we're in ANSI mode (usually). Try to decode it into str/unicode, # replacing invalid characters to be safe (not thoeratically necessary, # I think). Note that we need to use 'mbcs' instead of encoding # settings from sys because this is from the Windows API, not Python # internals (which those settings reflect). (pypa/pipenv#3382) if isinstance(executable, bytes): executable = executable.decode("mbcs", "replace")
name = executable.rpartition(".")[0].lower() if name not in SHELL_NAMES: pid = ppid continue
key = PROCESS_QUERY_LIMITED_INFORMATION with _handle(kernel32.OpenProcess, key, 0, pid) as proch: return (name, _get_full_path(proch))
return None123import collections
Process = collections.namedtuple("Process", "args pid ppid")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import ioimport osimport reimport sys
from ._core import Process
# FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=procfs# NetBSD: https://man.netbsd.org/NetBSD-9.3-STABLE/mount_procfs.8# DragonFlyBSD: https://www.dragonflybsd.org/cgi/web-man?command=procfsBSD_STAT_PPID = 2
# See https://docs.kernel.org/filesystems/proc.htmlLINUX_STAT_PPID = 3
STAT_PATTERN = re.compile(r"\(.+\)|\S+")
def detect_proc(): """Detect /proc filesystem style.
This checks the /proc/{pid} directory for possible formats. Returns one of the following as str:
* `stat`: Linux-style, i.e. ``/proc/{pid}/stat``. * `status`: BSD-style, i.e. ``/proc/{pid}/status``. """ pid = os.getpid() for name in ("stat", "status"): if os.path.exists(os.path.join("/proc", str(pid), name)): return name raise ProcFormatError("unsupported proc format")
def _use_bsd_stat_format(): try: return os.uname().sysname.lower() in ("freebsd", "netbsd", "dragonfly") except Exception: return False
def _get_ppid(pid, name): path = os.path.join("/proc", str(pid), name) with io.open(path, encoding="ascii", errors="replace") as f: parts = STAT_PATTERN.findall(f.read()) # We only care about TTY and PPID -- both are numbers. if _use_bsd_stat_format(): return parts[BSD_STAT_PPID] return parts[LINUX_STAT_PPID]
def _get_cmdline(pid): path = os.path.join("/proc", str(pid), "cmdline") encoding = sys.getfilesystemencoding() or "utf-8" with io.open(path, encoding=encoding, errors="replace") as f: # XXX: Command line arguments can be arbitrary byte sequences, not # necessarily decodable. For Shellingham's purpose, however, we don't # care. (pypa/pipenv#2820) # cmdline appends an extra NULL at the end, hence the [:-1]. return tuple(f.read().split("\0")[:-1])
class ProcFormatError(EnvironmentError): pass
def iter_process_parents(pid, max_depth=10): """Try to look up the process tree via the /proc interface.""" stat_name = detect_proc()
# Inner generator function so we correctly throw an error eagerly if proc # is not supported, rather than on the first call to the iterator. This # allows the call site detects the correct implementation. def _iter_process_parents(pid, max_depth): for _ in range(max_depth): ppid = _get_ppid(pid, stat_name) args = _get_cmdline(pid) yield Process(args=args, pid=pid, ppid=ppid) if ppid == "0": break pid = ppid
return _iter_process_parents(pid, max_depth)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import errnoimport subprocessimport sys
from ._core import Process
class PsNotAvailable(EnvironmentError): pass
def iter_process_parents(pid, max_depth=10): """Try to look up the process tree via the output of `ps`.""" try: cmd = ["ps", "-ww", "-o", "pid=", "-o", "ppid=", "-o", "args="] output = subprocess.check_output(cmd) except OSError as e: # Python 2-compatible FileNotFoundError. if e.errno != errno.ENOENT: raise raise PsNotAvailable("ps not found") except subprocess.CalledProcessError as e: # `ps` can return 1 if the process list is completely empty. # (sarugaku/shellingham#15) if not e.output.strip(): return raise if not isinstance(output, str): encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() output = output.decode(encoding)
processes_mapping = {} for line in output.split("\n"): try: _pid, ppid, args = line.strip().split(None, 2) # XXX: This is not right, but we are really out of options. # ps does not offer a sane way to decode the argument display, # and this is "Good Enough" for obtaining shell names. Hopefully # people don't name their shell with a space, or have something # like "/usr/bin/xonsh is uber". (sarugaku/shellingham#14) args = tuple(a.strip() for a in args.split(" ")) except ValueError: continue processes_mapping[_pid] = Process(args=args, pid=_pid, ppid=ppid)
for _ in range(max_depth): try: process = processes_mapping[pid] except KeyError: return yield process pid = process.ppid.cache/pip/http-v2/5/5/9/a/2/559a28d2d50a6d0988e3c56e5d0d411789da84005e4420f1a26bb23eAdded
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/_monitor.pyAdded+104
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/_tqdm_pandas.pyAdded+24
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/contrib/concurrent.pyAdded+105
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/contrib/utils_worker.pyAdded+38
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/std.pyAdded+1525
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/utils.pyAdded+325
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/METADATAAdded+38
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/RECORDAdded+19
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/licenses/LICENSEAdded+21
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_async_read_write.pyAdded+207
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_error.pyAdded+28
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft.pyAdded+227
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/__init__.pyAdded+12
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/_async.pyAdded+213
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/_sync.pyAdded+849
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_unix.pyAdded+116
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_windows.pyAdded+111
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/py.typedAdded
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/version.pyAdded+24
.cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions-4.15.0.dist-info/METADATAAdded+72
.cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions-4.15.0.dist-info/WHEELAdded+4
.cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions.pyAdded
.cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc-0.0.4.dist-info/RECORDAdded+8
.cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc-0.0.4.dist-info/WHEELAdded+4
.cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc/__init__.pyAdded+3
.cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc/main.pyAdded+36
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/METADATAAdded+202
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/RECORDAdded+17
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/top_level.txtAdded+1
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11/_abnf.pyAdded+132
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11/_state.pyAdded+365
.cache/uv/archive-v0/YlYoCgs7J-Rpy5AtSN3P_/httpcore/_exceptions.pyAdded+81
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/LICENSEAdded+13
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/RECORDAdded+13
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/WHEELAdded+6
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/top_level.txtAdded+1
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/zip-safeAdded+1
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/__init__.pyAdded+23
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/_core.pyAdded+11
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/nt.pyAdded+163
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/_core.pyAdded+3
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/proc.pyAdded+83
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/ps.pyAdded+51
.cache/uv/archive-v0/mZts5W47V4a3dXgJR251L/idna/uts46data.pyAdded
.cache/uv/simple-v18/pypi/certifi.rkyvAdded
.cache/uv/simple-v18/pypi/h11.rkyvAdded
.cache/uv/simple-v18/pypi/httpcore.rkyvAdded
.cache/uv/simple-v18/pypi/markdown-it-py.rkyvAdded
.cache/uv/simple-v18/pypi/mdurl.rkyvAdded