我正在使用子进程模块,Popen类输出一些结果如:
063.245.209.093.00080-128.192.076.180.01039:HTTP / 1.1 302找到 063.245.209.093.00080-128.192.076.180.01040:发现HTTP / 1.1 302
这是我写的脚本:
import subprocess, shlex, fileinput,filecmp
proc = subprocess.Popen('egrep \'^HTTP/\' *', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,)
stdout_value = proc.communicate()[0]
print 'results:'
print stdout_value
我的问题是:如何将stdout的结果转换/记录到文件中?
感谢您的所有回复和帮助!
答案 0 :(得分:1)
import subprocess
import glob
def egrep(pattern, *files):
""" runs egrep on the files and returns the entire result as a string """
cmd = ['egrep', pattern]
for filespec in files:
cmd.extend(glob.glob(filespec))
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
return proc.communicate()[0]
results = egrep(r'^HTTP/', '*')
print 'results:'
print results
# write to file
with open('result_file.txt', 'w') as f:
f.write(results)
答案 1 :(得分:0)
stdin
的{{1}},stdout
和stderr
个参数中的一个或任何一个可以是subprocess.Popen()
个对象(或文件描述符),使程序读取或写入给定文件。