What is the best way to handle a command line argument that includes an escape sequence like \n?

Joe JoeSalmeri at hotmail.com
Thu Mar 3 07:51:01 EST 2005


Hi Steve,

I've been using Python for many years, just hadn't had to deal with an 
escape sequence in the command line args. :-) and couldn't find the solution 
in the docs.

It is easy to prove my assertion:

import sys
c = sys.argv[1]
print len(c)
print 'Line 1', c, 'Line 2'

Output:
2
Line 1 \n Line 2

Versus:

import sys
c = sys.argv[1]
print len(c)
print 'Line 1', c.decode('string_escape'), 'Line 2'

Output:
2
Line 1
Line 2

Agreed, it is much easier on Unix to deal with this, I have not seen a way 
to get the XP command interpreter to allow a multiline command line as you 
described.

Your solution was exactly what I need.  I had an escape sequence entered on 
the command line and needed to decode the string so that Python used it as 
an escape sequence, in fact the sequence really is part of the output that 
the program produces.

Thanks again for your assistance.

Regards,

Joe

> I don't want you getting more confused rather than less - newcomers are 
> sometimes confused by Python's encoding of backslashes and such when 
> printing out strings. What is your evidence for the assertion that c is 
> set to \\n rather than \n?
>
> In Unix, it's easier to avoid this, since the shell lets you enter 
> multi-line strings (note that these lines may wrap in the mail):
>
> [sholden at headrat sholden]$ python -c "import sys; print repr(sys.argv[1])" 
> "\n"
> '\\n'
> [sholden at headrat sholden]$ python -c "import sys; print repr(sys.argv[1])" 
> "
> > "
> '\n'
>
> The first case simply demonstrates that the shell doesn't interpret 
> backslash escape sequences. I used repr() because that's what the 
> interpreter will print if you enter an expression at the interactive 
> prompt. The first case shows that the argument is two characters - you can 
> verify this using the len() function.
>
> The second case shows how (with a sensible command shell) you can provide 
> a newline as an argument.
>
> In Windows we can emulate the first case exactly:
> C:\Steve>C:\python24\python -c "import sys; print repr(sys.argv[1])" "\n"
> '\\n'
>
> Unfortunately Windows XP's command interpreter doesn't bother to wait 
> until you close a double-quote left open at the end of a line:
>
> C:\Steve>\python24\python -c "import sys; print repr(sys.argv[1])" "
> ''
>
> So someone else will have to tell you how to do that, but you should be 
> clear about what's happening before you try and correct the problem.
>
> regards
>  Steve
> -- 
> Meet the Python developers and your c.l.py favorites March 23-25
> Come to PyCon DC 2005                      http://www.pycon.org/
> Steve Holden                           http://www.holdenweb.com/ 





More information about the Python-list mailing list