如何使用Python-Shell包从nodejs传递Python args?

StackUnderFlow

我正在使用这个python-shell软件包,对python和nodejs来说是非常新的东西。

我想将值传递给下面的python脚本。

script.py

my_name = [0]
print("Hello and welcome " + my_name + "!")

我想在下面传递“ Bruce Wayne”的arg并让上面的script.py在my_name变量中接收它

pythonShell.js

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

    var options = {
      mode: 'text',
      pythonPath: '/usr/bin/python', 
      pythonOptions: ['-u'],
      // make sure you use an absolute path for scriptPath
      scriptPath: '/home/username/Test_Project/Python_Script_dir',
      args: ['Bruce Wayne']
    };

    PythonShell.run('script.py', options, function (err, results) {
      if (err) throw err;
      // results is an array consisting of messages collected during execution
      console.log('results: %j', results);
    });
DaveStSome哪里

访问命令行参数有多种方法

这是使用sys.argv(包含参数)的示例

此外,sys.argv还包含的循环(请注意,带有path的脚本是第一个arg)。

script.py

import sys

my_name = sys.argv[1]

for n, a in enumerate(sys.argv):
    print('arg {} has value {} endOfArg'.format(n, a))
print("Hello and welcome " + str(my_name) + "!")

的JavaScript

const {PythonShell} = require('python-shell');

let options = {
    mode: 'text',
    pythonPath: '/path/to/python/bin/python3.7',
    pythonOptions: ['-u'], // get print results in real-time
    scriptPath: '/absolute/path/to/script/',
    args: ['Bruce Wayne']
};

PythonShell.run('numSO1.py', options, function (err, results) {
    if (err) throw err;
    // results is an array consisting of messages collected during execution
    console.log('results: %j', results);
});

输出(由于数组全为一行,因此已重新格式化):

results: [
    "arg 0 has value /path/to/script/script.py endOfArg",
    "arg 1 has value Bruce Wayne endOfArg",
    "Hello and welcome Bruce Wayne!"]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章