shell command needs whitespace characters escaped
Nick Craig-Wood
nick at craig-wood.com
Fri Dec 8 13:30:07 EST 2006
Fredrik Lundh <fredrik at pythonware.com> wrote:
> metaperl wrote:
>
> > I downloaded a file which has a space in the filename. I want to run a
> > shell unzip on it, but it fails in my current code:
> >
> > syscmd = "cd %s ; unzip %s" % (self.storage.input, file.basename())
> > os.system(syscmd)
> >
> > because no escaping was done.
> >
> > Is there a more principled way to construct a shell command and execute
> > it so that all necessary characters are escaped?
>
> use subprocess.list2cmdline to create the command string
That is windows only isn't it?
>>> subprocess.list2cmdline(['a', "'b", 'c'])
"a 'b c"
Doesn't make a unix shell friendly command line.
For unix you can use this
def quotemeta(args):
"""Quote all the metacharacters in the args for the unix shell"""
return " ".join([re.sub(r"([^A-Za-z0-9_])", r"\\\1", string) for string in args])
>>> print quotemeta(['a', "'b", 'c'])
a \'b c
> (or better, subprocess.call).
A good idea!
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list