>>> compile("""
def some_function(x):
return x+2
some_function""",'compiled function','single')
Traceback (most recent call last):
File "<pyshell#3>", line 4, in <module>
some_function""",'compiled function','single')
File "compiled function", line 4
some_function
^
SyntaxError: unexpected EOF while parsing
答案 0 :(得分:2)
如果要使用compile
编译多语句字符串,single
应为exec
。此外,在编译代码之后,您必须执行它并捕获全局变量以访问创建的函数:
def anonymous(code):
# To fix the indentation
fixed_code = '\n'.join(line[4:] for line in code.splitlines())
_globals = {}
exec(compile(fixed_code, '<string>', 'exec'), _globals)
if 'f' not in _globals:
raise ValueError('You must name your function "f"')
return _globals['f']
anonymous('''
def f(x):
return x + 2
''')(12)
答案 1 :(得分:1)
问题不是很清楚,但这是你想要的例子吗?
>>> c=compile('''\
... def some_function(x):
... return x+2
... print(some_function(5))
... ''','<string>','exec')
>>> exec(c)
7
>>> c=compile('7+2','<string>','eval')
>>> eval(c)
9