Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect python script cmd output to a file?

Tags:

python

cmd

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?

like image 387
Garin GG Avatar asked Aug 04 '17 06:08

Garin GG


People also ask

How do I redirect a command to a file in Linux?

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

How to redirect stdout to a specific filename in Python?

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.

How do I redirect output to a file in Windows?

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.

What is the >> redirection operator used for in command prompt?

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.


2 Answers

$ (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

like image 149
cfeduke Avatar answered Nov 14 '22 23:11

cfeduke


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.

like image 26
Bhargava Bodas Avatar answered Nov 14 '22 23:11

Bhargava Bodas