2016-11-22 12 views
3

私は012Jを使用して、自分のNodeJs環境でPythonスクリプトを実行しています。NodeJsからPythonスクリプトに変数を挿入するには?

私は、次のNodeJsコードがあります。

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

を、私はスクリプトが実行される前のpython controlLockスクリプトにコマンドやコンポート変数を含めることができるようにする必要があります(それ以外の場合は文句を言わない正しい値を持っています) 。

は以下controlLock.pyファイル

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')) 

答えて

1

あなたはrun the python script with argumentsをすることができます。 PythonShell.run()に渡すoptionsには、argsというプロパティがあり、これを使用してPythonスクリプトに引数を渡すことができます。あなたはread these command line argumentsからPythonスクリプトを入手し、必要な場所に挿入することができます。

python-shell引数

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

Pythonスクリプト

# 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] 
関連する問題