2013-04-11 103 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)