python子进程打印并存储stdout



我正在学习python并编写一个小脚本。我需要我的输出在一个文件中,还需要在屏幕上打印输出。我尝试了各种方法,比如stdout=subprocess.PIPE,我无法同时输出。请原谅我这个愚蠢的问题`

#!/usr/bin/python
import os
import subprocess
with  open('/root/test/testfile') as f , open('aaa.txt',"w") as final:
content =  f.read().splitlines()
for x in content:
result= subprocess.Popen(['grep',x,'/news/today/night/logs'],stdout=final)

看起来您只是在使用子流程来运行grep,但python也可以进行类似grep的字符串匹配。该程序将读取"0"中的行;测试文件";然后从";log";包含测试文件行的。从"0"中的第一行开始的所有日志匹配;测试文件";将在第二行的匹配项之上,等等。与多个测试文件行匹配的日志行将多次输出。

此代码假定您没有匹配正则表达式。

#!/usr/bin/python
# assuming logs is not too big, you could read it into memory once
# with open('/news/today/night/logs') as logfile:
#     logs = list(logfile)

with  open('/root/test/testfile') as f , open('aaa.txt',"w") as final:
for wanted in f:
wanted = wanted.strip()
with open('/news/today/night/logs') as logs:
for log in logs:
if wanted in log:
print(log, end='')
final.write(log)

试试这个:

#!/usr/bin/python
import os
with open('/root/test/testfile') as f, open('/root/test/aaa.txt',"a") as final:
content = f.read().splitlines()
for line in content:
if "/news/today/night/logs" in line:
print(line)
final.write(line)

我让你的aaa.txt文件附加而不是写入。

最新更新