您可以使用subprocess.Popen看到輸出和寫入文件:
from subprocess import Popen, PIPE
print("""What did you want to run? (pick a number)
(1) Ping
(2) Traceroute""")
runit = raw_input("> ")
print ("Enter a hostname to check")
host = raw_input("> ") #accept input for hostname
if runit == "1":
p = Popen("cmd /c ping " + host, shell=True, stdout=PIPE)
with open("ping.txt","w") as f:
for line in iter(p.stdout.readline,""):
print(line)
f.write(line)
elif runit == "2":
p = Popen("cmd /c tracert " + host, shell=True, stdout=PIPE)
with open("trace.txt", "w") as f:
for line in iter(p.stdout.readline, ""):
print(line)
f.write(line)
爲了保持代碼乾燥,並允許用戶重新選擇,如果他們選擇了錯誤的選擇,你可以使用while循環與str.format用字典,以保持選項:
from subprocess import Popen, PIPE
opts = {"1": "ping", "2": "tracert"}
while True:
print("""What did you want to run? (pick a number)
(1) Ping
(2) Traceroute""")
runit = raw_input("> ")
if runit in opts:
host = raw_input("Enter a hostname to check\n> ") # accept input for hostname
p = Popen("cmd /c {} {}".format(opts[runit], host), shell=True, stdout=PIPE)
with open("ping.txt", "w") as f:
for line in iter(p.stdout.readline, ""):
print(line)
f.write(line)
break
print("Invalid option")
你的意思是將輸出寫入文件? –
是的,我想讓命令在命令提示符下運行,然後將它寫入文件以供稍後查看。 – Matt
[python的可能重複將shell命令的輸出保存到文本文件](http://stackoverflow.com/questions/20421187/python-save-the-output-of-a-shell-command-into-a - 文本文件) – skrrgwasme