0
>>> 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
4

2 回答 2

2

如果你想用 编译一个多语句字符串compilesingle应该是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)
于 2013-10-27T05:33:59.273 回答
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
于 2013-10-27T05:31:05.297 回答