Python Language Subprocess Library How to create the command list argument

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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']


Got any Python Language Question?