本文整理汇总了Python中six.exec_函数的典型用法代码示例。如果您正苦于以下问题:Python exec_函数的具体用法?Python exec_怎么用?Python exec_使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了exec_函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: Broken
def Broken(self, oid, pair):
broken_klasses_lock.acquire()
try:
if pair in broken_klasses:
klass = broken_klasses[pair]
else:
module, klassname = pair
d = {'BrokenClass': BrokenClass}
exec_("class %s(BrokenClass): ' '; __module__=%r" %
(klassname, module), d)
klass = broken_klasses[pair] = d[klassname]
module = module.split('.')
if len(module) > 2 and module[0] == 'Products':
klass.product_name = module[1]
klass.title = (
'This object from the %s product '
'is broken!' %
klass.product_name)
klass.info = (
'This object\'s class was %s in module %s.' %
(klass.__name__, klass.__module__))
klass = persistentBroken(klass)
LOG.warning(
'Could not import class %r '
'from module %r' % (klass.__name__, klass.__module__))
finally:
broken_klasses_lock.release()
if oid is None:
return klass
i = klass()
i._p_oid = oid
i._p_jar = self
return i
开发者ID:dhavlik,项目名称:Zope,代码行数:33,代码来源:Uninstalled.py
示例2: run_plain
def run_plain():
# Using normal Python shell
import code
imported_objects = import_objects(options, self.style)
try:
# Try activating rlcompleter, because it's handy.
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(imported_objects).complete)
readline.parse_and_bind("tab:complete")
# We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
# conventions and get $PYTHONSTARTUP first then import user.
if use_pythonrc:
pythonrc = os.environ.get("PYTHONSTARTUP")
if pythonrc and os.path.isfile(pythonrc):
global_ns = {}
with open(pythonrc) as rcfile:
try:
six.exec_(compile(rcfile.read(), pythonrc, 'exec'), global_ns)
imported_objects.update(global_ns)
except NameError:
pass
# This will import .pythonrc.py as a side-effect
try:
import user # NOQA
except ImportError:
pass
code.interact(local=imported_objects)
开发者ID:JamesX88,项目名称:tes,代码行数:34,代码来源:shell_plus.py
示例3: remote_profile
def remote_profile(script, timer, interval, pickle_protocol,
addr, start_signo, stop_signo, verbose):
"""Launch a server to profile continuously. The default address is
127.0.0.1:8912.
"""
filename, code, globals_ = script
sys.argv[:] = [filename]
# create listener.
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(addr)
listener.listen(1)
# be verbose or quiet.
if verbose:
log = lambda x: click.echo(click.style(' > ', fg='cyan') + x)
bound_addr = listener.getsockname()
log('Listening on {0}:{1} for profiling...'.format(*bound_addr))
else:
log = noop
# start profiling server.
frame = sys._getframe()
profiler = BackgroundProfiler(timer, frame, code, start_signo, stop_signo)
profiler.prepare()
server_args = (log, interval, pickle_protocol)
server = SelectProfilingServer(listener, profiler, *server_args)
spawn_thread(server.serve_forever)
# exec the script.
try:
exec_(code, globals_)
except KeyboardInterrupt:
pass
开发者ID:IanMulvany,项目名称:profiling,代码行数:31,代码来源:__main__.py
示例4: conv_fn_str_to_obj
def conv_fn_str_to_obj(fn_tup, tok, sim_funcs):
d_orig = {}
d_orig.update(tok)
d_orig.update(sim_funcs)
d_ret_list = []
for f in fn_tup:
d_ret = {}
name = f[0]
attr1 = f[1]
attr2 = f[2]
tok_1 = f[3]
tok_2 = f[4]
simfunction = f[5]
# exec(f[6] in d_orig)
six.exec_(f[6], d_orig)
d_ret['function'] = d_orig[name]
d_ret['feature_name'] = name
d_ret['left_attribute'] = attr1
d_ret['right_attribute'] = attr2
d_ret['left_attr_tokenizer'] = tok_1
d_ret['right_attr_tokenizer'] = tok_2
d_ret['simfunction'] = simfunction
d_ret['function_source'] = f[6]
d_ret_list.append(d_ret)
return d_ret_list
开发者ID:paulgc,项目名称:magellan,代码行数:26,代码来源:autofeaturegen.py
示例5: __profile__
def __profile__(filename, code, globals_,
timer=None, pickle_protocol=PICKLE_PROTOCOL,
dump_filename=None, mono=False):
frame = sys._getframe()
profiler = Profiler(timer, top_frame=frame, top_code=code)
profiler.start()
try:
exec_(code, globals_)
except:
# don't profile print_exc().
profiler.stop()
traceback.print_exc()
else:
profiler.stop()
if PY2:
# in Python 2, exec's cpu time is duplicated with actual cpu time.
stat = profiler.stats.get_child(frame.f_code)
stat.remove_child(exec_.func_code)
if dump_filename is None:
viewer, loop = make_viewer(mono)
viewer.set_stats(profiler.stats, get_title(filename))
try:
loop.run()
except KeyboardInterrupt:
pass
else:
stats = profiler.result()
with open(dump_filename, 'wb') as f:
pickle.dump(stats, f, pickle_protocol)
click.echo('To view statistics:')
click.echo(' $ python -m profiling view ', nl=False)
click.secho(dump_filename, underline=True)
开发者ID:bootinge,项目名称:profiling,代码行数:32,代码来源:__main__.py
示例6: get_feature_fn
def get_feature_fn(feat_str, tok, sim):
if not isinstance(feat_str, six.string_types):
logger.error('Input feature string is not of type string')
raise AssertionError('Input feature string is not of type string')
if not isinstance(tok, dict):
logger.error('Input tok is not of type dict')
raise AssertionError('Input tok. is not of type dict')
if not isinstance(sim, dict):
logger.error('Input sim is not of type dict')
raise AssertionError('Input sim. is not of type dict')
temp = {}
# update sim
if len(sim) > 0:
temp.update(sim)
if len(tok) > 0:
temp.update(tok)
fn = 'def fn(ltuple, rtuple):\n'
fn += ' '
fn += 'return ' + feat_str
d = parse_feat_str(feat_str, tok, sim)
# six.exec_(fn, temp, temp)
six.exec_(fn, temp)
d['function'] = temp['fn']
d['function_source'] = fn
return d
开发者ID:paulgc,项目名称:magellan,代码行数:27,代码来源:addfeatures.py
示例7: handle
def handle(self, *args, **options):
imports = options['imports']
query = options['query']
verbose = options['verbose']
assert imports, 'No imports specified.'
assert query, 'No query specified.'
for imp in imports.strip().split('|'):
imp_parts = tuple(imp.split(','))
if len(imp_parts) == 1:
cmd = ('import %s' % imp_parts)
elif len(imp_parts) == 2:
cmd = ('from %s import %s' % imp_parts)
elif len(imp_parts) == 3:
cmd = ('from %s import %s as %s' % imp_parts)
else:
raise Exception('Invalid import: %s' % (imp,))
if verbose:
print(cmd)
six.exec_(cmd)
if verbose:
print(query)
q = eval(query, globals(), locals())
job = get_current_job()
if job:
job.monitor_records = q.count()
job.save()
if q.count():
print('%i records require attention.' % (q.count(),), file=sys.stderr)
else:
print('%i records require attention.' % (q.count(),), file=sys.stdout)
开发者ID:SpisTresci,项目名称:django-chroniker,代码行数:32,代码来源:check_monitor.py
示例8: run_rc_file
def run_rc_file(editor, rc_file):
"""
Run rc file.
"""
assert isinstance(editor, Editor)
assert isinstance(rc_file, six.text_type)
# Expand tildes.
rc_file = os.path.expanduser(rc_file)
# Check whether this file exists.
if not os.path.exists(rc_file):
print('Impossible to read %r' % rc_file)
_press_enter_to_continue()
return
# Run the rc file in an empty namespace.
try:
namespace = {}
with open(rc_file, 'r') as f:
code = compile(f.read(), rc_file, 'exec')
six.exec_(code, namespace, namespace)
# Now we should have a 'configure' method in this namespace. We call this
# method with editor as an argument.
if 'configure' in namespace:
namespace['configure'](editor)
except Exception as e:
# Handle possible exceptions in rc file.
traceback.print_exc()
_press_enter_to_continue()
开发者ID:amjith,项目名称:pyvim,代码行数:33,代码来源:rc_file.py
示例9: run_strategy
def run_strategy(source_code, strategy_filename, start_date, end_date, init_cash, data_bundle_path, show_progress):
scope = {
"logger": user_log,
"print": user_print,
}
scope.update({export_name: getattr(api, export_name) for export_name in api.__all__})
code = compile(source_code, strategy_filename, 'exec')
exec_(code, scope)
try:
data_proxy = LocalDataProxy(data_bundle_path)
except FileNotFoundError:
print_("data bundle might crash. Run `%s update_bundle` to redownload data bundle." % sys.argv[0])
sys.exit()
trading_cal = data_proxy.get_trading_dates(start_date, end_date)
Scheduler.set_trading_dates(data_proxy.get_trading_dates(start_date, datetime.date.today()))
trading_params = TradingParams(trading_cal, start_date=start_date.date(), end_date=end_date.date(),
init_cash=init_cash, show_progress=show_progress)
executor = StrategyExecutor(
init=scope.get("init", dummy_func),
before_trading=scope.get("before_trading", dummy_func),
handle_bar=scope.get("handle_bar", dummy_func),
trading_params=trading_params,
data_proxy=data_proxy,
)
results_df = executor.execute()
return results_df
开发者ID:andyyang0,项目名称:rqalpha,代码行数:32,代码来源:__main__.py
示例10: __load_from_path
def __load_from_path(cls, conf, path):
if isdir(path):
conf.config_folder = path
files = sorted(os.listdir(path))
for file in files:
if file.endswith('.conf'):
filepath = path + os.sep + file
conf = Config.__load_from_path(conf, filepath)
return conf
with open(path) as config_file:
name = 'configuration'
code = config_file.read()
module = imp.new_module(name)
six.exec_(code, module.__dict__)
conf.config_file = path
for name, value in module.__dict__.items():
if name.upper() == name:
conf._items[name] = value
setattr(conf, name, value)
return conf
开发者ID:globocom,项目名称:derpconf,代码行数:27,代码来源:config.py
示例11: compile_strategy
def compile_strategy(source_code, strategy, scope):
try:
code = compile(source_code, strategy, 'exec')
six.exec_(code, scope)
return scope
except Exception as e:
exc_type, exc_val, exc_tb = sys.exc_info()
exc_val = patch_user_exc(exc_val, force=True)
try:
msg = str(exc_val)
except Exception as e1:
msg = ""
six.print_(e1)
error = CustomError()
error.set_msg(msg)
error.set_exc(exc_type, exc_val, exc_tb)
stackinfos = list(traceback.extract_tb(exc_tb))
if isinstance(e, (SyntaxError, IndentationError)):
error.add_stack_info(exc_val.filename, exc_val.lineno, "", exc_val.text)
else:
for item in stackinfos:
filename, lineno, func_name, code = item
if strategy == filename:
error.add_stack_info(*item)
# avoid empty stack
if error.stacks_length == 0:
error.add_stack_info(*item)
raise CustomException(error)
开发者ID:SeavantUUz,项目名称:rqalpha,代码行数:31,代码来源:strategy_loader_help.py
示例12: verify
def verify(cls, path):
if path is None:
return []
if not exists(path):
raise ConfigurationError('Configuration file not found at path %s' % path)
with open(path) as config_file:
name = 'configuration'
code = config_file.read()
module = imp.new_module(name)
six.exec_(code, module.__dict__)
conf = cls(defaults=[])
for name, value in module.__dict__.items():
if name.upper() == name:
setattr(conf, name, value)
not_found = []
for key, value in cls.class_defaults.items():
if key not in conf.__dict__:
not_found.append((key, value))
return not_found
开发者ID:globocom,项目名称:derpconf,代码行数:27,代码来源:config.py
示例13: execute_python_code
def execute_python_code(code):
try:
c = compile(code, '<string>', 'exec')
except Exception:
print('On execute_python_code with code=\n{}'.format(code))
raise
six.exec_(c)
开发者ID:zerotk,项目名称:reraiseit,代码行数:7,代码来源:test_reraiseit.py
示例14: load_module
def load_module(self, name):
co, pyc = self.modules.pop(name)
if name in sys.modules:
# If there is an existing module object named 'fullname' in
# sys.modules, the loader must use that existing module. (Otherwise,
# the reload() builtin will not work correctly.)
mod = sys.modules[name]
else:
# I wish I could just call imp.load_compiled here, but __file__ has to
# be set properly. In Python 3.2+, this all would be handled correctly
# by load_compiled.
mod = sys.modules[name] = imp.new_module(name)
try:
mod.__file__ = co.co_filename
# Normally, this attribute is 3.2+.
mod.__cached__ = pyc
mod.__loader__ = self
# Normally, this attribute is 3.4+
mod.__spec__ = spec_from_file_location(name, co.co_filename, loader=self)
six.exec_(co, mod.__dict__)
except: # noqa
if name in sys.modules:
del sys.modules[name]
raise
return sys.modules[name]
开发者ID:lmregus,项目名称:Portfolio,代码行数:25,代码来源:rewrite.py
示例15: load_module
def load_module(self, fullname):
if self.mod is None:
mod = self.mod = imp.new_module(self.name)
else:
mod = self.mod
log_buffer = []
mod.logging = mod.logger = logging.Logger(self.name)
handler = SaveLogHandler(log_buffer)
handler.setFormatter(LogFormatter(color=False))
mod.logger.addHandler(handler)
mod.log_buffer = log_buffer
mod.__file__ = '<%s>' % self.name
mod.__loader__ = self
mod.__project__ = self.project
mod.__package__ = ''
code = self.get_code(fullname)
six.exec_(code, mod.__dict__)
linecache.clearcache()
if '__handler_cls__' not in mod.__dict__:
BaseHandler = mod.__dict__.get('BaseHandler', base_handler.BaseHandler)
for each in list(six.itervalues(mod.__dict__)):
if inspect.isclass(each) and each is not BaseHandler \
and issubclass(each, BaseHandler):
mod.__dict__['__handler_cls__'] = each
return mod
开发者ID:xyrnwbtj,项目名称:dockerAutomatedBuild,代码行数:29,代码来源:project_module.py
示例16: OnSetPropertyValues
def OnSetPropertyValues(self,event):
try:
d = self.pg.GetPropertyValues(inc_attributes=True)
ss = []
for k,v in d.items():
v = repr(v)
if not v or v[0] != '<':
if k.startswith('@'):
ss.append('setattr(obj, "%s", %s)'%(k,v))
else:
ss.append('obj.%s = %s'%(k,v))
with MemoDialog(self,
"Enter Content for Object Used in SetPropertyValues",
'\n'.join(ss)) as dlg: # default_object_content1
if dlg.ShowModal() == wx.ID_OK:
import datetime
sandbox = {'obj':ValueObject(),
'wx':wx,
'datetime':datetime}
exec_(dlg.tc.GetValue(), sandbox)
t_start = time.time()
#print(sandbox['obj'].__dict__)
self.pg.SetPropertyValues(sandbox['obj'])
t_end = time.time()
self.log.write('SetPropertyValues finished in %.0fms\n' %
((t_end-t_start)*1000.0))
except:
import traceback
traceback.print_exc()
开发者ID:GadgetSteve,项目名称:Phoenix,代码行数:32,代码来源:PropertyGrid.py
示例17: execfile_
def execfile_(filepath, _globals, open=open):
from sphinx.util.osutil import fs_encoding
# get config source -- 'b' is a no-op under 2.x, while 'U' is
# ignored under 3.x (but 3.x compile() accepts \r\n newlines)
f = open(filepath, 'rbU')
try:
source = f.read()
finally:
f.close()
# py26 accept only LF eol instead of CRLF
if sys.version_info[:2] == (2, 6):
source = source.replace(b'\r\n', b'\n')
# compile to a code object, handle syntax errors
filepath_enc = filepath.encode(fs_encoding)
try:
code = compile(source, filepath_enc, 'exec')
except SyntaxError:
if convert_with_2to3:
# maybe the file uses 2.x syntax; try to refactor to
# 3.x syntax using 2to3
source = convert_with_2to3(filepath)
code = compile(source, filepath_enc, 'exec')
else:
raise
exec_(code, _globals)
开发者ID:brentdur,项目名称:jiraLink,代码行数:27,代码来源:pycompat.py
示例18: _test
def _test(self, modname):
self.modname = modname
six.exec_("import %s" % modname, {})
self.module = sys.modules[modname]
self.check_all()
self.__implements__ = getattr(self.module, '__implements__', None)
self.__imports__ = getattr(self.module, '__imports__', [])
self.__extensions__ = getattr(self.module, '__extensions__', [])
self.stdlib_name = MAPPING.get(modname)
self.stdlib_module = None
if self.stdlib_name is not None:
try:
self.stdlib_module = __import__(self.stdlib_name)
except ImportError:
pass
self.check_implements_presence_justified()
if self.stdlib_module is None:
return
# use __all__ as __implements__
if self.__implements__ is None:
self.__implements__ = sorted(self.module.__all__)
self.set_stdlib_all()
self.check_implements_subset_of_stdlib_all()
self.check_implements_actually_implements()
self.check_imports_actually_imports()
self.check_extensions_actually_extend()
self.check_completeness()
开发者ID:dustyneuron,项目名称:gevent,代码行数:35,代码来源:test__all__.py
示例19: _set_source
def _set_source(func, new_source):
# Fetch the actual function we are changing
real_func = _get_real_func(func)
# Figure out any future headers that may be required
feature_flags = real_func.__code__.co_flags & FEATURE_MASK
# Compile and retrieve the new Code object
localz = {}
new_code = compile(
new_source,
'<patchy>',
'exec',
flags=feature_flags,
dont_inherit=True
)
six.exec_(new_code, func.__globals__, localz)
new_func = localz[func.__name__]
# Figure out how to get the Code object
if isinstance(new_func, (classmethod, staticmethod)):
new_code = new_func.__func__.__code__
else:
new_code = new_func.__code__
# Put the new Code object in place
real_func.__code__ = new_code
# Store the modified source. This used to be attached to the function but
# that is a bit naughty
_source_map[real_func] = new_source
开发者ID:pombredanne,项目名称:patchy,代码行数:31,代码来源:api.py
示例20: __profile__
def __profile__(filename, code, globals_, profiler_factory,
pickle_protocol=remote.PICKLE_PROTOCOL, dump_filename=None,
mono=False):
frame = sys._getframe()
profiler = profiler_factory(base_frame=frame, base_code=code)
profiler.start()
try:
exec_(code, globals_)
except:
# don't profile print_exc().
profiler.stop()
traceback.print_exc()
else:
profiler.stop()
# discard this __profile__ function from the result.
profiler.stats.discard_child(frame.f_code)
if dump_filename is None:
try:
profiler.run_viewer(get_title(filename), mono=mono)
except KeyboardInterrupt:
pass
else:
result = profiler.result()
with open(dump_filename, 'wb') as f:
pickle.dump((profiler.__class__, result), f, pickle_protocol)
click.echo('To view statistics:')
click.echo(' $ profiling view ', nl=False)
click.secho(dump_filename, underline=True)
开发者ID:pomeo92,项目名称:profiling,代码行数:28,代码来源:__main__.py
注:本文中的six.exec_函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论