2016-05-17 164 views
0

本質上,我想創建一個有多個選擇的腳本來檢查主機名上的某些數據。例如,此處的代碼可以選擇在給定主機名上ping或運行tracert如何使用Python將命令從命令提示符寫入文件?

import os 

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": 
    os.system("cmd /c ping " + host) 
elif runit == "2": 
    os.system("cmd /c tracert " + host) 

上述工程的代碼,我可以得到的結果和手動複製他們,但我想這是自動完成的。我知道我可以使用類似

p = open("ping1.txt", "w") 

打開文件,但我不知道如何複製跟蹤或命令提示符下平的結果嗎?任何幫助,將不勝感激。

+0

你的意思是將輸出寫入文件? –

+0

是的,我想讓命令在命令提示符下運行,然後將它寫入文件以供稍後查看。 – Matt

+0

[python的可能重複將shell命令的輸出保存到文本文件](http://stackoverflow.com/questions/20421187/python-save-the-output-of-a-shell-command-into-a - 文本文件) – skrrgwasme

回答

0

您可以使用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") 
+0

是的,這工作正如我所希望的。非常感謝!仍然有點不熟悉像shell = 1,stdout = PIPE這樣的子進程參數,但是我找到了該頁面,並且會對其進行更多的瞭解。我瞭解其餘,並感謝它! – Matt

+0

不用擔心,通常你可以通過傳遞一個沒有設置shell = True的單個參數列表,但我不會使用windows,所以我不太確定它是否會,因爲我知道一些命令需要shell = True使用窗口 –

+0

1-您可以使用'stdout = file'代替2-不需要重複代碼。與[this](http://stackoverflow.com/a/37311520/4279) – jfs

0

os.system(command)在子shell執行命令,並返回最系統(至少對於CMD.EXE)在其退出狀態。

subprocess模塊非常適合做不止於此的任何事情。

您可能想要使用subprocess.check_output,它使用參數運行該命令並將其輸出作爲字節字符串返回。

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)` 
+0

一旦將輸出作爲字節字符串,其餘部分應該是微不足道的。儘管'subprocess.check_output()'可能不適合,如果命令不保證'ping',如果你不指定'-c count' 。那麼Padraic Cunningham提出的解決方案更好! –

-1

要將命令的輸出重定向到一個文件,你可以傳遞stdout參數subprocess.check_call()

#!/usr/bin/env python2 
import subprocess 

one_or_two = raw_input("""What did you want to run? (pick a number) 
     (1) Ping 
     (2) Traceroute 
> """) 
command = ["", "ping", "tracert"][int(one_or_two)] 
host = raw_input("Enter a hostname to check\n> ") 

with open('output.txt', 'wb', 0) as file: 
    subprocess.check_call([command, host], stdout=file) 

如果你想顯示除了在控制檯輸出複製輸出到一個文件,見Displaying subprocess output to stdout and redirecting it