o
    0׾gP                     @   s2  d Z ddlmZ ddlmZ ddlZg dZejdZG dd de	Z
G d	d
 d
eZd[ddZdd Zi Zdd Zdd Zdd Zdd Zdd Ze Zdd Zdd Zdd ZG dd  d eZ				!	!	!d\d"d#Zd$d% Z				!	!	!d\d&d'Zd(d) Zd*d+ Zd,d- Z ed]d.d/Z!ed0d1 Z"ed2d3 Z#ed4d5 Z$ed6d7 Z%d8d9 Z&e	!	!	d^d:d;Z'ed_d<d=Z(ed>d? Z)d`dAdBZ*edadCdDZ+edbdEdFZ,edbdGdHZ-edIdJ Z.edKdL Z/edMdN Z0dOdP Z1dQdR Z2	!	!	!	!dcdTdUZ3dVdW Z4dXdY Z5e5 d e4_ e6dZkre4  dS dS )da=  
Make the standard library cooperative.

The primary purpose of this module is to carefully patch, in place,
portions of the standard library with gevent-friendly functions that
behave in the same way as the original (at least as closely as possible).

The primary interface to this is the :func:`patch_all` function, which
performs all the available patches. It accepts arguments to limit the
patching to certain modules, but most programs **should** use the
default values as they receive the most wide-spread testing, and some monkey
patches have dependencies on others.

Patching **should be done as early as possible** in the lifecycle of the
program. For example, the main module (the one that tests against
``__main__`` or is otherwise the first imported) should begin with
this code, ideally before any other imports::

    from gevent import monkey
    monkey.patch_all()

A corollary of the above is that patching **should be done on the main
thread** and **should be done while the program is single-threaded**.

.. tip::

    Some frameworks, such as gunicorn, handle monkey-patching for you.
    Check their documentation to be sure.

.. warning::

    Patching too late can lead to unreliable behaviour (for example, some
    modules may still use blocking sockets) or even errors.

.. tip::

    Be sure to read the documentation for each patch function to check for
    known incompatibilities.

Querying
========

Sometimes it is helpful to know if objects have been monkey-patched, and in
advanced cases even to have access to the original standard library functions. This
module provides functions for that purpose.

- :func:`is_module_patched`
- :func:`is_object_patched`
- :func:`get_original`

.. _plugins:

Plugins and Events
==================

Beginning in gevent 1.3, events are emitted during the monkey patching process.
These events are delivered first to :mod:`gevent.events` subscribers, and then
to `setuptools entry points`_.

The following events are defined. They are listed in (roughly) the order
that a call to :func:`patch_all` will emit them.

- :class:`gevent.events.GeventWillPatchAllEvent`
- :class:`gevent.events.GeventWillPatchModuleEvent`
- :class:`gevent.events.GeventDidPatchModuleEvent`
- :class:`gevent.events.GeventDidPatchBuiltinModulesEvent`
- :class:`gevent.events.GeventDidPatchAllEvent`

Each event class documents the corresponding setuptools entry point name. The
entry points will be called with a single argument, the same instance of
the class that was sent to the subscribers.

You can subscribe to the events to monitor the monkey-patching process and
to manipulate it, for example by raising :exc:`gevent.events.DoNotPatch`.

You can also subscribe to the events to provide additional patching beyond what
gevent distributes, either for additional standard library modules, or
for third-party packages. The suggested time to do this patching is in
the subscriber for :class:`gevent.events.GeventDidPatchBuiltinModulesEvent`.
For example, to automatically patch `psycopg2`_ using `psycogreen`_
when the call to :func:`patch_all` is made, you could write code like this::

    # mypackage.py
    def patch_psycopg(event):
        from psycogreen.gevent import patch_psycopg
        patch_psycopg()

In your ``setup.py`` you would register it like this::

    from setuptools import setup
    setup(
        ...
        entry_points={
            'gevent.plugins.monkey.did_patch_builtins': [
                'psycopg2 = mypackage:patch_psycopg',
            ],
        },
        ...
    )

For more complex patching, gevent provides a helper method
that you can call to replace attributes of modules with attributes of your
own modules. This function also takes care of emitting the appropriate events.

- :func:`patch_module`

.. _setuptools entry points: http://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins
.. _psycopg2: https://pypi.python.org/pypi/psycopg2
.. _psycogreen: https://pypi.python.org/pypi/psycogreen

Use as a module
===============

Sometimes it is useful to run existing python scripts or modules that
were not built to be gevent aware under gevent. To do so, this module
can be run as the main module, passing the script and its arguments.
For details, see the :func:`main` function.

.. versionchanged:: 1.3b1
   Added support for plugins and began emitting will/did patch events.
    )absolute_import)print_functionN)	patch_allpatch_builtins	patch_dnspatch_ospatch_queuepatch_selectpatch_signalpatch_socket	patch_sslpatch_subprocess	patch_syspatch_thread
