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?
1 Answer
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)
6 Comments
'whatever.exe {}'.format(v) instead of 'whatever.exe ' + v?whatever.exe and the rest of the arguments :). str.format is clearer.shlex.split(); -1 on the "pass the full command line as a string" (Windows is a different beast, but on UNIX that just won't work without shell=True), so right now I'm at =0..exe extension, or did they say it explicitly somewhere? (CLR binaries are executable on UNIX systems where binfmt_misc or an equivalent has been used to tell Mono to invoke them).
shlex.split.