【发布时间】:2012-06-21 20:21:48
【问题描述】:
我在我的代码中使用 python-daemon,其中包含打印语句。我想将它们发送到一个文件,所以我运行了以下命令:
python server.py >> log.out
但是,log.out 中没有任何内容。
谁能告诉我我需要做什么?
谢谢。
【问题讨论】:
-
你能给我们看一些示例代码吗?
我在我的代码中使用 python-daemon,其中包含打印语句。我想将它们发送到一个文件,所以我运行了以下命令:
python server.py >> log.out
但是,log.out 中没有任何内容。
谁能告诉我我需要做什么?
谢谢。
【问题讨论】:
DaemonContext 对象允许在您创建对象时重定向 stdout/stderr/stdin。例如:
import os
import daemon
if __name__ == '__main__':
here = os.path.dirname(os.path.abspath(__file__))
out = open('checking_print.log', 'w+')
with daemon.DaemonContext(working_directory=here, stdout=out):
for i in range(1, 1000):
print('Counting ... %s' % i)
您应该能够cat checking_print.log 并查看打印语句的输出。
DaemonContext 对象的一个很好的参考是PEP 3143。
【讨论】:
如果您的代码中有错误,则不会将其写入文件。见http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html
尝试创建这个文件:
print 'stdout'
raise Exception('stderr')
【讨论】:
如果它已经作为守护进程运行,您很可能需要强制重定向 STDOUT、STDERR 等。您可以在 I/O Redirection here 上阅读更多信息。
python server.py 2>log.out >&2
【讨论】: