# Always monkey-patch as the very first thing
from gevent import monkey; monkey.patch_all()

# If we're running from a subdirectory of the code (in source mode, not egg),
# change dir to the root directory for easier debugging and unit test launching.
import os
cwd, path = os.getcwd(), os.path.realpath(__file__)
base_path = os.path.dirname(path)
if '.egg' not in cwd:
    while not os.path.exists('.anode_root_marker'):
        os.chdir('..')


@@ -42,53 +42,1116 @@
 hing
-%0Afrom gevent import monkey; monkey.patch_all(
+.%0A%0A# Make monkey-patching work with debuggers by detecting already-imported modules%0A# TODO: Move this into a module that third parties can use%0A# TODO: Confirm that monkey-patched thread-local storage still works%0Aimport sys%0Aif 'pydevd' in sys.modules:%0A    # The order matters%0A    monkey_list = %5B'os', 'time', 'thread', 'socket', 'select', 'ssl', 'httplib'%5D%0A    for monkey in monkey_list:%0A        if monkey in sys.modules:%0A            mod = sys.modules%5Bmonkey%5D%0A%0A            # Reload so the non-monkeypatched versions in the debugger don't get patched%0A            #reload(mod)%0A            del sys.modules%5Bmonkey%5D%0A%0A    %0A    unmonkey = %7B'threading': %5B'_allocate_lock', '_get_ident'%5D%7D%0A    unmonkey_backup = %7B%7D%0A    for modname,feats in unmonkey.iteritems():%0A        mod = __import__(modname)%0A        unmonkey_backup%5Bmodname%5D = dict((feat, getattr(mod, feat)) for feat in feats)%0A%0A    from gevent import monkey; monkey.patch_all()%0A    %0A    for modname,feats_backup in unmonkey_backup.iteritems():%0A        mod = __import__(modname)%0A        for name,impl in feats_backup.iteritems():%0A            setattr(mod, name, impl
 )%0A%0A#

support for debuggers!!