Search code examples
pythonspecial-charactersoptparse

Optparse- Preserving special characters


I'm using optparse and recently I'm encountering the following problem- I want to pass as an argument a directory name. Something like:

./script.py --dir c:\a\b

However, optparse eliminates the "\" sign so the related variable remains with the value c:ab

Note: This script is being run on Linux machine, that connects to Windows machine and does some stuff. This is why I use the ./ in the script name and the directory is Windows sytle.

How do I make optparse preserve the special characters?


Solution

  • This is not a Python problem; it is your shell that parses the backslashes in the command line before sending it to Python. optparse is not to blame.

    Escape them by doubling the slashes:

    ./script.py --dir c:\\a\\b
    

    or put quotes around the argument:

    ./script.py --dir "c:\a\b"