【发布时间】:2017-01-08 11:29:51
【问题描述】:
我正在尝试使用child_process spawn 将参数从 Node.js 传递给 Python。我还想使用我在 Node.js 数组中指定的参数之一调用特定的 Python 函数。
test.js
'use strict';
const path = require('path');
const spawn = require('child_process').spawn;
const exec = (file, fnCall, argv1, argv2) => {
const py = spawn('python', [path.join(__dirname, file), fnCall, argv1, argv2]);
py.stdout.on('data', (chunk) => {
const textChunk = chunk.toString('utf8'); // buffer to string
const array = textChunk.split(', ');
console.log(array);
});
};
exec('lib/test.py', 'test', 'argument1', 'argument2'.length - 2); // => [ 'argument1', '7' ]
exec('lib/test.py', 'test', 'arg3', 'arg4'.length - 2); // => [ 'arg3', '2' ]
这里的第二个参数是test,它应该调用test() Python函数。
lib/test.py:
import sys
def test():
first_arg = sys.argv[2]
second_arg = sys.argv[3]
data = first_arg + ", " + second_arg
print(data, end="")
sys.stdout.flush()
如果我尝试在没有任何 Node.js 的情况下从命令行运行这个 Python 文件,执行如下所示:
$ python lib/test.py test arg3 2
其中test、arg3 和2 只是命令行参数,但test 应该调用test() 函数,该函数将使用arg3、2 参数作为@987654336 @。
【问题讨论】:
标签: python arguments command-line-arguments sys