如何使用子流程库在顶级python文件中使用命令行参数调用其他python文件?

2024-10-01 00:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

到目前为止,我已经创建了一个顶级python文件,该文件设置为调用两个python脚本,用户可以从中输入。但是,当我运行程序并选择其中一个选项时,我会得到一个“SyntaxError:invalid syntax”回溯。当我输入第一个参数(设备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()吗?如何解决此问题?谢谢你的帮助


Tags: 文件thepyimport脚本forinputdevice
1条回答
网友
1楼 · 发布于 2024-10-01 00:22:09

您正在使用python2。在python2中,input不仅接受输入,还将其作为python代码进行计算。显然,IP地址不是有效的python代码。因此出现了语法错误

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

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

或者您可以切换到python3

相关问题 更多 >