Python Forum

Full Version: Passing flags to python script, through a function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a python script, that i am able to call it from the command line, and i pass the parameters to it, through flags on the terminal. For example:

python my_program.py --parameter1 "0.4" --parameter2 "none"
Now, i want to be able to call that script from inside flask.
I can easily wrap the python script in a function, but what i do now know, is how will i be able to pass the parameters to it?

Keep in mind, that the python script handles parameters with

parser.add_argument()
How will i be able to pass the flags, as function parameters (or something like that)?
You can use subprocess.run()
import subprocess
import sys
subprocess.run([sys.executable, "my_program.py", "--parameter1", "0.4", "--parameter2", "none"])
Thank you very much!
Doing this however, will create a new process in the process list? Am i correct?

Thus, if you 'spawn' it five times, five new processes will be created. Is this correct?
Yes, each call of suprocess.run() creates a new process.
If creating another process is unnecessary, then exposing a function that you call from the Flask app is the right idea. Have it take as an argument the list of string arguments that you then pass to the parser. Presumably, you're using argparse.ArgumentParser, whose parse_args method does let you do that (see the docs). So, in the script, you'd just pass sys.argv to that function and in your Flask app, yeah, you'd just pass a list of strings containing the values you wanted. It's just good old dependency injection.