[Pythonmac-SIG] Escaping commandline strings
Cameron Simpson
cs at zip.com.au
Tue Jan 4 22:20:51 CET 2011
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
More information about the Pythonmac-SIG
mailing list