I have Python subprocess calls which are formatted as a sequence of arguments (like subprocess.Popen(['ls','-l']) instead of a single string (i.e. subprocess.Popen('ls -l')).
When using sequenced arguments like I did, is there a way to get the resulting string that is sent to the shell (for debugging purposes)?
One simple approach would be to join all arguments together myself. But I doubt this would in all cases be identical to what subprocess does, since the main reason for using a sequence is to ‘allow[s] the module to take care of any required escaping and quoting of arguments’.
As mentioned in a comment,
subprocesscomes with (not documented in the docs pages)list2cmdlinethat transforms a list of arguments into a single string.According to the source doc,
list2cmdlineis used mostly on Windows:Nevertheless, it’s quite usable on other OSes.
EDIT
Should you need the reverse operation (ie, splitting a command line into a list of properly tokenized arguments), you’ll want to use the
shlex.splitfunction, as illustrated in the doc ofsubprocess.