monkey.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. # Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details.
  2. # pylint: disable=redefined-outer-name
  3. """
  4. Make the standard library cooperative.
  5. Patching
  6. ========
  7. The primary purpose of this module is to carefully patch, in place,
  8. portions of the standard library with gevent-friendly functions that
  9. behave in the same way as the original (at least as closely as possible).
  10. The primary interface to this is the :func:`patch_all` function, which
  11. performs all the available patches. It accepts arguments to limit the
  12. patching to certain modules, but most programs **should** use the
  13. default values as they receive the most wide-spread testing, and some monkey
  14. patches have dependencies on others.
  15. Patching **should be done as early as possible** in the lifecycle of the
  16. program. For example, the main module (the one that tests against
  17. ``__main__`` or is otherwise the first imported) should begin with
  18. this code, ideally before any other imports::
  19. from gevent import monkey
  20. monkey.patch_all()
  21. .. tip::
  22. Some frameworks, such as gunicorn, handle monkey-patching for you.
  23. Check their documentation to be sure.
  24. Querying
  25. --------
  26. Sometimes it is helpful to know if objects have been monkey-patched, and in
  27. advanced cases even to have access to the original standard library functions. This
  28. module provides functions for that purpose.
  29. - :func:`is_module_patched`
  30. - :func:`is_object_patched`
  31. - :func:`get_original`
  32. Use as a module
  33. ===============
  34. Sometimes it is useful to run existing python scripts or modules that
  35. were not built to be gevent aware under gevent. To do so, this module
  36. can be run as the main module, passing the script and its arguments.
  37. For details, see the :func:`main` function.
  38. Functions
  39. =========
  40. """
  41. from __future__ import absolute_import
  42. from __future__ import print_function
  43. import sys
  44. __all__ = [
  45. 'patch_all',
  46. 'patch_builtins',
  47. 'patch_dns',
  48. 'patch_os',
  49. 'patch_select',
  50. 'patch_signal',
  51. 'patch_socket',
  52. 'patch_ssl',
  53. 'patch_subprocess',
  54. 'patch_sys',
  55. 'patch_thread',
  56. 'patch_time',
  57. # query functions
  58. 'get_original',
  59. 'is_module_patched',
  60. 'is_object_patched',
  61. # module functions
  62. 'main',
  63. ]
  64. if sys.version_info[0] >= 3:
  65. string_types = (str,)
  66. PY3 = True
  67. else:
  68. import __builtin__ # pylint:disable=import-error
  69. string_types = (__builtin__.basestring,)
  70. PY3 = False
  71. WIN = sys.platform.startswith("win")
  72. # maps module name -> {attribute name: original item}
  73. # e.g. "time" -> {"sleep": built-in function sleep}
  74. saved = {}
  75. def is_module_patched(modname):
  76. """Check if a module has been replaced with a cooperative version."""
  77. return modname in saved
  78. def is_object_patched(modname, objname):
  79. """Check if an object in a module has been replaced with a cooperative version."""
  80. return is_module_patched(modname) and objname in saved[modname]
  81. def _get_original(name, items):
  82. d = saved.get(name, {})
  83. values = []
  84. module = None
  85. for item in items:
  86. if item in d:
  87. values.append(d[item])
  88. else:
  89. if module is None:
  90. module = __import__(name)
  91. values.append(getattr(module, item))
  92. return values
  93. def get_original(mod_name, item_name):
  94. """Retrieve the original object from a module.
  95. If the object has not been patched, then that object will still be retrieved.
  96. :param item_name: A string or sequence of strings naming the attribute(s) on the module
  97. ``mod_name`` to return.
  98. :return: The original value if a string was given for ``item_name`` or a sequence
  99. of original values if a sequence was passed.
  100. """
  101. if isinstance(item_name, string_types):
  102. return _get_original(mod_name, [item_name])[0]
  103. return _get_original(mod_name, item_name)
  104. _NONE = object()
  105. def patch_item(module, attr, newitem):
  106. olditem = getattr(module, attr, _NONE)
  107. if olditem is not _NONE:
  108. saved.setdefault(module.__name__, {}).setdefault(attr, olditem)
  109. setattr(module, attr, newitem)
  110. def remove_item(module, attr):
  111. olditem = getattr(module, attr, _NONE)
  112. if olditem is _NONE:
  113. return
  114. saved.setdefault(module.__name__, {}).setdefault(attr, olditem)
  115. delattr(module, attr)
  116. def patch_module(name, items=None):
  117. gevent_module = getattr(__import__('gevent.' + name), name)
  118. module_name = getattr(gevent_module, '__target__', name)
  119. module = __import__(module_name)
  120. if items is None:
  121. items = getattr(gevent_module, '__implements__', None)
  122. if items is None:
  123. raise AttributeError('%r does not have __implements__' % gevent_module)
  124. for attr in items:
  125. patch_item(module, attr, getattr(gevent_module, attr))
  126. return module
  127. def _queue_warning(message, _warnings):
  128. # Queues a warning to show after the monkey-patching process is all done.
  129. # Done this way to avoid extra imports during the process itself, just
  130. # in case. If we're calling a function one-off (unusual) go ahead and do it
  131. if _warnings is None:
  132. _process_warnings([message])
  133. else:
  134. _warnings.append(message)
  135. def _process_warnings(_warnings):
  136. import warnings
  137. for warning in _warnings:
  138. warnings.warn(warning, RuntimeWarning, stacklevel=3)
  139. def _patch_sys_std(name):
  140. from gevent.fileobject import FileObjectThread
  141. orig = getattr(sys, name)
  142. if not isinstance(orig, FileObjectThread):
  143. patch_item(sys, name, FileObjectThread(orig))
  144. def patch_sys(stdin=True, stdout=True, stderr=True):
  145. """Patch sys.std[in,out,err] to use a cooperative IO via a threadpool.
  146. This is relatively dangerous and can have unintended consequences such as hanging
  147. the process or `misinterpreting control keys`_ when ``input`` and ``raw_input``
  148. are used.
  149. This method does nothing on Python 3. The Python 3 interpreter wants to flush
  150. the TextIOWrapper objects that make up stderr/stdout at shutdown time, but
  151. using a threadpool at that time leads to a hang.
  152. .. _`misinterpreting control keys`: https://github.com/gevent/gevent/issues/274
  153. """
  154. # test__issue6.py demonstrates the hang if these lines are removed;
  155. # strangely enough that test passes even without monkey-patching sys
  156. if PY3:
  157. return
  158. if stdin:
  159. _patch_sys_std('stdin')
  160. if stdout:
  161. _patch_sys_std('stdout')
  162. if stderr:
  163. _patch_sys_std('stderr')
  164. def patch_os():
  165. """
  166. Replace :func:`os.fork` with :func:`gevent.fork`, and, on POSIX,
  167. :func:`os.waitpid` with :func:`gevent.os.waitpid` (if the
  168. environment variable ``GEVENT_NOWAITPID`` is not defined). Does
  169. nothing if fork is not available.
  170. .. caution:: This method must be used with :func:`patch_signal` to have proper SIGCHLD
  171. handling and thus correct results from ``waitpid``.
  172. :func:`patch_all` calls both by default.
  173. .. caution:: For SIGCHLD handling to work correctly, the event loop must run.
  174. The easiest way to help ensure this is to use :func:`patch_all`.
  175. """
  176. patch_module('os')
  177. def patch_time():
  178. """Replace :func:`time.sleep` with :func:`gevent.sleep`."""
  179. from gevent.hub import sleep
  180. import time
  181. patch_item(time, 'sleep', sleep)
  182. def _patch_existing_locks(threading):
  183. if len(list(threading.enumerate())) != 1:
  184. return
  185. try:
  186. tid = threading.get_ident()
  187. except AttributeError:
  188. tid = threading._get_ident()
  189. rlock_type = type(threading.RLock())
  190. try:
  191. import importlib._bootstrap
  192. except ImportError:
  193. class _ModuleLock(object):
  194. pass
  195. else:
  196. _ModuleLock = importlib._bootstrap._ModuleLock # python 2 pylint: disable=no-member
  197. # It might be possible to walk up all the existing stack frames to find
  198. # locked objects...at least if they use `with`. To be sure, we look at every object
  199. # Since we're supposed to be done very early in the process, there shouldn't be
  200. # too many.
  201. # By definition there's only one thread running, so the various
  202. # owner attributes were the old (native) thread id. Make it our
  203. # current greenlet id so that when it wants to unlock and compare
  204. # self.__owner with _get_ident(), they match.
  205. gc = __import__('gc')
  206. for o in gc.get_objects():
  207. if isinstance(o, rlock_type):
  208. if hasattr(o, '_owner'): # Py3
  209. if o._owner is not None:
  210. o._owner = tid
  211. else:
  212. if o._RLock__owner is not None:
  213. o._RLock__owner = tid
  214. elif isinstance(o, _ModuleLock):
  215. if o.owner is not None:
  216. o.owner = tid
  217. def patch_thread(threading=True, _threading_local=True, Event=False, logging=True,
  218. existing_locks=True,
  219. _warnings=None):
  220. """
  221. Replace the standard :mod:`thread` module to make it greenlet-based.
  222. - If *threading* is true (the default), also patch ``threading``.
  223. - If *_threading_local* is true (the default), also patch ``_threading_local.local``.
  224. - If *logging* is True (the default), also patch locks taken if the logging module has
  225. been configured.
  226. - If *existing_locks* is True (the default), and the process is still single threaded,
  227. make sure than any :class:`threading.RLock` (and, under Python 3, :class:`importlib._bootstrap._ModuleLock`)
  228. instances that are currently locked can be properly unlocked.
  229. .. caution::
  230. Monkey-patching :mod:`thread` and using
  231. :class:`multiprocessing.Queue` or
  232. :class:`concurrent.futures.ProcessPoolExecutor` (which uses a
  233. ``Queue``) will hang the process.
  234. .. versionchanged:: 1.1b1
  235. Add *logging* and *existing_locks* params.
  236. """
  237. # XXX: Simplify
  238. # pylint:disable=too-many-branches,too-many-locals
  239. # Description of the hang:
  240. # There is an incompatibility with patching 'thread' and the 'multiprocessing' module:
  241. # The problem is that multiprocessing.queues.Queue uses a half-duplex multiprocessing.Pipe,
  242. # which is implemented with os.pipe() and _multiprocessing.Connection. os.pipe isn't patched
  243. # by gevent, as it returns just a fileno. _multiprocessing.Connection is an internal implementation
  244. # class implemented in C, which exposes a 'poll(timeout)' method; under the covers, this issues a
  245. # (blocking) select() call: hence the need for a real thread. Except for that method, we could
  246. # almost replace Connection with gevent.fileobject.SocketAdapter, plus a trivial
  247. # patch to os.pipe (below). Sigh, so close. (With a little work, we could replicate that method)
  248. # import os
  249. # import fcntl
  250. # os_pipe = os.pipe
  251. # def _pipe():
  252. # r, w = os_pipe()
  253. # fcntl.fcntl(r, fcntl.F_SETFL, os.O_NONBLOCK)
  254. # fcntl.fcntl(w, fcntl.F_SETFL, os.O_NONBLOCK)
  255. # return r, w
  256. # os.pipe = _pipe
  257. # The 'threading' module copies some attributes from the
  258. # thread module the first time it is imported. If we patch 'thread'
  259. # before that happens, then we store the wrong values in 'saved',
  260. # So if we're going to patch threading, we either need to import it
  261. # before we patch thread, or manually clean up the attributes that
  262. # are in trouble. The latter is tricky because of the different names
  263. # on different versions.
  264. if threading:
  265. threading_mod = __import__('threading')
  266. # Capture the *real* current thread object before
  267. # we start returning DummyThread objects, for comparison
  268. # to the main thread.
  269. orig_current_thread = threading_mod.current_thread()
  270. else:
  271. threading_mod = None
  272. orig_current_thread = None
  273. patch_module('thread')
  274. if threading:
  275. patch_module('threading')
  276. if Event:
  277. from gevent.event import Event
  278. patch_item(threading_mod, 'Event', Event)
  279. if existing_locks:
  280. _patch_existing_locks(threading_mod)
  281. if logging and 'logging' in sys.modules:
  282. logging = __import__('logging')
  283. patch_item(logging, '_lock', threading_mod.RLock())
  284. for wr in logging._handlerList:
  285. # In py26, these are actual handlers, not weakrefs
  286. handler = wr() if callable(wr) else wr
  287. if handler is None:
  288. continue
  289. if not hasattr(handler, 'lock'):
  290. raise TypeError("Unknown/unsupported handler %r" % handler)
  291. handler.lock = threading_mod.RLock()
  292. if _threading_local:
  293. _threading_local = __import__('_threading_local')
  294. from gevent.local import local
  295. patch_item(_threading_local, 'local', local)
  296. def make_join_func(thread, thread_greenlet):
  297. from gevent.hub import sleep
  298. from time import time
  299. def join(timeout=None):
  300. end = None
  301. if threading_mod.current_thread() is thread:
  302. raise RuntimeError("Cannot join current thread")
  303. if thread_greenlet is not None and thread_greenlet.dead:
  304. return
  305. if not thread.is_alive():
  306. return
  307. if timeout:
  308. end = time() + timeout
  309. while thread.is_alive():
  310. if end is not None and time() > end:
  311. return
  312. sleep(0.01)
  313. return join
  314. if threading:
  315. from gevent.threading import main_native_thread
  316. for thread in threading_mod._active.values():
  317. if thread == main_native_thread():
  318. continue
  319. thread.join = make_join_func(thread, None)
  320. if sys.version_info[:2] >= (3, 4):
  321. # Issue 18808 changes the nature of Thread.join() to use
  322. # locks. This means that a greenlet spawned in the main thread
  323. # (which is already running) cannot wait for the main thread---it
  324. # hangs forever. We patch around this if possible. See also
  325. # gevent.threading.
  326. greenlet = __import__('greenlet')
  327. if orig_current_thread == threading_mod.main_thread():
  328. main_thread = threading_mod.main_thread()
  329. _greenlet = main_thread._greenlet = greenlet.getcurrent()
  330. main_thread.join = make_join_func(main_thread, _greenlet)
  331. # Patch up the ident of the main thread to match. This
  332. # matters if threading was imported before monkey-patching
  333. # thread
  334. oldid = main_thread.ident
  335. main_thread._ident = threading_mod.get_ident()
  336. if oldid in threading_mod._active:
  337. threading_mod._active[main_thread.ident] = threading_mod._active[oldid]
  338. if oldid != main_thread.ident:
  339. del threading_mod._active[oldid]
  340. else:
  341. _queue_warning("Monkey-patching not on the main thread; "
  342. "threading.main_thread().join() will hang from a greenlet",
  343. _warnings)
  344. def patch_socket(dns=True, aggressive=True):
  345. """Replace the standard socket object with gevent's cooperative sockets.
  346. If ``dns`` is true, also patch dns functions in :mod:`socket`.
  347. """
  348. from gevent import socket
  349. # Note: although it seems like it's not strictly necessary to monkey patch 'create_connection',
  350. # it's better to do it. If 'create_connection' was not monkey patched, but the rest of socket module
  351. # was, create_connection would still use "green" getaddrinfo and "green" socket.
  352. # However, because gevent.socket.socket.connect is a Python function, the exception raised by it causes
  353. # _socket object to be referenced by the frame, thus causing the next invocation of bind(source_address) to fail.
  354. if dns:
  355. items = socket.__implements__ # pylint:disable=no-member
  356. else:
  357. items = set(socket.__implements__) - set(socket.__dns__) # pylint:disable=no-member
  358. patch_module('socket', items=items)
  359. if aggressive:
  360. if 'ssl' not in socket.__implements__: # pylint:disable=no-member
  361. remove_item(socket, 'ssl')
  362. def patch_dns():
  363. """Replace DNS functions in :mod:`socket` with cooperative versions.
  364. This is only useful if :func:`patch_socket` has been called and is done automatically
  365. by that method if requested.
  366. """
  367. from gevent import socket
  368. patch_module('socket', items=socket.__dns__) # pylint:disable=no-member
  369. def patch_ssl():
  370. """Replace SSLSocket object and socket wrapping functions in :mod:`ssl` with cooperative versions.
  371. This is only useful if :func:`patch_socket` has been called.
  372. """
  373. patch_module('ssl')
  374. def patch_select(aggressive=True):
  375. """
  376. Replace :func:`select.select` with :func:`gevent.select.select`
  377. and :func:`select.poll` with :class:`gevent.select.poll` (where available).
  378. If ``aggressive`` is true (the default), also remove other
  379. blocking functions from :mod:`select` and (on Python 3.4 and
  380. above) :mod:`selectors`:
  381. - :func:`select.epoll`
  382. - :func:`select.kqueue`
  383. - :func:`select.kevent`
  384. - :func:`select.devpoll` (Python 3.5+)
  385. - :class:`selectors.EpollSelector`
  386. - :class:`selectors.KqueueSelector`
  387. - :class:`selectors.DevpollSelector` (Python 3.5+)
  388. """
  389. patch_module('select')
  390. if aggressive:
  391. select = __import__('select')
  392. # since these are blocking we're removing them here. This makes some other
  393. # modules (e.g. asyncore) non-blocking, as they use select that we provide
  394. # when none of these are available.
  395. remove_item(select, 'epoll')
  396. remove_item(select, 'kqueue')
  397. remove_item(select, 'kevent')
  398. remove_item(select, 'devpoll')
  399. if sys.version_info[:2] >= (3, 4):
  400. # Python 3 wants to use `select.select` as a member function,
  401. # leading to this error in selectors.py (because gevent.select.select is
  402. # not a builtin and doesn't get the magic auto-static that they do)
  403. # r, w, _ = self._select(self._readers, self._writers, [], timeout)
  404. # TypeError: select() takes from 3 to 4 positional arguments but 5 were given
  405. # Note that this obviously only happens if selectors was imported after we had patched
  406. # select; but there is a code path that leads to it being imported first (but now we've
  407. # patched select---so we can't compare them identically)
  408. select = __import__('select') # Should be gevent-patched now
  409. orig_select_select = get_original('select', 'select')
  410. assert select.select is not orig_select_select
  411. selectors = __import__('selectors')
  412. if selectors.SelectSelector._select in (select.select, orig_select_select):
  413. def _select(self, *args, **kwargs): # pylint:disable=unused-argument
  414. return select.select(*args, **kwargs)
  415. selectors.SelectSelector._select = _select
  416. _select._gevent_monkey = True
  417. if aggressive:
  418. # If `selectors` had already been imported before we removed
  419. # select.epoll|kqueue|devpoll, these may have been defined in terms
  420. # of those functions. They'll fail at runtime.
  421. remove_item(selectors, 'EpollSelector')
  422. remove_item(selectors, 'KqueueSelector')
  423. remove_item(selectors, 'DevpollSelector')
  424. selectors.DefaultSelector = selectors.SelectSelector
  425. def patch_subprocess():
  426. """
  427. Replace :func:`subprocess.call`, :func:`subprocess.check_call`,
  428. :func:`subprocess.check_output` and :class:`subprocess.Popen` with
  429. :mod:`cooperative versions <gevent.subprocess>`.
  430. .. note::
  431. On Windows under Python 3, the API support may not completely match
  432. the standard library.
  433. """
  434. patch_module('subprocess')
  435. def patch_builtins():
  436. """
  437. Make the builtin __import__ function `greenlet safe`_ under Python 2.
  438. .. note::
  439. This does nothing under Python 3 as it is not necessary. Python 3 features
  440. improved import locks that are per-module, not global.
  441. .. _greenlet safe: https://github.com/gevent/gevent/issues/108
  442. """
  443. if sys.version_info[:2] < (3, 3):
  444. patch_module('builtins')
  445. def patch_signal():
  446. """
  447. Make the signal.signal function work with a monkey-patched os.
  448. .. caution:: This method must be used with :func:`patch_os` to have proper SIGCHLD
  449. handling. :func:`patch_all` calls both by default.
  450. .. caution:: For proper SIGCHLD handling, you must yield to the event loop.
  451. Using :func:`patch_all` is the easiest way to ensure this.
  452. .. seealso:: :mod:`gevent.signal`
  453. """
  454. patch_module("signal")
  455. def _check_repatching(**module_settings):
  456. _warnings = []
  457. key = '_gevent_saved_patch_all'
  458. if saved.get(key, module_settings) != module_settings:
  459. _queue_warning("Patching more than once will result in the union of all True"
  460. " parameters being patched",
  461. _warnings)
  462. first_time = key not in saved
  463. saved[key] = module_settings
  464. return _warnings, first_time
  465. def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, httplib=False,
  466. subprocess=True, sys=False, aggressive=True, Event=False,
  467. builtins=True, signal=True):
  468. """
  469. Do all of the default monkey patching (calls every other applicable
  470. function in this module).
  471. .. versionchanged:: 1.1
  472. Issue a :mod:`warning <warnings>` if this function is called multiple times
  473. with different arguments. The second and subsequent calls will only add more
  474. patches, they can never remove existing patches by setting an argument to ``False``.
  475. .. versionchanged:: 1.1
  476. Issue a :mod:`warning <warnings>` if this function is called with ``os=False``
  477. and ``signal=True``. This will cause SIGCHLD handlers to not be called. This may
  478. be an error in the future.
  479. """
  480. # pylint:disable=too-many-locals,too-many-branches
  481. # Check to see if they're changing the patched list
  482. _warnings, first_time = _check_repatching(**locals())
  483. if not _warnings and not first_time:
  484. # Nothing to do, identical args to what we just
  485. # did
  486. return
  487. # order is important
  488. if os:
  489. patch_os()
  490. if time:
  491. patch_time()
  492. if thread:
  493. patch_thread(Event=Event, _warnings=_warnings)
  494. # sys must be patched after thread. in other cases threading._shutdown will be
  495. # initiated to _MainThread with real thread ident
  496. if sys:
  497. patch_sys()
  498. if socket:
  499. patch_socket(dns=dns, aggressive=aggressive)
  500. if select:
  501. patch_select(aggressive=aggressive)
  502. if ssl:
  503. patch_ssl()
  504. if httplib:
  505. raise ValueError('gevent.httplib is no longer provided, httplib must be False')
  506. if subprocess:
  507. patch_subprocess()
  508. if builtins:
  509. patch_builtins()
  510. if signal:
  511. if not os:
  512. _queue_warning('Patching signal but not os will result in SIGCHLD handlers'
  513. ' installed after this not being called and os.waitpid may not'
  514. ' function correctly if gevent.subprocess is used. This may raise an'
  515. ' error in the future.',
  516. _warnings)
  517. patch_signal()
  518. _process_warnings(_warnings)
  519. def main():
  520. args = {}
  521. argv = sys.argv[1:]
  522. verbose = False
  523. script_help, patch_all_args, modules = _get_script_help()
  524. while argv and argv[0].startswith('--'):
  525. option = argv[0][2:]
  526. if option == 'verbose':
  527. verbose = True
  528. elif option.startswith('no-') and option.replace('no-', '') in patch_all_args:
  529. args[option[3:]] = False
  530. elif option in patch_all_args:
  531. args[option] = True
  532. if option in modules:
  533. for module in modules:
  534. args.setdefault(module, False)
  535. else:
  536. sys.exit(script_help + '\n\n' + 'Cannot patch %r' % option)
  537. del argv[0]
  538. # TODO: break on --
  539. if verbose:
  540. import pprint
  541. import os
  542. print('gevent.monkey.patch_all(%s)' % ', '.join('%s=%s' % item for item in args.items()))
  543. print('sys.version=%s' % (sys.version.strip().replace('\n', ' '), ))
  544. print('sys.path=%s' % pprint.pformat(sys.path))
  545. print('sys.modules=%s' % pprint.pformat(sorted(sys.modules.keys())))
  546. print('cwd=%s' % os.getcwd())
  547. patch_all(**args)
  548. if argv:
  549. sys.argv = argv
  550. __package__ = None
  551. assert __package__ is None
  552. globals()['__file__'] = sys.argv[0] # issue #302
  553. globals()['__package__'] = None # issue #975: make script be its own package
  554. with open(sys.argv[0]) as f:
  555. # Be sure to exec in globals to avoid import pollution. Also #975.
  556. exec(f.read(), globals())
  557. else:
  558. print(script_help)
  559. def _get_script_help():
  560. from inspect import getargspec
  561. patch_all_args = getargspec(patch_all)[0] # pylint:disable=deprecated-method
  562. modules = [x for x in patch_all_args if 'patch_' + x in globals()]
  563. script_help = """gevent.monkey - monkey patch the standard modules to use gevent.
  564. USAGE: python -m gevent.monkey [MONKEY OPTIONS] script [SCRIPT OPTIONS]
  565. If no OPTIONS present, monkey patches all the modules it can patch.
  566. You can exclude a module with --no-module, e.g. --no-thread. You can
  567. specify a module to patch with --module, e.g. --socket. In the latter
  568. case only the modules specified on the command line will be patched.
  569. MONKEY OPTIONS: --verbose %s""" % ', '.join('--[no-]%s' % m for m in modules)
  570. return script_help, patch_all_args, modules
  571. main.__doc__ = _get_script_help()[0]
  572. if __name__ == '__main__':
  573. main()