【问题标题】:how to call the methods as command arguments in python如何在python中调用方法作为命令参数
【发布时间】:2020-08-20 22:11:56
【问题描述】:

我有一个类似的示例程序

文件.py

def test1():
    print("test1")
def test2():
    print("test2")
def test3():
    print("test3")
def main():
    sys.argv[1]
    sys.argv[2]
    sys.argv[3]
 #   test1()
 #   test2()
 #   test3()

main()

我需要执行类似“python3 File.py test1() test2() test3()”的命令

有些场景我只需要执行一两个方法只需要“python3 File.py test1() test2()

【问题讨论】:

  • 你可以为每个文件创建一个函数吗?
  • @MVB76 然后单独导入它们,确保它们都在同一个目录中
  • 为什么不使用eval
  • @impopularGuy 你能给我关于 eval 函数的详细信息吗?如何使用 eval 执行这个命令 python3 File.py test1() test2() test3()

标签: python-3.x


【解决方案1】:

我不确定这是否是您要查找的内容,但是如果您在 file.py 保存的目录中打开 CMD,则可以使用:

python -i file.py

这将在交互式 shell 中打开文件。然后,您可以通过普通函数调用访问这些函数,例如 test1()

【讨论】:

    【解决方案2】:

    我将main函数填写如下:

    arguments = list(sys.argv)
    arguments.pop(0)
    while arguments:
        function_name = arguments.pop(0)
        locals()[function_name]()
    

    然后,在命令行中键入:

    $ python3 file.py test1 test3 test2
    

    【讨论】:

    • 我收到一条错误消息,指出文件“main.py”,第 13 行,在 main locals()["function_name"]() TypeError: 'str' object is not callable
    • 我的错,对不起。请去掉function_name周围的引号,见固定代码。
    猜你喜欢
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2020-01-13
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多