论坛首页 编程语言技术论坛

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

浏览 4202 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-01-10   最后修改:2011-01-10

环境: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()
 

问题解决。

   发表时间:2011-07-01  
python -u xxx.py > log.log &
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics