How to redirect the output of python script cmd to file?

So I have a python script that prints text to the console and I need it to write to a file instead, but the script is quite complex and I am not coding python, so I would not change it.

I want to do it

>python script.py arg1 arg2 ... argn > "somefile.txt"

      

But it does not work, and I guess that python takes >

and "somefile.txt"

as arguments.

Can this be done and how?

+3


source to share


2 answers


$ (python script.py one two) > test.txt

Or if you want to see the output and write it to a file:

$ python script.py one two | tee test.txt



If this still doesn't write to the file, try redirecting STDERR

:

$ python script.py one two 2>&1 | tee test.txt

+4


source


Add these lines of code to the top of your python file.

import sys
sys.stdout = open('somefile.txt', 'w')

      



This is the sys.stdout parameter for a file object of your choice.

0


source







All Articles