2015-10-20 29 views
0

所以,我試圖從一個特定的文件導入一個函數,並在一個不同的文件上的函數中運行它。這裏是我的代碼:如何導入一個你不知道python名字的函數?

import re 

def get_func_names(string): 
    temp = re.compile(r"def [a-z]+") 
    result = temp.findall(string) 
    return [elem[4:] for elem in result] 

def test_a_function(val): 
    import swift 
    g = open('swift.py', 'r') 
    g = g.read() 
    functions = get_func_names(g) 
    k = functions[0] 
    k = eval(k(val)) 
    return k 

get_func_names使用re模塊和模式匹配得到所有蟒蛇文檔中「高清」之後出現的名字,只有返回的函數的名稱。 test_a_function導入python文檔,打開它,應用get_func_names,並嘗試使用eval函數計算函數名稱的第一個字符串,但是我收到一個錯誤,指出'str'對象不可調用。

有沒有辦法解決我的方法或其他方式來做到這一點?

編輯:

好的,謝謝你的回答,但最後因爲某些原因,它只能與導入庫模塊

import importlib 
import types 

def getfuncs(modulename): 
    retval = {} 
    opened = importlib.import_module(modulename) 
    for name in opened.__dict__.keys(): 
     if isinstance(opened.__dict__[name], types.FunctionType): 
      retval[name] = opened.__dict__[name] 
    return retval 
+3

咦?你爲什麼想要評估任何東西?只需將您的文件作爲模塊導入,並從您的字典中提取出想要的內容即可。看'__imp __()'。 –

+2

Python也有一個強大的,可靠的AST模塊。您可以讓其解析器完成在另一個源文件中查找內容的工作。試圖使用正則表達式只是完全不必要的痛苦和痛苦(和錯誤,因爲你的正則表達式不知道'def foo'是否在多行字符串中)。 –

+1

開始的地方:https://docs.python.org/2/library/imp.html; https://docs.python.org/2/library/ast.html –

回答

0

工作考慮:

import types 

def getfuncs(modulename): 
    retval = {} 
    module = __import__(modulename, globals(), locals(), [], -1) 
    for (name, item) in module.__dict__.iteritems(): 
     if isinstance(item, types.FunctionType): 
      retval[name] = item 
    return retval 

getfuncs('swift') # returns a dictionary of functions in the swift module 

如果你不希望在模塊層次上發生評估的副作用,你可以使用AST模塊來評估函數定義,但是這會有相當多的工作(並且模塊編寫不是期待這種行爲不一定正常)。

相關問題