【问题标题】:Python3 http.server : save log to a filePython3 http.server:将日志保存到文件
【发布时间】:2017-10-10 11:21:47
【问题描述】:

我使用Python3.6编写了一个简单的HTTP服务器来重定向所有请求。

我写的文件可以找到here

我可以在 Win8.1 CMD 和 Ubuntu 16.04.3 Bash 中看到输出。 但是,无论我尝试以下任何一种方法,它都不起作用,日志无法保存到文件中。

nohup python3 ./filename.py > ./logfile 2>&1 &
python3 ./filename.py > ./logfile 2>&1 &
setsid ./filename.py > ./logfile 2>&1 &

我尝试使用:

import sys
logfile = open('logfile.log','w')
sys.stdout = logfile
sys.stdin = logfile
sys.stderr = logfile

没用。

【问题讨论】:

  • “没用”是什么意思?如果您在服务器运行时尝试读取文件,则输出可能尚未刷新
  • 不。我的意思是我尝试运行它,几个小时后,日志文件仍然是空的。我必须看到这样的日志 > 2017/1/1 GET / - 301 。但是,我在日志文件中看不到任何内容。

标签: python bash python-3.x stdout


【解决方案1】:

默认情况下,Python 的 stdout 和 stderr 是缓冲的。正如其他响应者所指出的,如果您的日志文件为空,那么(假设您的日志记录是正确的)输出还没有被刷新。

脚本的链接不再有效,但您可以尝试以python3 -u filename.py 或等效的PYTHONUNBUFFERED=x python3 filename.py 运行您的脚本。这会导致 stdout 和 stderr 流没有缓冲。

使用标准库的http.server 模块从当前目录提供文件的完整示例:

PYTHONUNBUFFERED=x python3 -m http.server &> http.server.log & echo $! > http.server.pid

所有输出(stdout & stderr)都重定向到http.server.log,可以加尾,服务器的进程ID写入http.server.pid 这样你就可以通过kill $(cat http.server.pid) 杀死进程。

【讨论】:

    【解决方案2】:

    我已经在 Ubuntu 16.04 上尝试过你的代码,它的工作原理非常棒。

    import sys
    logfile = open('logfile.log','w')
    sys.stdout = logfile
    sys.stdin = logfile
    sys.stderr = logfile
    

    【讨论】:

    • 请看这里的截图。也许是缺少一些依赖? i.loli.net/2017/10/11/59dd7aa56f3ca.jpg
    • @PotatoChips 你读过 nohup 的手册页吗? nohup 重定向远离终端,因此尝试将剩余的输出(其中没有输出)引导到日志文件中不会在该日志文件中为您提供任何内容。而在另一种情况下,您的服务器仍在运行,因此它可能没有被刷新。所以在没有 nohup 的情况下运行它并关闭它,然后检查输出。如果您需要在服务器运行时读取日志,请确保正在刷新输出。
    • 我试图在没有 nohup 的情况下运行,几个小时后我终止了进程。日志文件仍然是空的。
    猜你喜欢
    • 2017-09-25
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    相关资源
    最近更新 更多