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

Steve Holden steve at holdenweb.com
Thu Mar 3 10:12:45 EST 2005


Joe wrote:
> 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
> 
The "2" appears to prove *my* assertion that the argument passed by the 
shell to your Python program consists of 2 characters, "\\" followed by "n".

> 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
> 
As does this.

> 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.
> 
In fairness it was Steven Bethard's solution that gave you the solution 
you needed. As long as ytour problem is solved, that's fine, and it 
appears that you've solved it in a reasonably cross-platform way.

> Thanks again for your assistance.
> 
Always happy to help when I can!

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