evanooruvan
evanooruvan

Reputation: 115

python subprocess print and store stdout

I am learning python and writing a small script. 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.PIPEi could not figure out outputting to both.please forgive me for this silly question`

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

Upvotes: 0

Views: 75

Answers (2)

tdelaney
tdelaney

Reputation: 77337

It looks like you are only using subprocess to run grep, but python can do grep-like matches of strings too. This program will read the lines in "testfile" and then write out lines from "log" that contain the testfile line. 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.

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)

Upvotes: 1

Cole Arseneau
Cole Arseneau

Reputation: 104

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.

Upvotes: 0

Related Questions