如何使用Python将命令从命令提示符写入文件?

时间:2016-05-17 21:55:18

标签: python windows subprocess

基本上,我想创建一个具有多个选项的脚本来检查主机名上的某些数据。例如,此处的代码可以选择在给定主机名上ping或运行tracert

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")

但我不确定如何从命令提示符复制跟踪或ping的结果?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分: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)

为了保持代码干燥并允许用户选择错误的选项,您可以使用带有 str.format 的while循环和dict来保留选项:

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")

答案 1 :(得分:0)

os.system(command)在子shell中执行命令并在大多数系统上返回其退出状态(至少对于cmd.exe)。

subprocess模块非常适合做更多的事情。

您可能希望使用subprocess.check_output运行带参数的命令,并将其输出作为字节字符串返回。

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

答案 2 :(得分:-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