optparse escaping control characters
John Machin
sjmachin at lexicon.net
Tue Aug 19 09:10:56 EDT 2008
On Aug 19, 10:35 pm, wannymaho... at gmail.com wrote:
> optparse seems to be escaping control characters that I pass as
> arguments on the command line. Is this a bug? Am I missing
> something? Can this be prevented, or worked around?
>
> This behaviour doesn't occur with non-control characters.
>
> For example, if this program (called test.py):
> from optparse import OptionParser
> parser = OptionParser()
> parser.add_option("-d", dest="delimiter", action="store")
> (options, args) = parser.parse_args()
> print options
>
> is run as follows:
> python test.py -d '\t'
>
> it outputs:
> {'delimiter': '\\t'}
>
> i.e. the \t has had an escape character added to give \\t.
You are inputting a TWO-byte string composed of a backslash and a
lowercase t, and feeding that to OptionParser.
C:\junk>type test.py
import sys; a = sys.argv[1]; d = {'delimiter': a}
print len(a), a, str(a), repr(a)
print d
# Note: this is Windows, where the shell quote is ", not '
C:\junk>python test.py "\t"
2 \t \t '\\t'
{'delimiter': '\\t'}
The extra backslash that you see is caused by the (implicit) use of
repr() to display the string.
If you want/need to enter a literal TAB character in the command line,
consult the manual for your shell.
HTH,
John
More information about the Python-list
mailing list