gpt4 book ai didi

python - 如何使用Python-Shell包从nodejs传递Python参数?

转载 作者:行者123 更新时间:2023-11-30 21:55:25 25 4
gpt4 key购买 nike

我正在使用这个python-shell package对于 python 和 Nodejs 的世界来说非常陌生。

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

脚本.py

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

我想传递下面的“Bruce Wayne”参数,并让上面的 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);
});

最佳答案

有多种方法可以访问 command line arguments .

这是一个使用 sys.argv 的示例(其中包含参数)。

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

脚本.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!"]

关于python - 如何使用Python-Shell包从nodejs传递Python参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56822202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com