Interpreting \ escape sequences in strings
Peter Otten
__peter__ at web.de
Sat Mar 13 17:43:30 EST 2004
Paul Watson wrote:
> How can I get the escapes from a command line parameter interpreted?
>
> The user provides a string on the command line. The string might contain
> traditional escapes such as \t, \n, etc. It might also contain escaped
> octal or hex such as \001 or \x09.
>
> The escapes are coming into sys.argv[] without shell interpretation. Do I
> need to use the compile module to make this work? Any suggestions?
>
> ===
> $ cat ./try_arglen2.py
> #! /usr/bin/env python
> import sys, StringIO
> print sys.argv[1]
>
> print sys.argv[1] % ()
>
> sf = StringIO.StringIO()
> print >> sf, sys.argv[1],
> c = sf.getvalue()
> sf.close()
> print "now" + c + "is" + c + "the"
>
> # This works because the interpreter is processing the escapes.
>
> sf = StringIO.StringIO("\001")
> c = sf.getvalue()
> sf.close()
> print "now" + c + "is" + c + "the"
>
> ===
> $ ./try_arglen2.py '\001'
> \001
> \001
> now\001is\001the
> now?is?the
If I'm understanding you correctly:
<args.py>
import sys
print sys.argv[1].decode("string_escape")
</args.py>
$ python args.py "winter\nof\012our\x0Adiscontent"
winter
of
our
discontent
Peter
More information about the Python-list
mailing list