Q:

Is it possible to export all the command line output to a file without manually redirecting via > symbol?

I have a python (2.7) script that has various print statements and other things. Now, I want to export the entire command-line output to a file. As most people know, this is very easy to do manually using the below command:  
script.py > file.txt
But I want to make > file.txt also as a part of my python script itself instead of having to redirect manually every time the script is run.
I tried using the with command but it only exports a specific object out into a file but not all the print statements, dataframes, and etc.
Is there a way to achieve this? I'm not well-versed in unix or python. Can someone please help me with some ideas?
Thanks in advance.

A:

you can use the sys module and add the following line at the begin of your code:
import sys
sys.stdout = open('file.txt', 'w')

