473,513 Members | 2,881 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Interpreting \ escape sequences in strings

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
Jul 18 '05 #1
6 5001
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

Jul 18 '05 #2

"Peter Otten" <__*******@web.de> wrote in message
news:c3*************@news.t-online.com...
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


I did have not explained it clearly. I want the user to specify a string
that I will put between words in the output. The user specified string can
have escape sequences. For example, the user wants to put a binary 1 (\001)
between each output word.

import sys
words = ['now', 'is', 'the', 'time']
print '\001'.join(words) #this works
print sys.argv[1].join(words) #this fails

$ ./putbetween.py '\001'
now?is?the?time
now\001is\001the\001time
Jul 18 '05 #3
Paul Watson wrote:
I did have not explained it clearly. I want the user to specify a string
Seems it was clear enough, you only didn't recognize the answer :-)
that I will put between words in the output. The user specified string
can
have escape sequences. For example, the user wants to put a binary 1
(\001) between each output word.

import sys
words = ['now', 'is', 'the', 'time']
print '\001'.join(words) #this works
print sys.argv[1].join(words) #this fails


Change the above line to

print sys.argv[1].decode("string_escape")

s.decode("string_escape") returns a new string with all c-style escape
sequences converted into the corresponding characters. This is an abuse -
ahem, example of a general mechanism. Look for codecs if you want to learn
more about it.

Peter

Jul 18 '05 #4

"Peter Otten" <__*******@web.de> wrote in message
news:c3*************@news.t-online.com...
Paul Watson wrote:
I did have not explained it clearly. I want the user to specify a
string
Seems it was clear enough, you only didn't recognize the answer :-)
that I will put between words in the output. The user specified string
can
have escape sequences. For example, the user wants to put a binary 1
(\001) between each output word.

import sys
words = ['now', 'is', 'the', 'time']
print '\001'.join(words) #this works
print sys.argv[1].join(words) #this fails


Change the above line to

print sys.argv[1].decode("string_escape")

s.decode("string_escape") returns a new string with all c-style escape
sequences converted into the corresponding characters. This is an abuse -
ahem, example of a general mechanism. Look for codecs if you want to learn
more about it.

Peter


Thank you. I appreciate your help. Yes, I missed it. I will look at the
decode doc. I expected that this was for converting character encodings
(codepages). This does work under Python 2.3, and decode was available in
2.2.

However, I am in a Python 2.1 environment. Do you know of any techniques
that would work under Python 2.1?
Jul 18 '05 #5
Paul Watson wrote:
However, I am in a Python 2.1 environment. Do you know of any techniques
that would work under Python 2.1?


eval('"' + s + '"')

This of course requires that " chars occuring in s are preceded by a
backslash:
def unescape(s): .... return eval('"' + s + '"')
.... unescape("\\x0a") '\n' unescape("\\x0a'") "\n'" unescape("\\x0a\"") Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in unescape
File "<string>", line 1
"\x0a""
^
SyntaxError: invalid token unescape('\\x0a\\"')

'\n"'

Peter

Jul 18 '05 #6
Peter Otten wrote:
Paul Watson wrote:
However, I am in a Python 2.1 environment. Do you know of any techniques
that would work under Python 2.1?


eval('"' + s + '"')


I should have warned you that this is a security hole, as it allows the user
to execute arbitrary code. E. g:

<args.py>
import sys

def somefunc():
print "somefunc called"
return ""

def unescape(s):
return eval('"' + s + '"')

print unescape(sys.argv[1])
</args.py>

$ python args.py '"+somefunc()+"'
somefunc called

Peter

Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3356
by: Thomas Philips | last post by:
I have been playing around with reading strings with embedded escape sequences from files both using readline() and codecs.open() and have a question.I create a file "test.txt" with exactly one line: 1\na\n\n2\n\n3 I then open test.txt and then read it using readline(): >>> input_file=file("test.txt") >>> x=input_file.readline() >>> x
6
1667
by: kartik | last post by:
Escape sequences don't seem to work in strings within list comprehensions: >>> print ] What am I missing? Thank you.
18
7149
by: Steve Litvack | last post by:
Hello, I have built an XMLDocument object instance and I get the following string when I examine the InnerXml property: <?xml version=\"1.0\"?><ROOT><UserData UserID=\"2282\"><Tag1 QID=\"55111\"><Tag2 AID=\"5511101\"></Tag2></Tag1><Tag1 QID=\"55112\"><Tag2 AID=\"5511217\"></Tag2></Tag1><Tag1 QID=\"5512282\"><Tag2...
3
5709
by: Ken | last post by:
HI: I'm reading a string that will be displayed in a MessageBox from a resource file. The string in the resource file contains escape sequences so they will be broken up into multiple lines. e.g. This is line 1\n\nThis is line 2. When this string is read using a ResourceManager GetString method the string is returned @-quoted, i.e as if...
5
3090
by: nummertolv | last post by:
Hi, My application is receiving strings, representing windows paths, from an external source. When using these paths, by for instance printing them using str() (print path), the backslashes are naturally interpreted as escape characters. >>> print "d:\thedir" d: hedir
4
4262
by: JJ | last post by:
Is there a way of checking that a line with escape sequences in it, has no strings in it (apart from the escape sequences)? i.e. a line with \n\t\t\t\t\t\t\t\r\n would have no string in it a line with \n\t\t\t\thello\t\t\n would hve the string 'hello' in it. In others words, is there a method of removing all escape sequences from a...
1
2245
by: Chris Carlen | last post by:
Hi: I'm writing a Python program, a hex line editor, which takes in a line of input from the user such as: -e 01 02 "abc def" 03 04 Trouble is, I don't want to split the quoted part where the space occurs.
3
6487
by: slomo | last post by:
How to read strings cantaining escape character from a file and use it as escape sequences? for example, a file 'unicodes.txt' has contents: \u0050\u0079\u0074\u0068\u006f\u006e Now, '\\u0050\\u0079\\u0074\\u0068\\u006f\\u006e\n'
10
2588
by: hanaa | last post by:
Hello there. $str="This is \na ball"; echo $str; Is there a way i can make the text to be as is, without expanding the escape sequences. I know that single quoted strings do not expand escape sequences. But I need to echo text that's been entered by the user in a html textarea as is. And thats why I dont want the escape sequences to be...
0
7269
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7177
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7394
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7123
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5701
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5100
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3237
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1611
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
811
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.