Android Beginner
Android Beginner

Reputation: 486

sending serial data from python script to node script

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.

Upvotes: 7

Views: 5823

Answers (2)

Nikola M.
Nikola M.

Reputation: 573

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

Upvotes: 6

mr.freeze
mr.freeze

Reputation: 14062

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

Upvotes: 9

Related Questions