0

I am calling a python script using PythonShell through this code :

let python_options = {
    mode: "text",
    pythonPath: "python",
    scriptPath:"./python/",
    args: ["-fil '"+file_path+"'"]
};
let pyshell = new PythonShell.PythonShell('my_script.py',python_options);
pyshell.on('message', function(message) {
    console.log(message);
});
pyshell.end( function(err,code,signal) {
    if (err) console.log("Error %j", err);
    console.log('The exit code was: ' + code);
    console.log('The exit signal was: ' + signal);

    // console.log("results: %j", results);
    res.send(code);
});

then within my Python script I do

import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-fil", '--file', required=False, default=None)

The error message I'm getting when calling the script is

my_script.py: error: unrecognized arguments: -fil 'path_to_the_file'

My issue is that the shell passes "-fil path_to_the_file" to the CLI, which gets interpreted as one argument by argparse, instead of -fil path_to_the_file which would be correctly interpreted by argparse.

How can I remove the quotes in PythonShell ?

7
  • have you tried passing it a list with multiple args instead of a list with a string representing all the args? e.g. args: ["-fil", file_path] Commented Mar 18, 2019 at 10:30
  • I'm getting the same error unfortunately. When I try myself in the CLI it works even with the quotes though so I'm less confident in my diagnostic now... Commented Mar 18, 2019 at 10:36
  • "-fil " "paht_to_the_file" works in the CLI in case my comment above was unclear. But the PythonShell call still fails with the same error message. Commented Mar 18, 2019 at 10:37
  • try --file instead of fil, let me know what happens, I think your python code is the one that is wrong. Are you sure if you say python my_script.py "-fil " "paht_to_the_file" works? Python should not understand an arg with quotes AFAIK it will take it as a postional arg not as a keyword Commented Mar 18, 2019 at 10:42
  • I actually modified my code after I asked the question to remove the shortcuts from the argparse instance. So I'm calling it with --file already and yes it works in the CLI only. pyhton 3.7 on windows Commented Mar 18, 2019 at 10:46

1 Answer 1

2

In case it can help anyone, the solution is to do :

let python_options = {
    mode: "text",
    pythonPath: "python",
    scriptPath:"./python/",
    args: ["-fil",file_path] // instead of args: ["-fil '"+file_path+"'"]
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.