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?
There are two ways you can redirect standard output of a command to a file. The first is to send the command output write to a new file every time you run the command. To do this, open the command prompt and type: dir test.exe > myoutput.txt
The greater than character (i.e. >) tells your operating system to redirect stdout to the filename you specified. At this point you should have a file named "redirected.txt" in the same folder as your Python script.
You can redirect output to a file in Windows for both of these output streams. There are two ways you can redirect standard output of a command to a file. The first is to send the command output write to a new file every time you run the command.
A LOG File of Command Prompt Results. The >> redirection operator is useful when you're collecting similar information from different computers or commands and you'd like all of that data in a single file. The above redirection operator examples are within the context of Command Prompt, but you can also use them in a BAT file.
$ (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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With