python - 如何运行存储在不同文件中的 python 函数

标签 python

我知道如何在 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/

相关文章:

python - 使用任务队列发送邮件

python - Python 中是否有 quadprog() 的替代方案

python - 为什么我在 Django 中收到表单无效错误?

python - 将压缩的 CSV 文件转换为 Dataframe

python - 使用 web2py 检索表字段

python - 在python中获取组合框的值

python - 使用productbuild的应用程序加载器: error when creating a . pkg文件

python - 绘图铅笔断了

python - Pandas:借助字典将变量子字符串从 A 列插入 B 列

c++ - 在 boost python 中使用自定义智能指针