最近做了一个项目,以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