我知道如何在 C 中执行此操作,但我不确定如何在 python 中执行此操作。我正在尝试制作一个将从外部文件读取的 python 程序,然后执行从该文件读取的函数名。示例:
文件结构:
main.py
map.py
Scripts/
script1.py
map.py 只包含一个数组和一个获取正确数组索引的函数:
map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
for i in range(0,len(map)):
if str in map[i]:
return map[i+1]
函数:“function_one()”和“function_two()”在 script1.py 中定义。 main.py 将包含如下内容:
selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.
有什么建议吗?
最佳答案
在您的 Scripts/
目录中,添加一个名为 __init__.py
的空白文件>
然后在您的 map.py 文件中,执行以下操作:
from Scripts import script1
map = {"One" : script1.function_one, "Two" : script1.function_two]
def return_mapping(str):
return map[str]
关于python - 如何运行存储在不同文件中的 python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5636986/