2013-10-27 25 views
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 

回答

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) 
+0

這不是Python 3代碼。 – ThePiercingPrince

+0

@LinuxDistance:只要將'exec'變成一個函數調用,它就可以工作。 Python 3和Python 2沒有那麼不同。 – Blender

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