本文整理汇总了Python中compile函数的典型用法代码示例。如果您正苦于以下问题:Python compile函数的具体用法?Python compile怎么用?Python compile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了compile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_invalid_sum
def test_invalid_sum(self):
pos = dict(lineno=2, col_offset=3)
m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
with self.assertRaises(TypeError) as cm:
compile(m, "<test>", "exec")
if support.check_impl_detail():
self.assertIn("but got <_ast.expr", str(cm.exception))
示例2: Update_Fields_State
def Update_Fields_State(self):
if self.fixed_range.checkState() == 2:
for k,l in enumerate(["X_Start","X_End","Y_Start","Y_End"]):
eval(compile("self.Display_Range_"+str(k)+".setEnabled(True)",'<string>','exec'))
else:
for k,l in enumerate(["X_Start","X_End","Y_Start","Y_End"]):
eval(compile("self.Display_Range_"+str(k)+".setEnabled(False)",'<string>','exec'))
示例3: check_roundtrip
def check_roundtrip(self, code1, filename="internal"):
ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST)
unparse_buffer = cStringIO.StringIO()
unparse.Unparser(ast1, unparse_buffer)
code2 = unparse_buffer.getvalue()
ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST)
self.assertASTEqual(ast1, ast2)
示例4: autocompile
def autocompile(ws, conf, env, **options):
"""Subcommand: autocompile -- automatically re-compiles when something in
content-dir has changed and parallel serving files."""
CONF_PY = './conf.py'
mtime = -1
cmtime = getmtime(CONF_PY)
while True:
ntime = max(
max(getmtime(e) for e in readers.filelist(conf['content_dir']) if utils.istext(e)),
max(getmtime(p) for p in readers.filelist(conf['layout_dir'])))
if mtime != ntime:
try:
compile(conf, env, **options)
except AcrylamidException as e:
log.fatal(e.args[0])
pass
event.reset()
mtime = ntime
if cmtime != getmtime(CONF_PY):
log.info(' * Restarting due to change in %s' % (CONF_PY))
# Kill the webserver
ws.shutdown()
# Force compilation since no template was changed
argv = sys.argv if options['force'] else sys.argv[:] + ["--force"]
# Restart acrylamid
os.execvp(sys.argv[0], argv)
time.sleep(1)
示例5: test_indentation
def test_indentation(self):
# testing compile() of indented block w/o trailing newline"
s = """
if 1:
if 2:
pass"""
compile(s, "<string>", "exec")
示例6: _compile_template
def _compile_template(self, lang, input_path, output_path, no_html=False):
try:
# Create output directory
self._create_dir(os.path.split(output_path)[0])
try:
# Open input file
code = codecs.open(input_path, 'r', 'utf-8').read()
except UnicodeDecodeError, e:
raise CompileException(0, 0, input_path, str(e))
# Compile
if no_html:
output = compile(code, loader=load_template_source, path=input_path,
options=get_options_for_path(input_path) + ['no-html'])
else:
output = compile(code, loader=load_template_source, path=input_path,
options=get_options_for_path(input_path))
# Open output file
codecs.open(output_path, 'w', 'utf-8').write(output)
# Delete -c-recompile file (mark for recompilation) if one such exist.
if os.path.exists(output_path + '-c-recompile'):
os.remove(output_path + '-c-recompile')
return True
示例7: _create_action_method
def _create_action_method(self, i, action):
# PP saving style action. No return value, e.g. "pp.lbft = 3".
exec compile('def _exec_action_%d(self, field, f, pp, grib, cm): %s' % (i, action), '<string>', 'exec')
# Make it a method of ours.
exec 'self._exec_action_%d = types.MethodType(_exec_action_%d, self, type(self))' % (i, i)
# Add to our list of actions.
exec 'self._exec_actions.append(self._exec_action_%d)' % i
示例8: Use
def Use(name):
# print(dir(sys.modules['solidpy'])); exit()
if name.endswith(".solid.py"):
with open(name) as f:
code = compile(f.read(), name, "exec")
exec(code, script_globals) # , script_locals)
elif name.endswith(".scad"):
Defaults.includeFiles.append(name)
else:
import imp
try:
fname = imp.find_module(name)[1]
except:
try:
fname = imp.find_module(name + ".solid")[1]
except:
fname = imp.find_module(name + "/" + name + ".solid")[1]
if fname is None:
code = "from " + name + " import *"
exec(code, script_globals) # , script_locals)
else:
with open(fname) as f:
code = compile(f.read(), fname, "exec")
exec(code, script_globals) # , script_locals)
示例9: function
def function(self):
code = "_lam = lambda %s: %s"%(",".join(self.arguments),self.return_expr)
print "code:", code
result = {}
exec compile(code, '<string>', 'exec') in result
print "result", result["_lam"]
return result["_lam"]
示例10: mod
def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
mod.lineno = mod.col_offset = 0
ast.fix_missing_locations(mod)
with self.assertRaises(exc) as cm:
compile(mod, "<test>", mode)
if msg is not None:
self.assertIn(msg, str(cm.exception))
示例11: execfile_
def execfile_(filepath, _globals):
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()
# py25,py26,py31 accept only LF eol instead of CRLF
if sys.version_info[:2] in ((2, 5), (2, 6), (3, 1)):
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)
示例12: test_empty_yield_from
def test_empty_yield_from(self):
# Issue 16546: yield from value is not optional.
empty_yield_from = ast.parse("def f():\n yield from g()")
empty_yield_from.body[0].body[0].value.value = None
with self.assertRaises(ValueError) as cm:
compile(empty_yield_from, "<test>", "exec")
self.assertIn("field value is required", str(cm.exception))
示例13: test_invalid_string
def test_invalid_string(self):
m = ast.Module([ast.Expr(ast.Str(42))])
ast.fix_missing_locations(m)
with self.assertRaises(TypeError) as cm:
compile(m, "<test>", "exec")
if support.check_impl_detail():
self.assertIn("string must be of type str or uni", str(cm.exception))
示例14: test_invalid_identitifer
def test_invalid_identitifer(self):
m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
ast.fix_missing_locations(m)
with self.assertRaises(TypeError) as cm:
compile(m, "<test>", "exec")
if support.check_impl_detail():
self.assertIn("identifier must be of type str", str(cm.exception))
示例15: EVAL
def EVAL(ast, env):
# try it as an expression then a statement
try:
return eval(ast)
except SyntaxError:
exec compile(ast, '', 'single') in globals()
return None