Receiving contiinuous output from python spawn child process not working

北城以北 提交于 2020-02-06 07:29:46

问题


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()

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);
});

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

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.

Thanks for your help!


回答1:


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()

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

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


来源:https://stackoverflow.com/questions/49947402/receiving-contiinuous-output-from-python-spawn-child-process-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!