2013-04-11 102 views
0

我有一個來自數據庫的字符串。該字符串是模塊內的.py文件的名稱。該結構是這樣的:將字符串轉換爲python中的函數

files 
├── file1.py 
├── file2.py 
└── __init__.py 

file1.py包含:

def file1(imprime): 
    print(imprime) 

的​​包含:

def file2(imprime): 
    print(imprime) 

我需要將字符串轉換成可調用的函數。

main.py文件我嘗試:

import files 
string = "file1.py" 
b = getattr(file1, string) 

text = 'print this...' 

b(text) 

誰能幫助我?

+1

我不明白的問題......也字符串是一個可怕的變量名:P – 2013-04-11 15:44:48

+2

爲什麼不這樣做,'進口文件1; b = file1.file1'? – Kevin 2013-04-11 15:46:50

回答

0

您可以使用導入功能按名稱導入模塊並將其粘貼到文件模塊上。

編輯:改變以顯示如何調用該函數

import os 
import files 
wanted_file = "file1.py" 
# name of module plus contained function 
wanted_name = os.path.splitext(wanted_file)[0] 
# if you do this many times, you can skip the import lookup after the first hit 
if not hasattr(files, wanted_name): 
    module = __import__('files.' + wanted_name) 
    setattr(files, wanted_name, module) 
else: 
    module = getattr(files, wanted_name) 
fctn = getattr(module, wanted_name) 
text = 'print this...' 
fctn(text) 
0

有幾個問題。在這種情況下,string不應該是「.py」文件名,而應該是模塊或函數名,所以file1

file1雖然不在範圍之內,因爲您已經導入了filesfile1該功能在files.file1模塊中。

你可以有文件/ 初始化的.py聲明如下:

from file1 import * 
from file2 import * 

如果你想file1功能和file2功能上files存在。那麼你會做b = getattr(files, string)