繁体   English   中英

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

[英]How can I use the subprocess library to call other python files with command-line arguments in a top-level python file?

基本上我有15个左右的脚本可以使用SSH库连接到各种网络设备。 我想创建一个可以运行其他python脚本的顶级python文件,以便用户可以决定他们想要运行哪些脚本。 我被建议使用子进程库,这似乎对我想做的事情最有意义。 重要的是要注意我的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:

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()吗? 我该如何解决这个问题? 谢谢您的帮助!

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

对于python2,你应该使用raw_input - 你可以删除str

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

或者你可以切换到python3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM