Python. Redirect stderr to log file

2019-07-29 15:27发布

问题:

I have Django web-site working on tornado and nginx.

I took this tornado launcher script (tornading.py)

Then I'm using python openid that outputs some information to sys.stderr.

As a result I get IOError.

How can I redirect it using logging package?

I thought about

f = open("myfile.log", "w")
sys.stderr = f

or

python tornado.py > /dev/null 2>&1

But what is the best way to solve it?

回答1:

The best way would be if the openid library didn't print to stderr, but used some kind of logging API instead (e.g. the logging module). I agree with thkala that modifying third-party code is not good in the long term, so you should fix it, and then provide the fix to the openid authors.

For the objective of advancing the open source community, that's the best way to solve it.



回答2:

Using shell redirections is more of a work-around than a solution and it may not be always possible, depending on how the script is launched.

It has the distinct advantage, however, of you not having to modify third-party code. Local modifications - even minor ones - can become a major issue when you decide to e.g. update said code to its latest version from upstream.