Sanitising arguments to shell commands

Ben Finney ben+python at
Fri Aug 21 12:26:02 CEST 2009

Chris Rebert <clp2 at> writes:

> module shlex — Simple lexical analysis
> New in version 1.5.2.
> "The shlex class makes it easy to write lexical analyzers for simple
> syntaxes resembling that of the Unix shell."

Exactly what I needed:

>>> import shlex
>>> user_configured_args = "--baz 'crunch cronch' --wobble"
>>> filenames = ["spam.txt", "beans.txt"]
>>> command_args = ["foo", "--bar"]
>>> command_args.extend(shlex.split(user_configured_args))
>>> command_args.extend(filenames)
>>> command_args
['foo', '--bar', '--baz', 'crunch cronch', '--wobble', 'spam.txt', 'beans.txt']

 \         “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\    Brain, but if we get Sam Spade, we'll never have any puppies.” |
_o__)                                           —_Pinky and The Brain_ |
Ben Finney

More information about the Python-list mailing list