如何使用 Python 从命令提示符将命令写入文件?
How do I write a command from Command Prompt to a file using Python?
本质上,我想创建一个具有多种选择的脚本来检查主机名上的某些数据。例如,此处的代码将有一个选项可以在给定的主机名上执行 ping 操作或 运行 a 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 的结果?任何帮助将不胜感激。
您可以使用 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)
为了保持代码干爽,并允许用户在 select 错误选择时再次选择,您可以使用带有 str.format 的 while 循环用字典来保留选项:
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")
os.system(command)
在子 shell 中执行命令并且 return 在大多数系统上设置它的退出状态(至少对于 cmd.exe)。
subprocess 模块非常适合做更多的事情。
您可能想使用 subprocess.check_output 运行带参数的命令,return 其输出为字节字符串。
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)`
要将命令的输出重定向到文件,您可以将 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。
本质上,我想创建一个具有多种选择的脚本来检查主机名上的某些数据。例如,此处的代码将有一个选项可以在给定的主机名上执行 ping 操作或 运行 a 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 的结果?任何帮助将不胜感激。
您可以使用 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)
为了保持代码干爽,并允许用户在 select 错误选择时再次选择,您可以使用带有 str.format 的 while 循环用字典来保留选项:
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")
os.system(command)
在子 shell 中执行命令并且 return 在大多数系统上设置它的退出状态(至少对于 cmd.exe)。
subprocess 模块非常适合做更多的事情。
您可能想使用 subprocess.check_output 运行带参数的命令,return 其输出为字节字符串。
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)`
要将命令的输出重定向到文件,您可以将 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。