Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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

>Solution :

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",":)")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading