2

I have written a server in node.js on Raspberry Pi. I want to run a python script from it but it does not execute the line. On previous instances, I have run files but coming to this instance of socket.io I can't run the file! Though the console shows accurate output passed to it from the client but it fails to read the file. The socket is responsible for movement.

/*jshint esversion: 6 */
var express = require('express');
// library for executing system calls
const spawn = require('child_process').spawn;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);
var colour = require('colors');
var ip = require('ip');
var PortNumber = 3000;
var xPos = 0, yPos = 0;
server.listen(PortNumber);
app.use(express.static('public'));
io.sockets.on('connection', function (socket) {
 socket.emit('ip', {value: 'http://' + ip.address() + ':8081'});
 // otp generation socket
 socket.on('userEmail', function (data) {
 var userEmail = data.value;
 // system call to generate OTP
 const OTPgeneration = spawn('python', [__dirname + '/python/OTPgeneration.py', userEmail]);
 OTPgeneration.stdout.on('data', (data) => {
 console.log(`${data}`);
 });
 });
 // otp submit button socket
 socket.on('userOtp', function (data) {
 var userOtp = data.value;
 console.log(userOtp);
 // system call to generate OTP
 const otpValidate = spawn('python', [__dirname + '/python/OTPvalidation.py', userOtp]);
 otpValidate.stdout.on('data', (data) => {
 console.log(`${data}`);
 // Get last output from python file
 var lastChar = `${data}`.slice(-2);
 if (lastChar === '0\n') {
 console.log('Wrong OTP');
 }
 else io.sockets.emit('otpConformation', {value: 'confirm'}); //sends the confirmation to all connected clients
 });
 });
 // x y values socket
 socket.on('servoPosition', function (data) {
 servoPosition = data.value;
 // servoPosition[0] is x and servoPosition[1] is y
 console.log('Reveived X: ' + servoPosition[0] + ' Y: ' + servoPosition[1]);
 // system call for i2c comminication
 const i2cData = spawn('python', [__dirname + '/python/sendI2C.py', servoPosition[0], servoPosition[1]]);
 i2cData.stdout.on('data', (data) => {
 console.log(`${data}`);
 });
 });
 // movement socket
 socket.on('movement', function (data) {
 var m = data.value;
 console.log("Movement :" + m);
 const submitMove = spawn('python', [__dirname + '/python/move.py', m]);
 submitMove.stdout.on('data', (data) => {
 console.log(`${data}`);
 });
 });
});
console.log('Server Running @'.green + ip.address().green + ":3000".green);
function readTextFile(file) {
 var rawFile = new XMLHttpRequest();
 //var rawFile = new XMLHttpRequest();
 rawFile.open("GET", file, false);
 rawFile.onreadystatechange = function () {
 if(rawFile.readyState === 4) {
 if(rawFile.status === 200 || rawFile.status === 0) {
 allText = rawFile.responseText;
 //alert(allText);
 }
 }
 };
 rawFile.send(null);
}
asked Apr 9, 2017 at 1:46
3
  • 1
    What do stderr and the exit code contain when the command fails? Commented Apr 9, 2017 at 2:17
  • right - please add these sections as well, along with stdout callback: OTPgeneration.stderr.on('data', (data) => { console.log(${data}); }); OTPgeneration.on('close', (code) => { console.log(${code}); }); Commented Apr 9, 2017 at 3:49
  • the above code works fine , as per requirement . the socket module doesnt work as expected.the node never excutes the python move.py script.even the console here at the movement sockets works fine.. Commented Apr 9, 2017 at 4:41

2 Answers 2

3

While using Node's native "child_process" module is the most performant option, it can be tedious in getting it to work. A quick solution is to use the node-cmd module. Run npm i node-cmd --save to install it. Import it via var cmd = require('node-cmd'); at the top of your server file. Then,

var pyProcess = cmd.get('python YOURPYTHONSCRIPT.py',
 function(data, err, stderr) {
 if (!err) {
 console.log("data from python script " + data)
 } else {
 console.log("python script cmd error: " + err)
 }
 }
 );

Editing as needed. node-cmd has 2 methods which invoke it, get and run. run simply runs the provided CLI command whereas get provides the use of a callback allowing for better error handling and makes working between stdin, stdout, stderr much easier.

answered Apr 9, 2017 at 5:06
Sign up to request clarification or add additional context in comments.

Comments

0

Consider using a package instead of dealing with spawning processes by your self. you can check this package on npm that i created- native-python

it provides a very simple and powerful way to run python functions from node might solve your problem.

import { runFunction } from '@guydev/native-python'
const example = async () => {
 const input = [1,[1,2,3],{'foo':'bar'}]
 const { error, data } = await runFunction('/path/to/file.py','hello_world', '/path/to/python', input)
 // error will be null if no error occured.
 if (error) {
 console.log('Error: ', error)
 }
 else {
 console.log('Success: ', data)
 // prints data or null if function has no return value
 }
}

python module

# module: file.py
def hello_world(a,b,c):
 print( type(a), a) 
 # <class 'int'>, 1
 print(type(b),b)
 # <class 'list'>, [1,2,3]
 print(type(c),c)
 # <class 'dict'>, {'foo':'bar'}
answered Dec 5, 2022 at 22:43

1 Comment

It looks like you are promoting your own work. Please see the instructions on self-promotion: "you must disclose your affiliation in your post."

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.