简体   繁体   English

python子进程打印和存储标准输出

[英]python subprocess print and store stdout

I am learning python and writing a small script.我正在学习 python 并编写一个小脚本。 I need my output to be in a file and also print the output on the screen as well.I tried various methods like stdout=subprocess.PIPE i could not figure out outputting to both.please forgive me for this silly question`我需要我的输出在一个文件中,并且也在屏幕上打印输出。我尝试了各种方法,比如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)

It looks like you are only using subprocess to run grep, but python can do grep-like matches of strings too.看起来您只是使用子进程来运行 grep,但是 python 也可以进行类似 grep 的字符串匹配。 This program will read the lines in "testfile" and then write out lines from "log" that contain the testfile line.该程序将读取“testfile”中的行,然后从“log”中写出包含 testfile 行的行。 All of the log matches from the first line in "testfile" will be above the matches for the second line, etc... And log lines that match multiple testfile lines will output multiple times. “testfile”中第一行的所有日志匹配将高于第二行的匹配,等等......匹配多个测试文件行的日志行将输出多次。

This code assumes that you are not matching a regular expression.此代码假定您不匹配正则表达式。

#!/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)

Try this:尝试这个:

#!/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)

I made your aaa.txt file append rather than write.我让你的 aaa.txt 文件追加而不是写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM