在无限运行的python脚本中重定向输出

时间:2013-06-20 12:41:00

标签: python

我有一个python脚本,它具有while(1)条件,从数据库中的表中获取输入 处理它并将内容写入stdout,但我无法将其输出重定向到文件。我尝试了所有标准方法,但发现可能因为脚本永远不会停止而且我必须 使用Ctrl-Z停止将stdout的输出附加到文件是不合格的。
任何线索??

3 个答案:

答案 0 :(得分:2)

我猜它从未写过换行符?如果这是真的,您需要偶尔sys.stdout.flush()

答案 1 :(得分:1)

您还可以使用-u选项禁用I / O缓冲:python -u yourscript.py。 (在某些情况下,这会降低性能。)

答案 2 :(得分:0)

尝试使用

    orig_stdout = sys.stdout
    completeName = os.path.abspath("**Path name of the file**")
    f = file(completeName, 'w')
    sys.stdout = f
    print "Whatever you want to put into file"
    sys.stdout = orig_stdout
    f.close()