![](/img/trans.png)
[英]How can I get the arguments on a command-line with vanila 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.