patch_timeget_originalis_module_patchedis_object_patchedpatch_modulemainwinc                   @   s   e Zd ZdZdd ZdS )_BadImplementsz6
    Raised when ``__implements__`` is incorrect.
    c                 C   s   t | d|f  d S )Nz7Module %r has a bad or missing value for __implements__)AttributeError__init__)selfmodule r   W/var/www/html/backend_erp/backend_erp_env/lib/python3.10/site-packages/gevent/monkey.pyr      s   z_BadImplements.__init__N)__name__
__module____qualname____doc__r   r   r   r   r   r      s    r   c                   @   s   e Zd ZdZdS )MonkeyPatchWarningzE
    The type of warnings we issue.

    .. versionadded:: 1.3a2
    N)r   r   r    r!   r   r   r   r   r"      s    r"   c                 C   s   ddl m} || _||  d S )Nr   )notify_and_call_entry_points)gevent.eventsr#   	_warnings)eventr%   r#   r   r   r   _notify_patch   s   r'   c                    s$   ddl m} |  fdd}|S )Nr   )wrapsc                     s2   ddl m} z | i |W S  |y   Y dS w )Nr   )
DoNotPatchF)r$   r)   )argskwargsr)   funcr   r   ignores   s   z$_ignores_DoNotPatch.<locals>.ignores)	functoolsr(   )r-   r(   r.   r   r,   r   _ignores_DoNotPatch   s   r0   c                 C   s   | t v S )z
    Check if a module has been replaced with a cooperative version.

    :param str mod_name: The name of the standard library module,
        e.g., ``'socket'``.

    )saved)mod_namer   r   r   r      s   r   c                 C   s   t | o	|t|  v S )a$  
    Check if an object in a module has been replaced with a
    cooperative version.

    :param str mod_name: The name of the standard library module,
        e.g., ``'socket'``.
    :param str item_name: The name of the attribute in the module,
        e.g., ``'create_connection'``.

    )r   r1   )r2   	item_namer   r   r   r      s   r   c                   C   s   t tS N)boolr1   r   r   r   r   is_anything_patched   s   	r6   c                 C   sZ   t | i }g }d }|D ]}||v r|||  q|d u r"t| }|t|| q|S r4   )r1   getappend
__import__getattr)nameitemsdvaluesr   itemr   r   r   _get_original   s   r@   c              	   C   s   t | tr| gn| }t |tr|g}d}n|}d}|D ]%}zt||}W n ty4   ||d u r2 Y qw |r=|d   S |  S dS )a  
    Retrieve the original object from a module.

    If the object has not been patched, then that object will still be
    retrieved.

    :param str mod_name: The name of the standard library module,
        e.g., ``'socket'``. Can also be a sequence of standard library
        modules giving alternate names to try, e.g., ``('thread', '_thread')``;
        the first importable module will supply all *item_name* items.
    :param item_name: A string or sequence of strings naming the
        attribute(s) on the module ``mod_name`` to return.

    :return: The original value if a string was given for
             ``item_name`` or a sequence of original values if a
             sequence was passed.
    TFr   N)
