python将shell命令的输出保存到文本文件中

时间:2013-12-06 10:08:21

标签: python shell

我想通过python将shell命令的输出保存到文本文件中。这是我实际的,非常基本的python代码:

修改 这是最终的脚本,感谢您的帮助:)

import subprocess

ip_adress_4 = 0    
pr = open("pointer_record.txt", "w")

while (ip_adress_4 < 255):
    ip_adress_4 = ip_adress_4 + 1
    ip_adress = '82.198.205.%d' % (ip_adress_4,)
    subprocess.Popen("host %s" % ip_adress, stdout=pr, shell=True)

2 个答案:

答案 0 :(得分:9)

尝试这样的事情:

import subprocess
file_ = open("ouput.txt", "w")
subprocess.Popen("ls", stdout=file_)

编辑:符合您的需求

import subprocess

file_ = open("ouput.txt", "w")
subprocess.Popen(["host", ipAddress], stdout=file_)

答案 1 :(得分:2)

使用subprocess.check_output代替Popen这将为您提供一个包含输出的字符串,然后您可以将其写入文件。

相关问题