从python派生子进程接收连续输出不起作用 [英] Receiving contiinuous output from python spawn child process not working

查看:89
本文介绍了从python派生子进程接收连续输出不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以python编写的秤的流输出。该程序(scale.py)连续运行并每半秒打印一次原始值。

I am attempting to stream output from a weighing scale that is written in python. This program (scale.py) runs continuously and prints the raw value every half second.

import RPi.GPIO as GPIO
import time
import sys

from hx711 import HX711

def cleanAndExit():
    print "Cleaning..."
    GPIO.cleanup()
    print "Bye!"
    sys.exit()

hx = HX711(5, 6)

hx.set_reading_format("LSB", "MSB")

hx.reset()
hx.tare()

while True:
    try:
        val = hx.get_weight(5)
        print val

        hx.power_down()
        hx.power_up()
        time.sleep(0.5)
    except (KeyboardInterrupt, SystemExit):
        cleanAndExit()

我正在尝试在单独的NodeJs程序中获取每个原始数据点(位于index.js在同一文件夹中),由 print val 打印。这是我的节点程序。

I am trying to get each raw data point in a separate NodeJs program (index.js located in the same folder) that is printed by print val. Here is my node program.

var spawn = require('child_process').spawn;
var py = spawn('python', ['scale.py']);

py.stdout.on('data', function(data){
  console.log("Data: " + data);
});

py.stderr.on('data', function(data){
  console.log("Error: " + data);
});

当我运行 sudo node index.js 没有输出,程序永久等待。

When I run sudo node index.js there is no output and the program waits into perpetuity.

我的思维过程是 print val 应该将输出放入stdout流中,这会触发<$ c $节点程序中的c> data 事件。

My thought process is that print val should put output into stdout stream and this should fire the data event in the node program. But nothing is happening.

谢谢您的帮助!

推荐答案

默认情况下,所有使用libc的C程序(包括用C语言编写的CPython)在连接到管道时都会自动缓冲控制台输出。

By default, all C programs (CPython included as it is written in C) that use libc will automatically buffer console output when it is connected to a pipe.

一种解决方案是每次需要时刷新输出缓冲区:

One solution is to flush the output buffer every time you need:

print val
sys.stdout.flush()

另一种解决方案是使用 -u 标志调用python

Another solution is to invoke python with the -u flag which forces it to be unbuffered:

var py = spawn('python', ['-u', 'scale.py']);

这篇关于从python派生子进程接收连续输出不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