Constructing a command for subprocess execution

Python module, subprocess's Popen call takes a list as its first argument, with name of the command as the first element of the list. Most often, we do "command line sentence".split() to get the list for the subprocess.Popen call.  It is very suboptimal way, especially when you have double-quotes characters which served as shell escape characters.

Consider the following command and see how shlex module makes it more suitable for subprocess.Popen

/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"



import shlex
cmd = """/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" """

list_cmd1 = cmd.split(' ')
list_cmd2 = shlex.split(cmd)

print list_cmd1
print list_cmd2

$python prog.py 
['/bin/vikings', '-input', 'eggs.txt', '-output', '"spam', 'spam.txt"', '-cmd', '"echo', '\'$MONEY\'"', '']
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]

Isn't the second version much simpler?

No comments: