Esempio n. 1
0
 def __import_asciidoc(self, reload=False):
     '''
     Import asciidoc module (script or compiled .pyc).
     See
     http://groups.google.com/group/asciidoc/browse_frm/thread/66e7b59d12cd2f91
     for an explanation of why a seemingly straight-forward job turned out
     quite complicated.
     '''
     if os.path.splitext(self.cmd)[1] in ['.py', '.pyc']:
         sys.path.insert(0, os.path.dirname(self.cmd))
         try:
             try:
                 if reload:
                     import __builtin__  # Because reload() is shadowed.
                     __builtin__.reload(self.asciidoc)
                 else:
                     import asciidoc
                     self.asciidoc = asciidoc
             except ImportError:
                 raise AsciiDocError('failed to import ' + self.cmd)
         finally:
             del sys.path[0]
     else:
         # The import statement can only handle .py or .pyc files, have to
         # use imp.load_source() for scripts with other names.
         try:
             imp.load_source('asciidoc', self.cmd)
             import asciidoc
             self.asciidoc = asciidoc
         except ImportError:
             raise AsciiDocError('failed to import ' + self.cmd)
     if Version(self.asciidoc.VERSION) < Version(MIN_ASCIIDOC_VERSION):
         raise AsciiDocError(
             'asciidocapi %s requires asciidoc %s or better' %
             (API_VERSION, MIN_ASCIIDOC_VERSION))
Esempio n. 2
0
 def __import_asciidoc(self, reload=False):
     '''
     Import asciidoc module (script or compiled .pyc).
     See
     http://groups.google.com/group/asciidoc/browse_frm/thread/66e7b59d12cd2f91
     for an explanation of why a seemingly straight-forward job turned out
     quite complicated.
     '''
     if os.path.splitext(self.cmd)[1] in ['.py','.pyc']:
         sys.path.insert(0, os.path.dirname(self.cmd))
         try:
             try:
                 if reload:
                     import __builtin__  # Because reload() is shadowed.
                     __builtin__.reload(self.asciidoc)
                 else:
                     import asciidoc
                     self.asciidoc = asciidoc
             except ImportError:
                 raise AsciiDocError('failed to import ' + self.cmd)
         finally:
             del sys.path[0]
     else:
         # The import statement can only handle .py or .pyc files, have to
         # use imp.load_source() for scripts with other names.
         try:
             imp.load_source('asciidoc', self.cmd)
             import asciidoc
             self.asciidoc = asciidoc
         except ImportError:
             raise AsciiDocError('failed to import ' + self.cmd)
     if Version(self.asciidoc.VERSION) < Version(MIN_ASCIIDOC_VERSION):
         raise AsciiDocError(
             'asciidocapi %s requires asciidoc %s or better'
             % (API_VERSION, MIN_ASCIIDOC_VERSION))
Esempio n. 3
0
def reload(module, _time=None):
    '''reload(module)

    Reload the given module, allowing it to retain state across the reload.

    This is effectively a drop-in replacement for the built-in ``reload``
    function, except it plays well with :func:`autoreload`.

    If there is a ``__before_reload__`` function in the module, it will be
    called before reload.

    If there is a ``__after_reload__`` function, it will be called after
    the reload, and it will receive the return value from ``__before_reload__``.

    '''

    print '# autoreload: Reloading: %s at 0x%x' % (module.__name__, id(module))
        
    state = None
    if hasattr(module, '__before_reload__'):
        state = module.__before_reload__()
        
    __builtin__.reload(module)
    
    # Wipe the dependency cache.
    _dependency_lists.pop(module.__name__, None)

    # Remember when it was reloaded.
    _reload_times[module.__name__] = _time or time.time()()
    if _VERBOSE:
        print '\n'.join('%s: %s' % (t, n) for n, t in sorted(_reload_times.iteritems()))

    if hasattr(module, '__after_reload__'):
        module.__after_reload__(state)
