0

I have a script (let's call it test.py) that writes to the console while running. In a command line I could use "python test.py >> a.txt" to have it write to a file.

How can I achieve the same from within another (foo.py) script, where I'm using os.system("test.py") to call the first script?

1 Answers1

0

Consider piping the standard output of your first program (e.g. writer.py) into your second program (e.g. reader.py), and have the second program read from standard input. Then, redirect the output of the second program to a file.

writer.py

#!/usr/bin/env python

for i in range(0, 10):
    print("Line {}".format(i))

reader.py

#!/usr/bin/env python

import fileinput

for line in fileinput.input():
    print("Hello - " + line.rstrip())

In the console, you can simply use | to pipe the output of writer.py to reader.py, and > to write the output of reader.py to a file:

➜ ./writer.py | ./reader.py > output.txt
Hello - Line 0
Hello - Line 1
Hello - Line 2
Hello - Line 3
Hello - Line 4
Hello - Line 5
Hello - Line 6
Hello - Line 7
Hello - Line 8
Hello - Line 9
Pierre
  • 1,068
  • 1
  • 9
  • 13