isinstancestrr@   ImportError)r2   r3   	mod_names
item_namesunpackmodresultr   r   r   r      s    
r   c                 C   s:   t | |t}|turt| ji || t| || d S r4   )r:   _NONEr1   
setdefaultr   setattr)r   attrnewitemolditemr   r   r   
patch_item"  s   rP   c                 C   s<   t | |t}|tu rd S t| ji || t| | d S r4   )r:   rJ   r1   rK   r   delattr)r   rM   rO   r   r   r   remove_item)  s
   rR   c                    sR    fdd}d| d }zt | |}W n ty    dd }Y nw |||| d S )Nc                    s   t |   d S r4   )_queue_warning)messager%   r   r   warn4  s   z __call_module_hook.<locals>.warn_gevent__monkey_patchc                  W   s   d S r4   r   )r*   r   r   r   <lambda>;      z$__call_module_hook.<locals>.<lambda>)r:   r   )gevent_moduler;   r   r<   r%   rV   	func_namer-   r   rU   r   __call_module_hook1  s   r]   c                   @   s,   e Zd ZeeZdd Zdd Zdd ZdS )_GeventDoPatchRequestc                 C   s    || _ || _|| _|pi | _d S r4   )target_modulesource_moduler<   patch_kwargs)r   r_   r`   r<   ra   r   r   r   r   E  s   z_GeventDoPatchRequest.__init__c                 C   s&   | j D ]}t| j|t| j| qd S r4   )r<   rP   r_   r:   r`   )r   rM   r   r   r   default_patch_itemsO  s   
z)_GeventDoPatchRequest.default_patch_itemsc                 G   s2   t |tr|f| }| j}|D ]}t|| qd S r4   )rB   rC   r_   rR   )r   r_   r<   r?   r   r   r   rR   S  s   

z!_GeventDoPatchRequest.remove_itemN)r   r   r    staticmethodr   r   rb   rR   r   r   r   r   r^   A  s
    
r^   Tc                 C   s   ddl m} |du rt|dd}|du rt|z|r#t|d| || |r1t|| j|| || W n |jy=   Y dS w t|dt	j
}	t	| |||}
|	|
 |rZt|d| || |rft|| j||  d	S )
aU  
    patch_module(target_module, source_module, items=None)

    Replace attributes in *target_module* with the attributes of the
    same name in *source_module*.

    The *source_module* can provide some attributes to customize the process:

    * ``__implements__`` is a list of attribute names to copy; if not present,
      the *items* keyword argument is mandatory. ``__implements__`` must only have
      names from the standard library module in it.
    * ``_gevent_will_monkey_patch(target_module, items, warn, **kwargs)``
    * ``_gevent_did_monkey_patch(target_module, items, warn, **kwargs)``
      These two functions in the *source_module* are called *if* they exist,
      before and after copying attributes, respectively. The "will" function
      may modify *items*. The value of *warn* is a function that should be called
      with a single string argument to issue a warning to the user. If the "will"
      function raises :exc:`gevent.events.DoNotPatch`, no patching will be done. These functions
      are called before any event subscribers or plugins.

    :keyword list items: A list of attribute names to replace. If
       not given, this will be taken from the *source_module* ``__implements__``
       attribute.
    :return: A true value if patching was done, a false value if patching was canceled.

    .. versionadded:: 1.3b1
    r   eventsN__implements__willF_gevent_do_monkey_patchdidT)geventre   r:   r   r]   r'   GeventWillPatchModuleEventr   r)   r^   rb   GeventDidPatchModuleEvent)r_   r`   r<   r%   _patch_kwargs_notify_will_subscribers_notify_did_subscribers_call_hooksre   do_patchrequestr   r   r   r   \  sF   !

r   c                 C   s0   t td|  | }t |d| }t|}|||fS )z
    Test that the source and target modules for *name* are
    available and return them.

    :raise ImportError: If the source or target cannot be imported.
    :return: The tuple ``(gevent_module, target_module, target_module_name)``
    gevent.
__target__)r:   r9   )r;   r[   target_module_namer_   r   r   r   _check_availability  s   

rv   c              
   C   s   t | \}}}	t||||||||d t|dd}