Esempio n. 4
0
def reload(module, _time=None):
    '''reload(module)

    Reload the given module, allowing it to retain state across the reload.

    This is effectively a drop-in replacement for the built-in ``reload``
    function, except it plays well with :func:`autoreload`.

    If there is a ``__before_reload__`` function in the module, it will be
    called before reload.

    If there is a ``__after_reload__`` function, it will be called after
    the reload, and it will receive the return value from ``__before_reload__``.

    '''

    print '# autoreload: Reloading: %s at 0x%x' % (module.__name__, id(module))

    state = None
    if hasattr(module, '__before_reload__'):
        state = module.__before_reload__()

    __builtin__.reload(module)

    # Wipe the dependency cache.
    _dependency_lists.pop(module.__name__, None)

    # Remember when it was reloaded.
    _reload_times[module.__name__] = _time or time.time()()
    if _VERBOSE > 1:
        print '\n'.join('%s: %s' % (t, n)
                        for n, t in sorted(_reload_times.iteritems()))

    if hasattr(module, '__after_reload__'):
        module.__after_reload__(state)
Esempio n. 5
0
def reload_pipeline():
    """Attempt to reload pipeline at run-time.

    CAUTION: This is primarily for development and debugging purposes.

    """

    api.uninstall()
    _uninstall_menu()

    for module in ("avalon.api",
                   "avalon.io",
                   "avalon.lib",
                   "avalon.pipeline",
                   "avalon.tools",
                   "avalon.nuke",
                   "avalon.nuke.pipeline",
                   "avalon.nuke.lib",
                   "avalon.nuke.workio"
                   ):

        log.info("Reloading module: {}...".format(module))

        module = importlib.import_module(module)
        reload(module)

    import avalon.nuke
    api.install(avalon.nuke)

    _register_events()
Esempio n. 6
0
def reload():
    modNames = (reload.__module__,)
    from sys import modules
    import __builtin__
    for m in modNames:
        __builtin__.reload(modules[m])

    print 'vehicle_extras reloaded'
Esempio n. 7
0
def reload_module(s,
                  modname=Interact(prompt="Reload module",
                                   default='',
                                   completer=make_completer(lambda x:[m
                                                                      for m in sys.modules
                                                                      if m.startswith(x)]),
                                   converter=str)):
    log.debug("reload %s", modname)
    log.debug("sys.m0dules:%s", sys.modules.keys())
    __builtin__.reload(sys.modules[modname])
    log.debug("done reload %s", modname)
Esempio n. 8
0
def reload(module, debug=False, lists=False, dicts=False):
    """Replacement for the builtin reload function:
    - Reloads the module as usual
    - Updates all old functions and class methods to use the new code
    - Updates all instances of each modified class to use the new class
    - Can update lists and dicts, but this is disabled by default
    - Requires that class and function names have not changed
    """
    if debug:
        print("Reloading %s" % str(module))

    ## make a copy of the old module dictionary, reload, then grab the new module dictionary for comparison
    oldDict = module.__dict__.copy()
    builtins.reload(module)
    newDict = module.__dict__

    ## Allow modules access to the old dictionary after they reload
    if hasattr(module, '__reload__'):
        module.__reload__(oldDict)

    ## compare old and new elements from each dict; update where appropriate
    for k in oldDict:
        old = oldDict[k]
        new = newDict.get(k, None)
        if old is new or new is None:
            continue

        if inspect.isclass(old):
            if debug:
                print("  Updating class %s.%s (0x%x -> 0x%x)" %
                      (module.__name__, k, id(old), id(new)))
            updateClass(old, new, debug)
            # don't put this inside updateClass because it is reentrant.
            new.__previous_reload_version__ = old

        elif inspect.isfunction(old):
            depth = updateFunction(old, new, debug)
            if debug:
                extra = ""
                if depth > 0:
                    extra = " (and %d previous versions)" % depth
                print("  Updating function %s.%s%s" %
                      (module.__name__, k, extra))
        elif lists and isinstance(old, list):
            l = old.len()
            old.extend(new)
            for i in range(l):
                old.pop(0)
        elif dicts and isinstance(old, dict):
            old.update(new)
            for k in old:
                if k not in new:
                    del old[k]
