本文整理匯總了Python中six.exec_方法的典型用法代碼示例。如果您正苦於以下問題:Python six.exec_方法的具體用法?Python six.exec_怎麽用?Python six.exec_使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類six
的用法示例。
在下文中一共展示了six.exec_方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: exec_wrapped_code
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def exec_wrapped_code(environment=None, post_process=None):
"""
Exec the submission code, with the given environment.
`post_process` is a function that takes a string, the original stdout of
the code, and returns a new string, the transformed stdout, suitable for
comparison.
"""
if environment is None:
environment = {}
def test_fn(submission_module):
with capture_stdout() as stdout:
six.exec_(submission_module.submission_code, environment)
stdout_text = stdout.getvalue()
if post_process:
stdout_text = post_process(stdout_text)
print(stdout_text)
return test_fn
示例2: exec_code_and_inspect_values
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def exec_code_and_inspect_values(environment=None, vars_to_inspect=None, post_process=None):
"""
Exec the submission code, with the given environment.
`vars_to_inspect` is a list of variables to inspect the values of (they will
be inspected by printing to stdout). Does not otherwise inspect student output.
`post_process` is a function that takes a string, the original stdout of
the code, and returns a new string, the transformed stdout, suitable for
comparison.
"""
if environment is None:
environment = {}
def test_fn(submission_module):
with capture_stdout() as stdout:
six.exec_(submission_module.submission_code, environment)
for var in vars_to_inspect:
print(var)
return test_fn
示例3: get_wrapped
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def get_wrapped(func, wrapper_template, evaldict):
# Preserve the argspec for the wrapped function so that testing
# tools such as pytest can continue to use their fixture injection.
args, a, kw, defaults = inspect.getargspec(func)
values = args[-len(defaults):] if defaults else None
signature = inspect.formatargspec(args, a, kw, defaults)
is_bound_method = hasattr(func, '__self__')
if is_bound_method:
args = args[1:] # Omit 'self'
callargs = inspect.formatargspec(args, a, kw, values,
formatvalue=lambda v: '=' + v)
ctx = {'signature': signature, 'funcargs': callargs}
six.exec_(wrapper_template % ctx, evaldict)
wrapper = evaldict['wrapper']
update_wrapper(wrapper, func)
if is_bound_method:
wrapper = wrapper.__get__(func.__self__, type(func.__self__))
return wrapper
示例4: testdata_guifront
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def testdata_guifront(defaultdb='testdb1'):
import ibeis
main_locals = ibeis.main(defaultdb=defaultdb, allow_newdir=True)
ibs, back = ut.dict_take(main_locals, ['ibs', 'back'])
ibswgt = back.ibswgt # NOQA
globals__ = globals()
locals__ = locals()
def testdata_main_loop(globals_=globals__, locals_=locals__):
locals_ = locals_.copy()
globals_ = globals_.copy()
locals_.update(locals__)
globals_.update(globals__)
if '--cmd' in sys.argv:
gt.qtapp_loop(qwin=ibswgt, ipy=True)
six.exec_(ut.ipython_execstr(), globals_, locals_)
elif ut.show_was_requested():
gt.qtapp_loop(qwin=ibswgt)
return ibs, back, ibswgt, testdata_main_loop
示例5: load_module
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def load_module(self, full_name):
orig = full_name.split('.')[-1]
if orig not in sklearn.__all__:
raise ImportError('%s not in sklearn' % orig)
mod = sys.modules.setdefault(full_name, imp.new_module(full_name))
mod.__file__ = ''
mod.__name__ = full_name
mod.__path__ = ''
mod.__loader__ = self
mod.__package__ = '.'.join(full_name.split('.')[:-1])
code = _code.substitute({'mod_name': orig})
six.exec_(code, mod.__dict__)
return mod
示例6: _set_signature
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def _set_signature(mock, original, instance=False):
# creates a function with signature (*args, **kwargs) that delegates to a
# mock. It still does signature checking by calling a lambda with the same
# signature as the original.
skipfirst = isinstance(original, ClassTypes)
result = _get_signature_object(original, instance, skipfirst)
if result is None:
return mock
func, sig = result
def checksig(*args, **kwargs):
sig.bind(*args, **kwargs)
_copy_func_details(func, checksig)
name = original.__name__
if not _isidentifier(name):
name = 'funcopy'
context = {'_checksig_': checksig, 'mock': mock}
src = """def %s(*args, **kwargs):
_checksig_(*args, **kwargs)
return mock(*args, **kwargs)""" % name
six.exec_(src, context)
funcopy = context[name]
_setup_func(funcopy, mock, sig)
return funcopy
示例7: parse_user_config
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def parse_user_config(config, source_code=None):
try:
if source_code is None:
with codecs.open(config["base"]["strategy_file"], encoding="utf-8") as f:
source_code = f.read()
scope = {}
code = compile(source_code, config["base"]["strategy_file"], 'exec')
six.exec_(code, scope)
__config__ = scope.get("__config__", {})
deep_update(__config__, config)
for sub_key, sub_dict in six.iteritems(__config__):
if sub_key not in config["whitelist"]:
continue
deep_update(sub_dict, config[sub_key])
except Exception as e:
system_log.error(_('in parse_user_config, exception: {e}').format(e=e))
finally:
return config
示例8: parse_user_config_from_code
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def parse_user_config_from_code(config, source_code=None):
try:
if source_code is None:
with codecs.open(config["base"]["strategy_file"], encoding="utf-8") as f:
source_code = f.read()
scope = {}
code = compile(source_code, config["base"]["strategy_file"], 'exec')
six.exec_(code, scope)
__config__ = scope.get("__config__", {})
for sub_key, sub_dict in six.iteritems(__config__):
if sub_key not in config["whitelist"]:
continue
deep_update(sub_dict, config[sub_key])
except Exception as e:
system_log.error(_(u"in parse_user_config, exception: {e}").format(e=e))
finally:
return config
示例9: test_exec_
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def test_exec_():
def f():
l = []
six.exec_("l.append(1)")
assert l == [1]
f()
ns = {}
six.exec_("x = 42", ns)
assert ns["x"] == 42
glob = {}
loc = {}
six.exec_("global y; y = 42; x = 12", glob, loc)
assert glob["y"] == 42
assert "x" not in glob
assert loc["x"] == 12
assert "y" not in loc
示例10: test_astore_model
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def test_astore_model(session, cas_session, change_dir):
"""Ensure the register_sas_classification_model.py example executes successfully."""
# Mock up Session() to return the Betamax-recorded session
def Session(*args, **kwargs):
return session
change_dir('examples')
with open('register_sas_classification_model.py') as f:
# Remove Session import and set CAS session to Betamax-recorded CAS
# session
code = f.read().replace('from sasctl import Session', '')
code = code.replace("s = swat.CAS('hostname', 5570, 'username', 'password')",
's = cas_session')
# Exec the script.
six.exec_(code)
示例11: test_register_sas_regression_model
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def test_register_sas_regression_model(session, cas_session, change_dir):
"""Ensure the register_sas_regression_model.py example executes successfully."""
# Mock up Session() to return the Betamax-recorded session
def Session(*args, **kwargs):
return session
change_dir('examples')
with open('register_sas_regression_model.py') as f:
# Remove Session import and set CAS session to Betamax-recorded CAS
# session
code = f.read().replace('from sasctl import Session', '')
code = code.replace("with swat.CAS('hostname', 5570, 'username', 'password') as cas:",
"with cas_session as cas:")
# Exec the script.
six.exec_(code)
示例12: test_full_lifecycle
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def test_full_lifecycle(session, change_dir):
"""Ensure the register_scikit_classification_model.py example executes successfully."""
pytest.skip("Fix/re-implement. Performance upload creates unrecorded CAS "
"session that can't be replayed.")
# Mock up Session() to return the Betamax-recorded session
def Session(*args, **kwargs):
return session
change_dir('examples')
with open('full_lifecycle.py') as f:
# Remove import of Session to ensure mock function will be used
# instead.
code = f.read().replace('from sasctl import Session', '')
six.exec_(code)
示例13: code_config
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def code_config(config, source_code=None):
try:
if source_code is None:
with codecs.open(config["base"]["strategy_file"], encoding="utf-8") as f:
source_code = f.read()
# FIXME: hardcode for parametric mod
def noop(*args, **kwargs):
pass
scope = {'define_parameter': noop}
code = compile(source_code, config["base"]["strategy_file"], 'exec')
six.exec_(code, scope)
return scope.get('__config__', {})
except Exception as e:
system_log.error(_(u"in parse_user_config, exception: {e}").format(e=e))
return {}
示例14: get_wrapped
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def get_wrapped(func, wrapper_template, evaldict):
# Preserve the argspec for the wrapped function so that testing
# tools such as pytest can continue to use their fixture injection.
args, a, kw, defaults = inspect.getargspec(func)
signature = inspect.formatargspec(args, a, kw, defaults)
is_bound_method = hasattr(func, '__self__')
if is_bound_method:
args = args[1:] # Omit 'self'
callargs = inspect.formatargspec(args, a, kw, None)
ctx = {'signature': signature, 'funcargs': callargs}
six.exec_(wrapper_template % ctx, evaldict)
wrapper = evaldict['wrapper']
update_wrapper(wrapper, func)
if is_bound_method:
wrapper = wrapper.__get__(func.__self__, type(func.__self__))
return wrapper
示例15: __init__
# 需要導入模塊: import six [as 別名]
# 或者: from six import exec_ [as 別名]
def __init__(self, score_file):
file_string = open(score_file, 'r').read()
file_string = file_string.replace('import jmp_score as jmp', '')
file_string = file_string.replace('from __future__ import division', '')
file_string = file_string.replace('from math import *', '')
file_string = file_string.replace('import numpy as np', '')
self.file_string = file_string
six.exec_(self.file_string, globals())
try:
self.input_dict = getInputMetadata()
self.output_dict = getOutputMetadata()
self.model_dict = getModelMetadata()
except NameError:
raise ValueError("The file is not a valid Python scroing file from JMP")