Python Language How to create the command list argument


The subprocess method that allows running commands needs the command in form of a list (at least using shell_mode=True).

The rules to create the list are not always straightforward to follow, especially with complex commands. Fortunately, there is a very helpful tool that allows doing that: shlex. The easiest way of creating the list to be used as command is the following:

import shlex
cmd_to_subprocess = shlex.split(command_used_in_the_shell)

A simple example:

import shlex
shlex.split('ls --color -l -t -r')

out: ['ls', '--color', '-l', '-t', '-r']