7

I have got two scripts - one python script and another a node script. The python script runs in an infinte loop and reads the serial data. Once it receives the serial data, it has to pass it to node.js scipt so it can be processed in a node server.

I thought of using the node.js child_process module to read the data from the python script but since the python script is a infinite loop, its not returning any data to the node script. Can anyone please let me know how to solve this issue ?

Python script:

import serial
ser = serial.Serial('COM10', 9600, timeout =1)
while 1 :
    print ser.readline()'

Node.js Script:

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

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

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

Note : My only reason for going with python script is node.js serialport module is not working currently for my project due to some issue in serialport module.

1
  • What's the nature of the serial data? A lot? A little? Text? Binary? Commented Jun 1, 2013 at 13:35

2 Answers 2

9

You need to flush the standard output stream in your python script after printing. Here is an example that prints the time (I don't have a serial device to test):

Python:

import sys
from datetime import datetime
from time import sleep
while 1:
    print datetime.now()
    sys.stdout.flush()
    sleep(5)

Node.js:

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

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

ls.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
});
Sign up to request clarification or add additional context in comments.

1 Comment

@nfreeze is there anyway to use this program without using stdout
6

Use -u python command line switch. It will tell python to use unbuffered streams.

var spawn = require('child_process').spawn,
ls    = spawn('python',['-u', 'pyserial.py']);

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.