[Pythonmac-SIG] Escaping commandline strings

Chris Weisiger cweisiger at msg.ucsf.edu
Tue Jan 4 22:41:33 CET 2011


A friend just pointed me to pipes.quote(). Is there any reason I shouldn't
just use that?

And given the number of rather simple things that are already in the
standard library (e.g. capitalize the first letter of a string), simplicity
isn't really an excuse for excluding this functionality. Especially since
doing this wrong leaves you open to security issues.

-Chris

On Tue, Jan 4, 2011 at 1:20 PM, Cameron Simpson <cs at zip.com.au> wrote:

> On 04Jan2011 12:21, Chris Weisiger <cweisiger at msg.ucsf.edu> wrote:
> | I want to sanitize some strings (e.g. escape apostrophes, spaces, etc.)
> | before passing them to the commandline via subprocess. Unfortunately I
> can't
> | seem to find any built-in function to do this. Am I really going to have
> to
> | write up my own sanitizer? Not that it'd be much effort, but I'd much
> rather
> | use an official function than risk forgetting something.
>
> If it is for Bourne shell syntax, it's almost too simple to put in a
> library: put into single quotes and replace all inner single quotes
> with:
>
>  '\''
>
> You can play games with strings that are safe to not quote, etc but the
> above is very simple and reliable. Something like (untested):
>
>  "'"+s.replace("'", "'\\''")+"'"
>
> Cheers,
> --
> Cameron Simpson <cs at zip.com.au> DoD#743
> http://www.cskk.ezoshosting.com/cs/
>
> You Know You're in the SCA When...
>        ...the tunes you unconsciously hum are in Latin.
>                - Cailfind ingen Grainne
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pythonmac-sig/attachments/20110104/17748dad/attachment.html>


More information about the Pythonmac-SIG mailing list