TIL Gotcha about calling a shell command using Python subprocess

So you want to call a shell command from your Python application. There is a really nice library subprocess to do that. It has a lot of different methods that you can call. Most of them take the command and it’s arguments as an array.

The gotcha is about arguments that have spaces and require quotes around them. So for example you want to call the command:

my_cmd --arg1 --arg2="this is an argument"

To do that in the subprocess you convert it to an array such as:

["my_cmd", "--arg1", "--arg2='this is an argument'"]

That’s when you’ll start getting weird issues. The subprocess handles the spaced arguments on it’s own. So it’ll try to sanitize the quptes you just added. The array you pass has to be:

["my_cmd", "--arg1", "--arg2=this is an argument"]

And let the library handle adding the quotes!


Read More...