python - 如何使用子进程库在顶级 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() 对吗?我该如何解决这个问题?谢谢您的帮助!
解决方案
您正在使用 python2。在 python2 中,input
不仅接受输入,还将其评估为 python 代码。显然 IP 地址不是有效的 python 代码。因此语法错误。
对于 python2,您应该使用raw_input
- 并且您可以删除str
.
deviceIP = raw_input("Enter the IP address for the device")
或者你可以切换到python3
推荐阅读
- node.js - 无效登录:535-5.7.8 不接受用户名和密码
- node.js - run start:dev 同时失败意外的标识符
- android - 为什么在改造中使用带有参数的POST方法在字符串中自动Atteched“\\”?
- python - 使用 python (MAC OSX) 和 PyCharm IDE 安装 OpenCV 时出错
- sitecore - 我无法在 sitecore 中选择内容项
- javascript - 谷歌电子表格获取/更新列'A'等于id的行
- python - Power BI:多个表作为 Power Query 中 Python 的输出
- java - 我无法提取正确的 xpath ,可以帮助我
- python - Python中的递归字符串比较
- php - 使用ajax填充3个下拉列表,一个接一个