In Python 3.3 you can use shlex.quote to return a shell-escaped version of a string. It is the successor of pipes.quote, which was deprecated since Python 1.6. Note that the documentation recommends this for cases where you cannot use a list, as suggested in another answer. Also according to the documentation, the quoting is compatible with UNIX shells. I can't guarantee that it will work for your case, but a quick test with rm
, using pipes
because I don't have Python 3.3:
$ touch \(a\ b\)
$ ls
(a b)
>>> import subprocess, pipes
>>> filename = pipes.quote("(a b)")
>>> command = 'rm {}'.format(filename)
>>> subprocess.Popen(command, shell=True)
$ ls
$