|
D ]'}tj|}|d urB||urBt|d  t||||dddd t|	 t|< q||fS )N)r<   r%   rm   rn   ro   rp   __alternate_targets__r   F)r<   r%   rn   ro   rp   )rv   r   r:   sysmodulesr7   r1   pop)r;   r<   r%   rm   rn   ro   rp   r[   r_   ru   alternate_namesalternate_namealternate_moduler   r   r   _patch_module  s*   r~   c                 C   s$   |d u rt | g d S ||  d S r4   )_process_warningsr8   )rT   r%   r   r   r   rS     s   rS   c                 C   s&   dd l }| D ]
}|j|tdd qd S )Nr      )
stacklevel)warningsrV   r"   )r%   r   warningr   r   r   r     s   r   c                 C   s8   ddl m} tt| }t||stt| || d S d S )Nr   )FileObjectThread)gevent.fileobjectr   r:   rx   rB   rP   )r;   r   origr   r   r   _patch_sys_std  s
   

r   c                 C      dS )a  
    Patch sys.std[in,out,err] to use a cooperative IO via a
    threadpool.

    This is relatively dangerous and can have unintended consequences
    such as hanging the process or `misinterpreting control keys`_
    when :func:`input` and :func:`raw_input` are used. :func:`patch_all`
    does *not* call this function by default.

    This method does nothing on Python 3. The Python 3 interpreter
    wants to flush the TextIOWrapper objects that make up
    stderr/stdout at shutdown time, but using a threadpool at that
    time leads to a hang.

    .. _`misinterpreting control keys`: https://github.com/gevent/gevent/issues/274

    .. deprecated:: 23.7.0
       Does nothing on any supported version.
    Nr   )stdinstdoutstderrr   r   r   r     s   r   c                   C      t d dS )a^  
    Replace :func:`os.fork` with :func:`gevent.fork`, and, on POSIX,
    :func:`os.waitpid` with :func:`gevent.os.waitpid` (if the
    environment variable ``GEVENT_NOWAITPID`` is not defined). Does
    nothing if fork is not available.

    .. caution:: This method must be used with :func:`patch_signal` to have proper `SIGCHLD`
         handling and thus correct results from ``waitpid``.
         :func:`patch_all` calls both by default.

    .. caution:: For `SIGCHLD` handling to work correctly, the event loop must run.
         The easiest way to help ensure this is to use :func:`patch_all`.
    osNr~   r   r   r   r   r     s   r   c                  C   s*   ddl } d| jjv rtddgd dS dS )z
    On Python 3.7 and above, replace :class:`queue.SimpleQueue` (implemented
    in C) with its Python counterpart.

    .. versionadded:: 1.3.5
    r   NSimpleQueuequeuer<   )gevent.queuer   __all__r~   )rj   r   r   r   r     s   	r   c                   C   r   )z?
    Replace :func:`time.sleep` with :func:`gevent.sleep`.
    timeNr   r   r   r   r   r   ,  s   r   c                   C   r   )a5  
    Replaces the implementations of :mod:`contextvars` with
    :mod:`gevent.contextvars`.

    On Python 3.7 and above, this is a standard library module. On
    earlier versions, a backport that uses the same distribution name
    and import name is available on PyPI (though this is not
    recommended). If that is installed, it will be patched.

    .. versionchanged:: 20.04.0
       Clarify that the backport is also patched.

    .. versionchanged:: 20.9.0
       This now does nothing on Python 3.7 and above.
       gevent now depends on greenlet 0.4.17, which
       natively handles switching context vars when greenlets are switched.
       Older versions of Python that have the backport installed will
       still be patched.

    .. deprecated:: 23.7.0
       Does nothing on any supported version.
    Nr   r   r   r   r   patch_contextvars3  s   r   c                 C   s  t t|  dkrd S |  | _z|  }W n ty$   |  }Y nw t| 	 }zdd l
}W n tyB   G dd dt}Y nw |jj}td}| D ]5}t||rwdD ]}t||rnt||d urlt|||  nqXtdt|qOt||r|jd ur||_qOd S )N   r   c                   @   s   e Zd ZdS )z*_patch_existing_locks.<locals>._ModuleLockN)r   r   r    r   r   r   r   _ModuleLockc  s    r   gc)_owner_RLock__ownerzEUnsupported Python implementation; Found unknown lock implementation.)lenlist	enumerate_allocate_lock_active_limbo_lock	get_identr   
_get_identtypeRLockimportlib._bootstraprD   object
_bootstrapr   r9   get_objectsrB   hasattrr:   rL   AssertionErrorvarsowner)	threadingtid
rlock_type	importlibr   r   o
owner_namer   r   r   _patch_existing_locksN  sD   





