本文整理汇总了Python中six.exec_函数的典型用法代码示例。如果您正苦于以下问题:Python exec_函数的具体用法?Python exec_怎么用?Python exec_使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了exec_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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)
示例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
示例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
示例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)
示例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
示例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)
示例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()
示例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
示例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
示例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)
示例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
示例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)
示例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]
示例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