So I have a python script that outputs text to the console and I need that logged to a file instead, but the script is quite complex and I don't code python, so I would rather not alter it.
I want to do this
>python script.py arg1 arg2 ... argn > "somefile.txt"
But it won't work, and my guess is that python takes > and "somefile.txt" as arguments..
Can this be achieved and how?
4 Answers 4
$ (python script.py one two) > test.txt
Or if you want to see the output and also write it to a file:
$ python script.py one two | tee test.txt
If this still isn't writing to the file, try redirecting STDERR:
$ python script.py one two 2>&1 | tee test.txt
4 Comments
tee command. You can install one, but you didn't ask about that anyway. Just redirect stdout via >somefile.txt and redirect stderr to stdout (i.e. the same file) via 2>&1.$ and didn't even think about Windows. If you are using Cygwin it may include tee (dunno, its been years).Add these lines of code to the beginning of the python file.
import sys
sys.stdout = open('somefile.txt', 'w')
This is setting the sys.stdout to a file object of your choice.
Comments
Since the script is not yours, my guess is that it uses python logging module. If this is the case then you just need to reconfigure the logging module to use stdout. See https://stackoverflow.com/a/28194953/292787 for how to do it.
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
Comments
Use:
python script.py arg1 arg2 ... argn >> somefile.txt
python script.py ... > somefile.txt 2>&1doesn't work, then the script is writing directly to the console instead of stdout or stderr.