`
houzhaowei
  • 浏览: 493122 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

后台运行python程序 遇到缓冲区问题

阅读更多

环境:linux

 

一段执行时间很长的程序(用python做hive客户端执行mapreduce) 在linux后台执行,把结果输出到某文件:

 

 

python xxx.py > log.log& 

 

 遇到的问题,程序没报错,文件里却什么都没有,没有输入进去。为什么呢?

于是我首先尝试用:

 

 

nohup python xxx.py > log.log &

 

预料之中 还是不行。

 

于是我做实验:

 

写了个test.py:

 

import sys,time
from threading import Thread
class worker(Thread):
     def run(self):
         for x in xrange(0,111):
             print x
             time.sleep(1)
def run():
     worker().start()
if __name__ == '__main__':
    run()

 每秒打印一次

我直接用python text.py 执行  没问题  每秒输出一个数

但我在后台执行:

 

python test.py > log.log& 

 

还是不行。开始不输出  直到程序执行完,一次性的写到log.log文件了。

为什么呢? 

原因可能是python 的print 先写到缓冲区了,还没flush到文件。

于是加了一行“ sys.stdout.flush() ” --在每次print后都flush一次。:

 

import sys,time
from threading import Thread
class worker(Thread):
     def run(self):
         for x in xrange(0,111):
             print x
             sys.stdout.flush()  
             time.sleep(1)
def run():
     worker().start()
if __name__ == '__main__':
    run()
 

问题解决。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics