Sending serial data from python script to node script

I have two scripts: one python script and another node script. The python script runs in an infinte loop and reads serial data. After receiving the serial data, it should pass it to node.js scipt so that it can be processed on the node server.

I was thinking about using the node.js child_process module to read data from a python script, but since the python script is an infinite loop, it does not return any data in the node script. Can someone please let me know how to solve this problem?

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 to upgrade from a python script is node.js. The serialport module is currently not working for my project due to some problem in the serialport module.

+4
source share
2 answers

After printing, you need to clear the standard output in your python script. Here is an example that prints time (I don't have a serial device for testing):

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

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

 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); }); 
+2
source

Source: https://habr.com/ru/post/1483939/


All Articles