为什么 grep 忽略“python3 -m http.server”输出的第一行?

Why grep ignores the first line of "python3 -m http.server" output?

提问人:Marinos An 提问时间:10/5/2023 更新时间:10/5/2023 访问量:48

问:

由于某种原因,grep 不会打印命令输出的第一行:

python3 -m http.server

python3 -m http.server
# prints: Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...


python3 -m http.server | grep -E .
# nothing is printed


python3 -m http.server 2>&1 | grep -E .
# nothing is printed

但是,如果我执行请求,我可以看到其余的日志(但不是第一行):

127.0.0.1 - - [05/Oct/2023 11:07:28] "GET / HTTP/1.1" 200 -

为什么会这样?有没有办法用grep打印第一行?(注意:管道到tail)

bash grep stdin io-重定向

评论


答:

1赞 matleg 10/5/2023 #1

似乎python stdout和stderr默认是缓冲的,请尝试:

PYTHONUNBUFFERED=x python3 -m http.server 2>&1 | grep -E .