Esempio n. 9
0
def reload(module, debug=False, lists=False, dicts=False):
    """Replacement for the builtin reload function:
    - Reloads the module as usual
    - Updates all old functions and class methods to use the new code
    - Updates all instances of each modified class to use the new class
    - Can update lists and dicts, but this is disabled by default
    - Requires that class and function names have not changed
    """
    if debug:
        print("Reloading %s" % str(module))
        
    ## make a copy of the old module dictionary, reload, then grab the new module dictionary for comparison
    oldDict = module.__dict__.copy()
    builtins.reload(module)
    newDict = module.__dict__
    
    ## Allow modules access to the old dictionary after they reload
    if hasattr(module, '__reload__'):
        module.__reload__(oldDict)
    
    ## compare old and new elements from each dict; update where appropriate
    for k in oldDict:
        old = oldDict[k]
        new = newDict.get(k, None)
        if old is new or new is None:
            continue
        
        if inspect.isclass(old):
            if debug:
                print("  Updating class %s.%s (0x%x -> 0x%x)" % (module.__name__, k, id(old), id(new)))
            updateClass(old, new, debug)
                    
        elif inspect.isfunction(old):
            depth = updateFunction(old, new, debug)
            if debug:
                extra = ""
                if depth > 0:
                    extra = " (and %d previous versions)" % depth
                print("  Updating function %s.%s%s" % (module.__name__, k, extra))
        elif lists and isinstance(old, list):
            l = old.len()
            old.extend(new)
            for i in range(l):
                old.pop(0)
        elif dicts and isinstance(old, dict):
            old.update(new)
            for k in old:
                if k not in new:
                    del old[k]
Esempio n. 10
0
def reload():
    """ 
    Reload the essential parts of the webPageGenerator module
    """
    __builtin__.reload(bottle)
    bottle.TEMPLATE_PATH.append(os.path.join(REPO_DIR, 'wsgi', 'views'))
    __builtin__.reload(elesWeb)
    __builtin__.reload(hotCarsWeb)
    __builtin__.reload(hotCars)
Esempio n. 11
0
def _get_module(server, request):

    # Interpret the command + parameters.
    cmd = request.getCmd()
    logger.info("Received command: %s", cmd)

    # Special handling for certain commands
    # TODO: these should certainly disappear at some point
    if cmd == 'robots.txt':
        cmd = 'robots'
    if cmd == 'favicon.ico':
        cmd = 'favicon'
    if cmd == "ngamsInternal.dtd":
        request.setCmd('RETRIEVE').addHttpPar("internal", cmd)
        cmd = 'RETRIEVE'

    # Is it a built-in or a plug-in?
    if cmd in _builtin_cmds:
        modname = __package__ + '.commands.' + cmd.lower()
    elif cmd in server.cfg.cmd_plugins:
        modname = server.cfg.cmd_plugins[cmd]
    else:
        modname = 'ngamsPlugIns.ngamsCmd_%s' % cmd

    # Reload the module if requested.
    reload_mod = 'reload' in request and int(request['reload']) == 1

    # Need to acquire the importing lock if we want to check the sys.modules
    # dictionary to short-cut the call to importlib.import_module. This is
    # because the modules are put into sys.modules by the import machinery
    # *before* they are fully loaded (probably to detect circular dependencies)
    # For details on a similar issue found in the pickle module see
    # https://bugs.python.org/issue12680
    #
    # In python 3.3+ this shoudn't be necessary anymore, as the locking scheme
    # has been changed to per-module locks. This function has been marked as
    # deprecated, and therefore we probably don't need it anymore
    imp.acquire_lock()
    try:
        mod = sys.modules.get(modname, None)
        if mod is None:
            logger.debug("Importing dynamic command module: %s", modname)
            try:
                mod = importlib.import_module(modname)
            except ImportError:
                logger.error("No module %s found", modname)
                raise NoSuchCommand()
            except:
                logger.exception("Error while importing %s", modname)
                raise
        elif reload_mod:
            logger.debug("Re-loading dynamic command module: %s", modname)
            mod = reload(mod)
        return mod
    finally:
        imp.release_lock()


