后台运行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()
 

问题解决。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值