John John - 1 year ago 114
Node.js Question

How to insert variable from NodeJs into a python script?

I am using

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'
};'', 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
script before the script gets executed (otherwise it wont have the right value).

Below is the

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
#call the serial_connection() function

Answer Source

You can run the python script with arguments. The options that you pass to 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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download