首页 > 解决方案 > 如何使用子进程库在顶级 python 文件中使用命令行参数调用其他 python 文件?

问题描述

所以基本上我有 15 个左右的脚本可以使用 SSH 库连接到各种网络设备。我想创建一个可以运行其他 python 脚本的顶级 python 文件,以便用户可以决定他们想要运行哪些脚本。有人建议我使用 subprocess 库,这似乎对我想做的事情最有意义。需要注意的是,我的 python 脚本包含用于运行的命令行 argparse 参数,例如:

 python reboot_server.py -deviceIP 172.1.1.1 -deviceUsername admin -devicePassword myPassword

到目前为止,我已经创建了一个顶级 python 文件,该文件设置为调用两个 python 脚本以开始用户可以输入的内容。但是,当我运行程序并选择其中一个选项时,我得到一个“SyntaxError:invalid syntax” Traceback。这发生在我输入第一个参数时,即设备 IP 地址

import subprocess
import os
import sys

def runMain():

    scriptName = os.path.basename(__file__)

    print("The name of this script: " + scriptName + "\n")

    while True:
        optionPrinter()

        user_input = input("Please select an option for which your heart desires...\n")

        switch_result = mySwitch(user_input)

        if switch_result == "our_Switch":
            deviceIP = str(input("Enter the IP address for the device"))
            deviceUsername = str(input("Enter the username for the device"))
            devicePassword = str(input("Enter the password for the device"))

            subprocess.call(['python', 'our_Switch.py', deviceIP, deviceUsername, devicePassword])

        elif switch_result == "San_test":
            deviceIP = str(input("Enter the IP address for the device"))
            deviceUsername = str(input("Enter the username for the device"))
            devicePassword = str(input("Enter the password for the device"))

            subprocess.call(['python', 'San_test.py', deviceIP, deviceUsername, devicePassword])

        else:
            print("Exiting the program now, have a great day !\n")
            sys.exit(-1)

这是回溯:

Traceback (most recent call last):
  File "C:/myFolder/src/top_level.py", line 57, in <module>
    runMain()
  File "C:/myFolder/src/top_level.py", line 39, in runMain
    deviceIP = str(input("Enter the IP address for the device"))
  File "<string>", line 1
    172.28.6.21
           ^
SyntaxError: invalid syntax

请记住,我尝试调用的所有脚本都在同一个源文件中。另外值得注意的是,我已经测试了我编写的每个脚本,并且它们都可以正常工作。我使用 subprocess.call() 对吗?我该如何解决这个问题?谢谢您的帮助!

标签: pythonpython-2.7

解决方案


您正在使用 python2。在 python2 中,input不仅接受输入,还将其评估为 python 代码。显然 IP 地址不是有效的 python 代码。因此语法错误。

对于 python2,您应该使用raw_input- 并且您可以删除str.

deviceIP = raw_input("Enter the IP address for the device")

或者你可以切换到python3


推荐阅读