# EOF
Esempio n. 12
0
def test_with_reload():
    pyximport._test_files = []
    tempdir = make_tempdir()
    sys.path.append(tempdir)
    filename = os.path.join(tempdir, "dummy.pyx")
    with open(filename, "w") as fid:
        fid.write("print 'Hello world from the Pyrex install hook'")
    import dummy
    reload(dummy)

    depend_filename = os.path.join(tempdir, "dummy.pyxdep")
    with open(depend_filename, "w") as depend_file:
        depend_file.write("*.txt\nfoo.bar")

    build_filename = os.path.join(tempdir, "dummy.pyxbld")
    with open(build_filename, "w") as build_file:
        build_file.write("""
from distutils.extension import Extension
def make_ext(name, filename):
    return Extension(name=name, sources=[filename])
""")

    with open(os.path.join(tempdir, "foo.bar"), "w") as fid:
        fid.write(" ")
    with open(os.path.join(tempdir, "1.txt"), "w") as fid:
        fid.write(" ")
    with open(os.path.join(tempdir, "abc.txt"), "w") as fid:
        fid.write(" ")
    reload(dummy)
    assert len(pyximport._test_files) == 1, pyximport._test_files
    reload(dummy)

    time.sleep(1)  # sleep a second to get safer mtimes
    with open(os.path.join(tempdir, "abc.txt"), "w") as fid:
        fid.write(" ")
    print("Here goes the reload")
    reload(dummy)
    assert len(pyximport._test_files) == 1, pyximport._test_files

    reload(dummy)
    assert len(pyximport._test_files) == 0, pyximport._test_files
    remove_tempdir(tempdir)
Esempio n. 13
0
def test_with_reload():
    pyximport._test_files = []
    tempdir = make_tempdir()
    sys.path.append(tempdir)
    filename = os.path.join(tempdir, "dummy.pyx")
    open(filename, "w").write("print 'Hello world from the Pyrex install hook'")
    import dummy
    reload(dummy)

    depend_filename = os.path.join(tempdir, "dummy.pyxdep")
    depend_file = open(depend_filename, "w")
    depend_file.write("*.txt\nfoo.bar")
    depend_file.close()

    build_filename = os.path.join(tempdir, "dummy.pyxbld")
    build_file = open(build_filename, "w")
    build_file.write("""
from distutils.extension import Extension
def make_ext(name, filename):
    return Extension(name=name, sources=[filename])
""")
    build_file.close()

    open(os.path.join(tempdir, "foo.bar"), "w").write(" ")
    open(os.path.join(tempdir, "1.txt"), "w").write(" ")
    open(os.path.join(tempdir, "abc.txt"), "w").write(" ")
    reload(dummy)
    assert len(pyximport._test_files)==1, pyximport._test_files
    reload(dummy)

    time.sleep(1) # sleep a second to get safer mtimes
    open(os.path.join(tempdir, "abc.txt"), "w").write(" ")
    print("Here goes the reolad")
    reload(dummy)
    assert len(pyximport._test_files) == 1, pyximport._test_files

    reload(dummy)
    assert len(pyximport._test_files) == 0, pyximport._test_files
    remove_tempdir(tempdir)
Esempio n. 14
0
def _get_module(server, request):

    # Interpret the command + parameters.
    cmd = request.getCmd()
    logger.info("Received command: %s", cmd)

    # Special handling for certain commands
    # TODO: these should certainly disappear at some point
    if cmd == 'robots.txt':
        cmd = 'robots'
    if cmd == 'favicon.ico':
        cmd = 'favicon'
    if cmd == "ngamsInternal.dtd":
        request.setCmd('RETRIEVE').addHttpPar("internal", cmd)
        cmd = 'RETRIEVE'

    # Is it a built-in or a plug-in?
    if cmd in _builtin_cmds:
        modname = __package__ + '.commands.' + cmd.lower()
    elif cmd in server.cfg.cmd_plugins:
        modname = server.cfg.cmd_plugins[cmd]
    else:
        modname = 'ngamsPlugIns.ngamsCmd_%s' % cmd

    # Reload the module if requested.
    reload_mod = 'reload' in request and int(request['reload']) == 1

    # We previously checked sys.modules before doing import_module, but that's
    # unnecessary, and moreover thread-usafe, since modules are put in sys.modules
    # before they are fully built (leading to errors like "module 'ngamsServer.commands.qarchive'
    # has no attribute 'handleCmd'", which it definitly has)
    logger.debug("Importing dynamic command module: %s", modname)
    try:
        mod = importlib.import_module(modname)
    except ImportError:
        logger.error("No module %s found", modname)
        raise NoSuchCommand()
    except:
        logger.exception("Error while importing %s", modname)
        raise
    if reload_mod:
        logger.debug("Re-loading dynamic command module: %s", modname)
        mod = reload(mod)
    return mod


# EOF
Esempio n. 15
0
#!/usr/b in/env pytho n
#-*- coding: UTF-8 -*-
''' 
AN24    00:80:98:0E:39:77
pc      00:22:68:E2:18:6F
desktop 00:1f:81:00:08:30
 '''

