Carbon
Carbon

Reputation: 3943

Call a whole string of arguments with subprocess in python

Say I want to do: subprocess.call(['whatever.exe',v]) where v is a string representing all the arguments to pass to whatever.exe. Is there a way to do this without breaking apart each argument individually?

Upvotes: 2

Views: 896

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

yes, you can pass the full command line as a string:

subprocess.call('whatever.exe {}'.format(v))

but it's not a very good idea because if some arguments contained in v have spaces in it you have to do the quoting manually (and as Charles reminded me for the 50th time it only works on Windows unless shell=True is set, which is another bad idea)

Another option would be using shlex.split and append to your already existing argument list (if executable has spaces in the path at least it is handled):

subprocess.call(['whatever.exe']+shlex.split(v))

but the best option is composing the list of arguments properly of course (as an actual list), and not passing a string to subprocess at all (safety, security & portability reasons to start with). If you're controlling what's in v you can change as a list, and if you don't, well, you're probably exposing your program to a possible attack or denial of service)

Upvotes: 2

Related Questions