def nexec(statement, globals=None, locals=None, **kwargs): """Execute *statement* using *globals* and *locals* dictionaries as *global* and *local* namespace. *statement* is transformed using :class:`.NapiTransformer`.""" try: import __builtin__ as builtins except ImportError: import builtins from ast import parse from napi.transformers import NapiTransformer from ast import fix_missing_locations as fml try: node = parse(statement, '<string>', 'exec') except ImportError:#KeyError: exec(statement) else: if globals is None: globals = builtins.globals() if locals is None: locals = {} trans = NapiTransformer(globals=globals, locals=locals, **kwargs) trans.visit(node) code = compile(fml(node), '<string>', 'exec') return builtins.eval(code, globals, locals)
def createInstance(self, module, type, **kargs): for package in reversed(self.packages.keys()): try: imported = __import__(self.packages[package].module+"."+module, __builtin__.globals(), __builtin__.locals(), [type]) instance = getattr(imported, type) except ImportError as importError: self.spam("Importing type "+type+" from "+ self.packages[package].module+"."+module+" failed: "+ str(importError)) self.spam(traceback.format_exc()) except AttributeError as attributeError: self.spam("Importing type "+type+" from "+ self.packages[package].module+"."+module+" failed: "+ str(attributeError)) self.spam(traceback.format_exc()) else: self.spam("Importing type "+type+" from "+ self.packages[package].module+"."+module+" succeeded") return instance(**kargs) error = "Failed to import "+type+" from module "+module+"." if self.debug: error = error+" See debugging output for details." else: error = error+" Enable debugging output for details." self.error(error)
def neval(expression, globals=None, locals=None, **kwargs): """Evaluate *expression* using *globals* and *locals* dictionaries as *global* and *local* namespace. *expression* is transformed using :class:`.NapiTransformer`.""" try: import __builtin__ as builtins except ImportError: import builtins from ast import parse from ast import fix_missing_locations as fml try: transformer = kwargs['transformer'] except KeyError: from napi.transformers import NapiTransformer as transformer #try: node = parse(expression, '<string>', 'eval') #except ImportError: # builtins.eval(expression) #else: if globals is None: globals = builtins.globals() if locals is None: locals = {} trans = transformer(globals=globals, locals=locals, **kwargs) trans.visit(node) code = compile(fml(node), '<string>', 'eval') return builtins.eval(code, globals, locals)
def clone_function(func, globals=None): """ Clone a function object by creating a new FunctionType with a cloned code object. """ from types import CodeType, FunctionType co = func.func_code code = CodeType( co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, co.co_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab ) import __builtin__ if globals is None: globals = __builtin__.globals() return FunctionType(code, globals, func.func_name, func.func_defaults)
def include(self, package, **kargs): package = package.replace("-", "_") if package in self.packages.keys(): return self.info("Including package: "+package) try: self.packages[package] = Package(package, **kargs) except Exception as includeError: self.error("Failed to include package "+package+": "+str(includeError)) if self.packages[package].requires: for required in self.packages[package].requires: self.include(required) packageModule = __import__(self.packages[package].module) packagePath = os.path.dirname(packageModule.__file__) modules = [name for _, name, _ in pkgutil.iter_modules([packagePath])] if "facade" in modules: facade = __import__(self.packages[package].module+".facade", __builtin__.globals(), __builtin__.locals(), ["*"]) for expression in dir(facade): if not __builtin__.__dict__.has_key(expression): __builtin__.__dict__[expression] = getattr(facade, expression)
def __init__(self, locals = __builtin__.globals()): InteractiveConsole.__init__(self, locals) self.stdout = sys.stdout self.stderr = sys.stderr self.pipe = Pipe() self.completer = Completer(locals)
def import_all_but_wx(name, globals=__builtin__.globals(), locals=__builtin__.locals(), fromlist=[], level=-1, default_import=__builtin__.__import__): if name == "wx" or name.startswith("wx."): raise ImportError("Not allowed to import wx!") return default_import(name, globals, locals, fromlist, level)
def get_available_gui_toolkits(cls): # # ''' Determines available gui toolkits. Examples: >>> __test_globals__['qt'] = __test_globals__['gtk'] = None >>> Browser('google.de').available_gui_toolkits ('default',) ''' toolkits = [] for toolkit in builtins.globals(): if(builtins.globals()[toolkit] is not None and '_initialize_%s_browser' % toolkit in cls.__dict__): toolkits.append(toolkit) toolkits.append('default') return builtins.tuple(toolkits)
def do_complete(text): """Does code completion""" import __main__ import __builtin__ import readline import rlcompleter matchDict=__main__.__dict__.copy() matchDict.update(__builtin__.globals()) rlc=rlcompleter.Completer(matchDict) rlc.complete(text,0) return list(set(rlc.matches)) #just to get rid of duplicates
def do_complete(text): """Does code completion""" import __main__ import __builtin__ import readline import rlcompleter matchDict = __main__.__dict__.copy() matchDict.update(__builtin__.globals()) rlc = rlcompleter.Completer(matchDict) rlc.complete(text, 0) return list(set(rlc.matches)) #just to get rid of duplicates
def config_files(self, site, context, dir = None, release = True): ctx = self.get_context(context) dns = [ctx['dns']] + ctx['redirects'] ndns = [r.replace('.','\.') for r in dns] ser.all_redirects = '|'.join(ndns) ser.apps = application_map(site.settings.INSTALLED_APPS, safe=False).values() environ['nginx'] = config_file(self, self.nginx, ctx, dir=dir) if not release: from __builtin__ import globals g = globals() g['script_result'] = environ
def config_files(self, site, context, dir=None, release=True): ctx = self.get_context(context) dns = [ctx['dns']] + ctx['redirects'] ndns = [r.replace('.', '\.') for r in dns] ser.all_redirects = '|'.join(ndns) ser.apps = application_map(site.settings.INSTALLED_APPS, safe=False).values() environ['nginx'] = config_file(self, self.nginx, ctx, dir=dir) if not release: from __builtin__ import globals g = globals() g['script_result'] = environ
def config_files(self, environ, dir = None, release = True): rs = [environ['domain_name']] + environ['redirects'] v = [] for r in rs: v.append(r.replace('.','\.')) environ['nginx_redirects'] = '|'.join(v) environ['apps'] = application_map().values() if dir is None: dir = None if not release else environ['confdir'] environ['nginx'] = config_file(self.nginx,environ=environ,dir=dir) if not release: from __builtin__ import globals g = globals() g['script_result'] = environ
def clone_function(func, globals=None): """ Clone a function object by creating a new FunctionType with a cloned code object. """ from types import CodeType, FunctionType co = func.func_code code = CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, co.co_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab) import __builtin__ if globals is None: globals = __builtin__.globals() return FunctionType(code, globals, func.func_name, func.func_defaults)
def __init__(self, name, homeVar = None, configDir = None, systemDir = None, userDir = None, module = None, requires = None, options = None, arguments = None, **kargs): super(Package, self).__init__() self.name = name self.module = module self.requires = requires self.options = options self.arguments = arguments self.homeVar = homeVar self.configDir = configDir self.systemDir = systemDir self.userDir = userDir if not self.module: self.module = self.name.replace("-", "_") imported = __import__(self.module+".config", __builtin__.globals(), __builtin__.locals(), ["config"]) self.configuration = getattr(imported, "Configuration")() if not self.homeVar: self.homeVar = (self.name.replace("-", "_")+"_HOME").upper() if not self.configDir: self.configDir = self.configuration.configurationPath if not self.systemDir: self.systemDir = self.configuration.filePath if not self.userDir: self.userDir = os.path.join(os.environ["HOME"], "."+self.name) if not self.requires: if hasattr(self.configuration, "requires"): self.requires = self.configuration.requires if not self.options: if hasattr(self.configuration, "options"): self.options = self.configuration.options if not self.arguments: if hasattr(self.configuration, "arguments"): self.arguments = self.configuration.arguments
import myhacks ctx # Error: NameError: file <maya console> line 1: name 'ctx' is not defined import __builtin__ __builtin__.globals()['ctx'] # Error: KeyError: file <maya console> line 1: ctx # __builtin__.globals()['ctx'] = myhacks.ctx ctx ctx.scriptEditor.comment() ctx.scriptEditor.uncomment() del ctx ctx # Error: NameError: file <maya console> line 1: name 'ctx' is not defined myhacks.ctx # Result: <myhacks.Context object at 0x0000000748150FD0> del myhacks.ctx myhacks.ctx # Error: AttributeError: file <maya console> line 1: 'module' object has no attribute 'ctx' reload(myhacks)
return __import__('sys').modules.setdefault(self.name, self.module) # add import hook for internal api sys.meta_path.append(__base__) # add custom subdirs to the search path for p in (_ for _ in os.listdir(root) if os.path.isdir(os.path.join(root,_)) and not _.startswith('.')): path = os.path.join(root, p) if path == __base__.base: continue #sys.meta_path.append(__submodule__(path)) sys.path.append(path) # empty out idapython's namespace import __builtin__ [__builtin__.globals().pop(_) for _ in __builtin__.globals().copy() if not _.startswith('_')] # re-populate with a default namespace from __root__ import * # try and execute our user's idapythonrc.py try: if os.getenv('HOME'): execfile(os.path.join(os.getenv('HOME'), 'idapythonrc.py')) elif os.getenv('USERPROFILE'): execfile(os.path.join(os.getenv('USERPROFILE'), 'idapythonrc.py')) else: raise OSError('Unable to figure out home directory') pass except IOError: logging.warn('No idapythonrc.py file found in home directory')
def Confirmation(f, action, **kwargs): function = globals()[f] oc = ObjectContainer(title2=action) oc.add(DirectoryObject(title=unicode('{} {}'.format(L('confirm'), action)), thumb=R('icon-default.png'), key=Callback(function, **kwargs))) return oc
def declare(member, value): attr = 'a_%s' % member globals()[attr] = value print attr, value