在python中将字符串转换为函数
我有一个来自数据库的字符串。此字符串是模块中的文件.py的名称。结构如下:在python中将字符串转换为函数,python,string,function,module,getattr,Python,String,Function,Module,Getattr,我有一个来自数据库的字符串。此字符串是模块中的文件.py的名称。结构如下: files ├── file1.py ├── file2.py └── __init__.py file1.py包含: def file1(imprime): print(imprime) def file2(imprime): print(imprime) file2.py包含: def file1(imprime): print(imprime) def file2(imprime):
files
├── file1.py
├── file2.py
└── __init__.py
file1.py
包含:
def file1(imprime):
print(imprime)
def file2(imprime):
print(imprime)
file2.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)
有人能帮我吗?有几个问题。在这种情况下,
字符串不应该是“.py”文件名,而是模块或函数名,因此file1
file1
不在范围内,因为您已导入文件
,并且file1
函数位于文件中。file1
模块
您可以让文件/init.py声明以下内容:
from file1 import *
from file2 import *
如果希望file1
函数和file2
函数存在于文件上
。然后执行b=getattr(files,string)
您可以使用导入功能按名称导入模块,并将其粘贴到文件模块上
编辑:显示如何调用函数的更改
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)
我不明白这个问题。。。字符串也是一个糟糕的变量名:PWhy不仅仅是do,importfile1;b=file1.file1
?