import bluetooth
from bluetooth import *
import sys
from __builtin__ import reload
import types
reload(sys)
#sys.setdefaultencoding('utf-8')
print '[ok] set default coding:', sys.getdefaultencoding()
#apply to connect

bd_addr = "00:80:98:0E:39:77"

port = 1

sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
print '[OK] connecting '
sock.send("\x10\x02G\x10\x03\x42\xbc")
print '[OK] sending connection request '
print 'waiting reply...'
'''
#waiting receive
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
Esempio n. 16
0
def reload():
    import __builtin__, sys
    __builtin__.reload(sys.modules[__name__])
Esempio n. 17
0
# jhbuild - a tool to ease building collections of source packages
# Copyright (C) 2001-2006  James Henstridge
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# We used to import pygtk which sets things to utf-8 and masks ascii encoding errors.
# It's usually what we want, and there are not many downsides, so replicate it here.
import sys
if sys.version_info[0] == 2:
    import __builtin__
    __builtin__.reload(sys)
    sys.setdefaultencoding("utf-8")

from jhbuild import monkeypatch
del monkeypatch
Esempio n. 18
0
def reload(context):
    for module in sys.modules.values():
        if module:
            __builtin__.reload(module)
Esempio n. 19
0
# endregion

# region aspects

'''
    The function "__get_all_modules__()" has to be defined before importing \
    any modules from this package.
'''
if __name__ != '__main__':
    from boostnode.aspect.signature import add_check as add_signature_check
    from boostnode.extension.native import Module

# # python3.5
# #     pass
    builtins.reload(sys)
    sys.setdefaultencoding(ENCODING)
# #
    try:
        '''
            Add signature checking for all functions and methods with joint \
            points in this package.
        '''
        add_signature_check(point_cut='%s\..*' % Module.get_package_name(
            frame=inspect.currentframe()))
    except WindowsError as exception:
# # python3.5
# #         logging.error(
# #             'Running subprocesses on windows without being administrator '
# #             "isn't possible. %s: %s", exception.__class__.__name__,
# #             builtins.str(exception))
Esempio n. 20
0
#!/usr/b in/env pytho n
# -*- coding: UTF-8 -*-
""" 
AN24    00:80:98:0E:39:77
pc      00:22:68:E2:18:6F
desktop 00:1f:81:00:08:30
 """

import bluetooth
from bluetooth import *
import sys
from __builtin__ import reload
import types

reload(sys)
# sys.setdefaultencoding('utf-8')
print "[ok] set default coding:", sys.getdefaultencoding()
# apply to connect

bd_addr = "00:80:98:0E:39:77"

port = 1

sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr, port))
print "[OK] connecting "
sock.send("\x10\x02G\x10\x03\x42\xbc")
print "[OK] sending connection request "
print "waiting reply..."
"""
#waiting receive
Esempio n. 21
0
def reload():
    import __builtin__
    from sys import modules
    __builtin__.reload(modules[reload.__module__])
Esempio n. 22
0
def reload():
    import __builtin__
    from sys import modules
    __builtin__.reload(modules[reload.__module__])
Esempio n. 23
0
from __builtin__ import reload

import maya.cmds as mc
from angela.rig import eyelid as el
import ADCtrl as ct, ADUtils as au

reload(el)
reload(ct)
reload(au)

class Eyelid:
    def __init__(self, crvUp,
                 crvDown,
                 offsetEyelidPos,
                 eyeballJnt,
                 prefixEyeball,
                 prefixEyeballAim,
                 scale,
                 side,
                 sideLFT,
                 sideRGT,
                 directionLid01,
                 directionLid02,
                 positionEyeAimCtrl,
                 eyeballAimMainCtrl,
                 headUpCtrl,
                 pupilJnt, irisJnt, prefixPupil, prefixIris,
                 eyeballSpecJnt, prefixEyeballSpec,
                 ctrlGrp, eyeballSpecTipJnt, mainJointGrp,
                 faceCtrlGrp
                 ):
Esempio n. 24
0
def reloadPythonCode(context):
    for module in sys.modules.values():
        if module:
            __builtin__.reload(module)
Esempio n. 25
0
def reload():
    import __builtin__, sys
    __builtin__.reload(sys.modules[__name__])