Alt182 Alt182 - 2 months ago 6
Python Question

Passing arg to subprocess.call

I have a series of scripts that get called in an explicit order by another

run.py
.

Inside
run.py
I have the following:

script1 = str(sys.path[0]) + "\\script1.py"
subprocess.call(["Python", script1])


And so on for 3 scripts. If I would like to pass two arguments to script 1 in this format, arguments such as explicit run settings to be used in the script when it is executing, how would I do this? I have a feeling it would rely on sys.argv within script1, but have gotten errors about the argument being out of range regardless of what index position I pass.

Thanks!

Answer

Subprocesses takes a list of arguments, which it then turns into a command it executes.

So:

subprocess.call(["Python", script1, 'arg1', 'arg2'])

To subprocess.call, all the parts of its list are arguments. You just happen to be specifying "Python" and script1, but to subprocess, both are just other arguments.

There is a lot more reading on the documentation for subprocess which I would recommend looking over.

Comments