下面是死的简单代码:
import logging
import requests
logging.basicConfig(level=logging.DEBUG)
res = requests.get('https://www.stackoverflow.com')
像 python ./test.py > foo.txt 一样运行将所有内容发送到 stderr。为什么这不会输出到标准输出?
请您参考如下方法:
logging.basicConfig 在没有handler/filename/stream 时使用StreamHandler给定参数,StreamHandler默认为STDERR流:
class StreamHandler(Handler):
def __init__(self, stream=None):
"""
Initialize the handler.
If stream is not specified, sys.stderr is used.
"""
Handler.__init__(self)
if stream is None:
stream = sys.stderr # <- Here
self.stream = stream
要使用 STDOUT,将 sys.stdout 作为 stream 传递:
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
现在,正如您目前所做的那样,您可以像这样从 shell 中捕获 STDERR:
python ./test.py 2> foo.txt
因此重定向文件描述符 2(即 STDERR)就可以了。
STDOUT 是文件描述符 1,当您进行裸重定向 > 时,假定为 1>。
如果出于某种原因你想使用不同的文件来重定向两个流,你可以这样做:
python ./test.py >stdout.txt 2>stderr.txt
如果你想将两者重定向到同一个文件:
python ./test.py >all.txt 2>&1 # POSIX
或
python ./test.py &>all.txt # `bash`-ism (works in other advanced shells as well)
