Search code examples
pythonregexoptparse

optparse does not save second whitespace into arg


I am writing a regex match program, and I am unable to use regular expressions that start with spaces.

Is there any way to tell OptParse to only delimit by the first whitespace?


Solution

  • No, because the shell removes those spaces, not optparse. Python is handed a list of already-parsed command-line parameters.

    Use quoting to preserve spaces:

    ./yourscript.py --option=" spaces in here "
    

    To demonstrate, I created the following script:

    #!/usr/bin/env python
    import sys
    print sys.argv
    

    to show you what optparse sees:

    $ ./demo.py     foo bar baz
    ['./demo.py', 'foo', 'bar', 'baz']
    

    Note how the whitespace is all removed and three values are passed to the script. But with quoting:

    $ ./demo.py "    foo bar" baz
    ['./demo.py', '    foo bar', 'baz']
    

    the whitespace is preserved, and I joined two strings together into one as well.