how to redirect "print" command output to a file without changing the python code?

Viewed 2686

I want to redirect all the output of my django (1.10.4) app to a file

Firstly, I tried:

python manage.py runserver 0.0.0.0:8000 >test.log 2>&1

But it doesn't redirect the output of the print command.

For example, in my code there is a statement:

print ('query_content:')

using command:

python manage.py runserver 0.0.0.0:8000

I can see that 'query_content:' is printed out on the screen.

But with :

python manage.py runserver 0.0.0.0:8000 >test.log 2>&1

In the test.log, there are only something like this:

[05/Nov/2017 20:38:20] "GET ... HTTP/1.1" 200 22404
[05/Nov/2017 20:38:26] "POST ... HTTP/1.1" 200 13
[05/Nov/2017 20:38:26] "GET .... HTTP/1.1" 200 16800
[05/Nov/2017 20:38:30] "GET ... 200 22430
...

One solution is:

import sys
sys.stdout = open('file', 'w')
print 'test'

But sometimes it is impossible to change the python code, is there any solution?

update:

I found that if the log file already exists, then everything is fine. But if I specify a new file name, then the output of python "print ..." statement cannot save the log file.

3 Answers
Related