r   c                    s  | rt d }ndd}d}td|dd\}}	| r{td|dd\}}
|r>ddlm} td| td	r>td	| |rDt |r{d
tj	v r{t d
}t|d
  |jD ] }t|rc| n|}|du rjqZt|dsutd| 
 |_qZ|rt d}ddlm} t|d| fdd}| rddlm} j D ]}|| krq||d|_qt d}tdd}j| kr|s |   _j_jdusJ  _j   fdd}td| j  j!}" _#|jv rj| jj!< |j!krj|= n|s6t$d|  fdd}td| ddl%m&} t'|(d||	 t'|(d| dS )aP  
    patch_thread(threading=True, _threading_local=True, Event=True, logging=True, existing_locks=True) -> None

    Replace the standard :mod:`thread` module to make it greenlet-based.

    :keyword bool threading: When True (the default),
        also patch :mod:`threading`.
    :keyword bool _threading_local: When True (the default),
        also patch :class:`_threading_local.local`.
    :keyword bool logging: When True (the default), also patch locks
        taken if the logging module has been configured.

    :keyword bool existing_locks: When True (the default), and the
        process is still single threaded, make sure that any
        :class:`threading.RLock` (and, under Python 3, :class:`importlib._bootstrap._ModuleLock`)
        instances that are currently locked can be properly unlocked. **Important**: This is a
        best-effort attempt and, on certain implementations, may not detect all
        locks. It is important to monkey-patch extremely early in the startup process.
        Setting this to False is not recommended, especially on Python 2.

    .. caution::
        Monkey-patching :mod:`thread` and using
        :class:`multiprocessing.Queue` or
        :class:`concurrent.futures.ProcessPoolExecutor` (which uses a
        ``Queue``) will hang the process.

        Monkey-patching with this function and using
        sub-interpreters (and advanced C-level API) and threads may be
        unstable on certain platforms.

    .. versionchanged:: 1.1b1
        Add *logging* and *existing_locks* params.
    .. versionchanged:: 1.3a2
        ``Event`` defaults to True.
    r   NthreadF)r%   ro   r   )Eventr   _Eventlogging_locklockzUnknown/unsupported handler %r_threading_local)localr   c                    s2   ddl m  ddlm d fdd	}|S )Nr   sleep)r   c                    sz   d }  u rtdd urjrd S  sd S | r" |  } r;|d ur1 |kr1d S  d  s&d S d S )NzCannot join current threadg{Gz?)current_threadRuntimeErrordeadis_alive)timeoutend)r   r   thread_greenletthreading_modr   r   r   join  s   
z2patch_thread.<locals>.make_join_func.<locals>.joinr4   )
gevent.hubr   r   )r   r   r   )r   )r   r   r   r   r   make_join_func   s    z$patch_thread.<locals>.make_join_func)main_native_threadgreenlet	_shutdownc                     s   j sd S j   ddlm}  z|   W n   ddlm} | j gt R   Y d_j	_ d _	  t
d d S )Nr   r   )get_hubFr   )_tstate_lockreleaserj   r   r   print_exceptionrx   exc_info_is_stopped__real_tstate_lockrP   )r   r   	_greenletmain_threadorig_shutdownr   r   r   r   H  s   

