[英]python subprocess print and store stdout
我正在学习 python 并编写一个小脚本。 我需要我的输出在一个文件中,并且也在屏幕上打印输出。我尝试了各种方法,比如stdout=subprocess.PIPE
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 的字符串匹配。 该程序将读取“testfile”中的行,然后从“log”中写出包含 testfile 行的行。 “testfile”中第一行的所有日志匹配将高于第二行的匹配,等等......匹配多个测试文件行的日志行将输出多次。
此代码假定您不匹配正则表达式。
#!/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 文件追加而不是写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.