John John - 9 days ago 5
Node.js Question

How to insert variable from NodeJs into a python script?

I am using

python-shell
to run my python script within my NodeJs environment.

I have the following NodeJs code:

var PythonShell = require('python-shell');

var command = 'open1';
var comport = 6;

var options = {
scriptPath: 'python/scripts'
};

PythonShell.run('controlLock.py', options, function (err, results) {
if (err) throw err;
console.log('results: %j', results);
});


and I need to be able to include the command and COMPORT variable into the python
controlLock
script before the script gets executed (otherwise it wont have the right value).

Below is the
controlLock.py
file

import serial
ser = serial.Serial()
ser.baudrate = 38400 #Suggested rate in Southco documentation, both locks and program MUST be at same rate
ser.port = "COM{}".format(comport)
ser.timeout = 10
ser.open()
#call the serial_connection() function
ser.write(("%s\r\n"%command).encode('ascii'))

Answer

You can run the python script with arguments. The options that you pass to PythonShell.run() has a property called args that you can use to pass arguments to the python script. You can then read these command line arguments from the python script and insert where they are needed.

python-shell arguments

var options = {
  scriptPath: 'python/scripts',
  args: [command, comport], // pass arguments to the script here
};

python script

# 0 is the script itself, technically an argument to python
script = sys.argv[0]

# 1 is the command arg you passed
command = sys.argv[1]

# 2 is the comport arg you passed
comport = sys.argv[2]
Comments