zpatch_thread.<locals>._shutdownz`Monkey-patching not on the main thread; threading.main_thread().join() will hang from a greenletc                      s       _  td d S )Nr   )r   _identrP   r   )r   r   r   r   r   r   ~  s   
rd   ))r9   r   r~   gevent.eventr   rP   r   r   rx   ry   r   _handlerListcallable	TypeErrorr   gevent.localr   gevent.threadingr   _activer>   r   r   r   r   
getcurrentr   r   r   Lockacquire	_danglingremoveidentr   r   rS   rj   re   r'   rl   )r   r   r   r   existing_locksr%   orig_current_threadgevent_threading_modgevent_thread_mod
thread_mod_wrhandlerr   r   r   r   r   already_patchedr   oldidre   r   r   r   r     s   E





&





r   c                 C   s\   ddl m} | r|j}n
t|jt|j }td|d |r*d|jvr,t|d dS dS dS )z
    Replace the standard socket object with gevent's cooperative
    sockets.

    :keyword bool dns: When true (the default), also patch address
        resolution functions in :mod:`socket`. See :doc:`/dns` for details.
    r   socketr   r   sslN)rj   r   rf   set__dns__r~   rR   )dns
aggressiver   r<   r   r   r   r     s   	
r   c                  C   s   ddl m}  td| jd dS )z
    Replace :doc:`DNS functions </dns>` in :mod:`socket` with
    cooperative versions.

    This is only useful if :func:`patch_socket` has been called and is
    done automatically by that method if requested.
    r   r   r   r   N)rj   r   r~   r   r   r   r   r   r     s   	r   r   c                 C   s   t d}t }t }dd }|| D ]9}t|tr8d|v r8|d |v r%q| D ]}|| u r6||| q)qt|trL| |jv rLd|j	vrL|| q||fS )Nr   c                 S   s   | d |  ddfS )Nr   __file__z	<unknown>)r7   )rH   r   r   r   report  s   z!_find_module_refs.<locals>.reportr   rs   )
r9   r   get_referrersrB   dictr>   addr   	__bases__r   )toexcluding_namesr   direct_ref_modulessubclass_modulesr   rvr   r   r   _find_module_refs  s"   
r  c           	      C   s   |odt jv ott jd d}td| d\}}|rKt|jdd\}}|s&|rMd }}|r5ddd	 |D  }|r@d
dd	 |D  }td| | |  dS dS dS )z
    patch_ssl() -> None

    Replace :class:`ssl.SSLSocket` object and socket wrapping functions in
    :mod:`ssl` with cooperative versions.

    This is only useful if :func:`patch_socket` has been called.
    r   
SSLContextrU   )r   z
gevent.sslzgevent._ssl3zgevent._sslgte279)r    z3Modules that had direct imports (NOT patched): %s. c                 S   s   g | ]
\}}d ||f qS )z%s (%s)r   ).0r;   fnamer   r   r   
<listcomp>  s    
zpatch_ssl.<locals>.<listcomp>zSubclasses (NOT patched): %s. c                 S   s   g | ]}t |qS r   )rC   )r  tr   r   r   r    s    a  Monkey-patching ssl after ssl has already been imported may lead to errors, including RecursionError on Python 3.6. It may also silently lead to incorrect behaviour on Python 3.7. Please monkey-patch earlier. See https://github.com/gevent/gevent/issues/1016. N)rx   ry   r   r~   r  orig_SSLContextrS   )	r%   _first_timemay_need_warning
gevent_modr   r   r   direct_ref_mod_strsubclass_strr   r   r   r     s>   
r   c                 C   s   t dd| id dS )a  
    Replace :func:`select.select` with :func:`gevent.select.select`
    and :func:`select.poll` with :class:`gevent.select.poll` (where available).

    If ``aggressive`` is true (the default), also remove other
    blocking functions from :mod:`select` .

    - :func:`select.epoll`
    - :func:`select.kqueue`
    - :func:`select.kevent`
    - :func:`select.devpoll` (Python 3.5+)
    selectr   rm   Nr   r   r   r   r   r	     s   
r	   c                 C   s6   zt d W n
 ty   Y dS w tdd| id dS )a  
    Replace :class:`selectors.DefaultSelector` with
    :class:`gevent.selectors.GeventSelector`.

    If ``aggressive`` is true (the default), also remove other
    blocking classes :mod:`selectors`:

    - :class:`selectors.EpollSelector`
    - :class:`selectors.KqueueSelector`
    - :class:`selectors.DevpollSelector` (Python 3.5+)

    On Python 2, the :mod:`selectors2` module is used instead
    of :mod:`selectors` if it is available. If this module cannot
    be imported, no patching is done and :mod:`gevent.selectors` is
    not available.

    In :func:`patch_all`, the *select* argument controls both this function
    and :func:`patch_select`.

    .. versionadded:: 20.6.0
    	selectorsNr   r  )rv   rD   r~   r  r   r   r   patch_selectors  s   
r  c                   C   r   )a=  
    Replace :func:`subprocess.call`, :func:`subprocess.check_call`,
    :func:`subprocess.check_output` and :class:`subprocess.Popen` with
    :mod:`cooperative versions <gevent.subprocess>`.

    .. note::
       On Windows under Python 3, the API support may not completely match
       the standard library.

    
subprocessNr   r   r   r   r   r   6  s   r   c                   C   r   )a  
    Make the builtin :func:`__import__` function `greenlet safe`_ under Python 2.

    .. note::
       This does nothing under Python 3 as it is not necessary. Python 3 features
       improved import locks that are per-module, not global.

    .. _greenlet safe: https://github.com/gevent/gevent/issues/108

    .. deprecated:: 23.7.0
       Does nothing on any supported platform.
    Nr   r   r   r   r   r   D  rZ   r   c                   C   r   )a  
    Make the :func:`signal.signal` function work with a :func:`monkey-patched os <patch_os>`.

    .. caution:: This method must be used with :func:`patch_os` to have proper ``SIGCHLD``
         handling. :func:`patch_all` calls both by default.

    .. caution:: For proper ``SIGCHLD`` handling, you must yield to the event loop.
         Using :func:`patch_all` is the easiest way to ensure this.

    .. seealso:: :mod:`gevent.signal`
    signalNr   r   r   r   r   r
   T  s   r
   c                  K   s   g }d}| d= t |i }| }|s|| krtd| i }|  D ]\}}||vr2| ||< ||< q!|r@|| s@d ||< ||< q!|||fS )N'_gevent_saved_patch_all_module_settingsr+   zUPatching more than once will result in the union of all True parameters being patchedT)r1   rK   rS   r<   )module_settingsr%   keycurrently_patched
first_timeto_patchkr   r   r   r   _check_repatchingd  s"   
r  c                 C   s0   |  dr|  ds| j}td| d S d S d S )Nr  r   zPatching signal but not os will result in SIGCHLD handlers installed after this not being called and os.waitpid may not function correctly if gevent.subprocess is used. This may raise an error in the future.)will_patch_moduler%   rS   )will_patch_allr   r   r   r   _subscribe_signal_os|  s   r  Fc                 K   sD  t d
i t \}}}|st| dS | D ]	\}}|t |< qddlm} zt|||| W n |jy=   Y dS w |rCt	  |rKt
|
|d |rPt  |rUt  | r]t||	d |rit|	d t|	d |rqt||d |rvt  |r{t  |rt  |rt  |rt  t|||| t|||| t| d	S )a  
    Do all of the default monkey patching (calls every other applicable
    function in this module).

    :return: A true value if patching all modules wasn't cancelled, a false
      value if it was.

    .. versionchanged:: 1.1
       Issue a :mod:`warning <warnings>` if this function is called multiple times
       with different arguments. The second and subsequent calls will only add more
       patches, they can never remove existing patches by setting an argument to ``False``.
    .. versionchanged:: 1.1
       Issue a :mod:`warning <warnings>` if this function is called with ``os=False``
       and ``signal=True``. This will cause SIGCHLD handlers to not be called. This may
       be an error in the future.
    .. versionchanged:: 1.3a2
       ``Event`` defaults to True.
    .. versionchanged:: 1.3b1
       Defined the return values.
    .. versionchanged:: 1.3b1
       Add ``**kwargs`` for the benefit of event subscribers. CAUTION: gevent may add
       and interpret additional arguments in the future, so it is suggested to use prefixes
       for kwarg values to be interpreted by plugins, for example, `patch_all(mylib_futures=True)`.
    .. versionchanged:: 1.3.5
       Add *queue*, defaulting to True, for Python 3.7.
    .. versionchanged:: 1.5
       Remove the ``httplib`` argument. Previously, setting it raised a ``ValueError``.
    .. versionchanged:: 1.5a3
       Add the ``contextvars`` argument.
    .. versionchanged:: 1.5
       Better handling of patching more than once.
    Nr   rd   F)r   r%   )r   r   r  )r%   r	  Tr   )r  localsr   r<   rj   re   r'   GeventWillPatchAllEventr)   r   r   r   r   r   r	   r  r   r   r   r
   r   r   !GeventDidPatchBuiltinModulesEventGeventDidPatchAllEvent)r   r   r   r  r   r   r   r  rx   r   r   builtinsr  r   contextvarsr+   r%   r  modules_to_patchr  r   re   r   r   r   r     sR   (

r   c                  C   s   i } t jdd  }d}d}t \}}}|ry|d dry|d dd  }|dkr-|d7 }n@|dkr4d	}n9|d
rJ|d
d|v rJd| |dd  < n#||v rbd| |< ||v ra|D ]}| |d qXnt |d d|   |d= |ry|d ds|rdd l}	dd l}
t	dd
dd |  D   t	dt j ddf  t	d|	t j  t	d|	tt j   t	d|
   |st	| d S |t jd d < ztj}W n ty   d}Y nw t jt t j|< dt jv rt j| t jd _tdi |  dd l}t||}|t jd ddS )Nr   Frun_pathr   z--   verboser   
run_modulezno-r  r   Tz

zCannot patch %rzgevent.monkey.patch_all(%s), c                 s       | ]}d | V  qdS )z%s=%sNr   )r  r?   r   r   r   	<genexpr>       zmain.<locals>.<genexpr>zsys.version=%s
 zsys.path=%szsys.modules=%szcwd=%szgevent.monkeyrj   __main__)run_namer   )rx   argv_get_script_help
startswithreplacerK   exitpprintr   printr   r<   versionstrippformatpathsortedry   keysgetcwd__spec__r;   	NameErrorr   monkeyr   runpyr:   )r*   r3  r)  run_fnscript_helppatch_all_argsry   optionr   r8  r   r2   rD  run_methr   r   r   r     s\   
 


r   c                  C   sh   dd l } z| j}W n ty   | j}Y nw |td }dd |D }dddd |D  }|||fS )Nr   c                 S   s   g | ]}d | t  v r|qS )patch_)globals)r  xr   r   r   r  2  s    z$_get_script_help.<locals>.<listcomp>a  gevent.monkey - monkey patch the standard modules to use gevent.

USAGE: ``python -m gevent.monkey [MONKEY OPTIONS] [--module] (script|module) [SCRIPT OPTIONS]``

If no MONKEY OPTIONS are present, monkey patches all the modules as if by calling ``patch_all()``.
You can exclude a module with --no-<module>, e.g. --no-thread. You can
specify a module to patch with --<module>, e.g. --socket. In the latter
case only the modules specified on the command line will be patched.

The default behavior is to execute the script passed as argument. If you wish
to run a module instead, pass the `--module` argument before the module name.

.. versionchanged:: 1.3b1
    The *script* argument can now be any argument that can be passed to `runpy.run_path`,
    just like the interpreter itself does, for example a package directory containing ``__main__.py``.
    Previously it had to be the path to
    a .py source file.

.. versionchanged:: 1.5
    The `--module` option has been added.

MONKEY OPTIONS: ``--verbose %s``r+  c                 s   r,  )z	--[no-]%sNr   )r  mr   r   r   r-  H  r.  z#_get_script_help.<locals>.<genexpr>)inspectgetfullargspecr   
getargspecr   r   )rN  getterrG  ry   rF  r   r   r   r4  *  s   


r4  r1  r4   )NNNTTT)TTT)TTTTTN)TT)r   )NT)T)TTTTTTTTFTTTTTT)7r!   
__future__r   r   rx   r   platformr5  WINr   r   RuntimeWarningr"   r'   r0   r1   r   r   r6   r@   r   r   rJ   rP   rR   r]   r^   r   rv   r~   rS   r   r   r   r   r   r   r   r   r   r   r   r  r   r	   r  r   r   r
   r  r  r   r   r4  r   r   r   r   r   <module>   s   y
#
L
'




;  


2


	
aD!

