Reputation: 3285
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'))
Upvotes: 3
Views: 4198
Reputation: 27599
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]
Upvotes: 4