Home > Mobile >  Passing Unknown Number Of Arguments to Python Script from NodeJS via Command Line
Passing Unknown Number Of Arguments to Python Script from NodeJS via Command Line

Time:06-16

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

CodePudding user response:

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",":)")
  • Related