shell command needs whitespace characters escaped

M

metaperl

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?
 
K

Klaus Alexander Seistrup

Metaperl said:
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.

Using "cd '%s' ; unzip '%s'" as your formatting string should work.

Cheers,
 
F

Fredrik Lundh

metaperl said:
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 (or better,
subprocess.call). see this FAQ entry for sample code:

http://effbot.org/pyfaq/why-can-t-raw-strings-r-strings-end-with-a-backslash.htm

</F>
 
N

Nick Craig-Wood

Fredrik Lundh said:
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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top