关于python中stdout的缓冲区问题

最近做了一个项目,以node.js搭的后端并在里面调用python脚本。由于想追踪脚本执行进度,于是使用stdout返回data进行监听。

const spawn = require('child_process').spawn
	const py = spawn('python', ['./elec_predict/elec_predict.py'])
	

	py.stdout.on('data', (res)=>{
			console.log("开始监听",res.toString())
		})

但是每次都不能实时返回数据,而是一下子返回很多个数据。

后来查询资料发现,这是因为python中stdout有一个缓冲区,存够一定多个数据才会将数据返回,所以我们只需要用flush刷新缓冲区即可在服务器中获得实时数据。

import threading
import time
import sys
import json


# run函数
def run():
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),flush=True) # 输出当地时间
    # print(json.dumps(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))  # 输出当地时间
	#sys.stdout.flush()
    timer = threading.Timer(1, run)  # 设置一个定时器,循环输出时间
    timer.start()  # 启动线程


run()

 

 可在print中后面加上flush=True

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值