Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将字符串转换为函数_Python_String_Function_Module_Getattr - Fatal编程技术网

在python中将字符串转换为函数

在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):

我有一个来自数据库的字符串。此字符串是模块中的文件.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):
    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