通过命令行将未知数的参数传递给python脚本

发布于 2025-02-08 10:09:23 字数 643 浏览 0 评论 0原文

我有一个节点服务器,该服务器通过

child_process execfile()

我没有问题,用已知数量的参数执行它,我只是像通过它一样通过它

 const { execFile } = require('node:child_process');
            const child = execFile('python', [conf.default.python_dir + "/script.py", arg1, arg2, arg3, arg4], (error:string, stdout:string, stderr:string) => {
              if (error) {
                throw error;
              }
              console.log(stdout);
            });

,但是我需要传递更改的参数,因为我不知道我的数据将拥有多少元素。我如何将数组的所有元素(随长度变化)传递到此Python脚本(作为参数)中。

我无法访问Python脚本,但是Python脚本理想情况下可以读取无限数量的参数,我只能通过命令行通过参数

I have a node server that executes an external python script via

child_process execFile()

I have no problem executing it with a known number of arguments i just pass it like

 const { execFile } = require('node:child_process');
            const child = execFile('python', [conf.default.python_dir + "/script.py", arg1, arg2, arg3, arg4], (error:string, stdout:string, stderr:string) => {
              if (error) {
                throw error;
              }
              console.log(stdout);
            });

However i need to pass changing number of arguments because i do not know how many elements my data is going to have. How can i pass all the elements of an array (with changing length) into this python script (as arguments).

I do not have access to the python script but python script is ideally able to read unlimited number of arguments and i only can pass arguments via command-line

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吾家有女初长成 2025-02-15 10:09:23

使用扩展操作传播数组(...)您可以创建一个接受无限参数的函数,然后将这些参数传播到execfile

const { execFile } = require('node:child_process');
function execFileWithArgs(...args) {
    const child = execFile('python', [conf.default.python_dir + "/script.py", ...args], (error:string, stdout:string, stderr:string) => {
              if (error) {
                throw error;
              }
              console.log(stdout);
            });
}
execFileWithArgs("unlimited","arguments","here",":)")

Using the spread operation to spread arrays (...) you can create a function that accepts unlimited amount of arguments and you spread those arguments into the execFile

const { execFile } = require('node:child_process');
function execFileWithArgs(...args) {
    const child = execFile('python', [conf.default.python_dir + "/script.py", ...args], (error:string, stdout:string, stderr:string) => {
              if (error) {
                throw error;
              }
              console.log(stdout);
            });
}
execFileWithArgs("unlimited","arguments","here",":)")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文