在python中将字符串转换为函数(Convert string to function in python)
我有一个来自数据库的字符串。 此字符串是模块中文件.py的名称。 结构是这样的:
files ├── file1.py ├── file2.py └── __init__.pyfile1.py包含:
def file1(imprime): print(imprime)file2.py包含:
def file2(imprime): print(imprime)我需要将字符串转换为可以调用的函数。
在main.py文件中我尝试:
import files string = "file1.py" b = getattr(file1, string) text = 'print this...' b(text)谁能帮我?
I have a string coming from the database. This string is the name of a file .py that is within a module. The structure is this:
files ├── file1.py ├── file2.py └── __init__.pyThe file1.py contain:
def file1(imprime): print(imprime)The file2.py contain:
def file2(imprime): print(imprime)I need to convert the string to a function that can be callable.
In main.py file I try:
import files string = "file1.py" b = getattr(file1, string) text = 'print this...' b(text)Can anyone help me?
最满意答案
您可以使用导入功能按名称导入模块并将其粘贴在文件模块上。
编辑:更改以显示如何调用该函数
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)You can use the import function to import the module by name and stick that on the files module.
Edit: Changes to show how to call the function
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)更多推荐
发布评论