2011-10-07 16 views
2

我有一个简单的Python脚本,我想在后台运行,输出重定向到一个文件,例如带有sleep()语句的Python脚本在后台运行时不记录

./test.py > output.log 2>&1 & 

此,只要有我的Python脚本没有sleep语句正常工作:

#! /usr/bin/env python 

import sys 
import time 
from time import gmtime, strftime 

urls=['http://a', 'http://b','http://c', 'http://d', 'http://e' ] 

def main(): 
    while True: 
     for url in urls: 
      try: 
       print url 
      except Exception, e: 
       print "Error checking url " + url 
       print e 
     #time.sleep(60) 


if __name__ == '__main__': 
    main() 

如果睡眠语句注释掉那么当脚本在后台运行不产生输出。

如果它在前台运行,它可以正常工作(有睡眠),并且输出会按照我的选择发送到控制台或文件。

例如这始终工作:

./test.py > output.log 

我的问题是,为什么有睡眠声明防止被引向当脚本在后台运行到文件输出,以及我怎样才能避免这种情况发生?

回答

3

输出不会丢失,只需要很长时间才能到达文件。这与缓冲有关:对于sleep,输出缓冲区需要很长时间来累积足够的数据才能刷新。

如果你只是打电话sleep()之前调用sys.stdout.flush(),这会使得输出立即显示:

sys.stdout.flush() 
    time.sleep(60) 
1

我还没有尝试过,但在发送脚本进入睡眠之前,您可以尝试使用sys.stdout.flush()