2

I want to pass in a string to my python script which contains escape sequences such as: \x00 or \t, and spaces.
However when I pass in my string as:

some string\x00 more \tstring

python treats my string as a raw string and when I print that string from inside the script, it prints the string literally and it does not treat the \ as an escape sequence.
i.e. it prints exactly the string above.

UPDATE:(AGAIN)
I'm using python 2.7.5 to reproduce, create a script, lets call it myscript.py:

import sys
print(sys.argv[1])

now save it and call it from the windows command prompt as such:

c:\Python27\python.exe myscript.py "abcd \x00 abcd"

the result I get is:

> 'abcd \x00 abcd'

P.S in my actual script, I am using option parser, but both have the same effect. Maybe there is a parameter I can set for option parser to handle escape sequences?

icedwater
  • 4,701
  • 3
  • 35
  • 50
Siavash
  • 7,583
  • 13
  • 49
  • 69

3 Answers3

7

The string you receive in sys.argv[1] is exactly what you typed on the command line. Its backslash sequences are left intact, not interpreted.

To interpret them, follow this answer: basically use .decode('string_escape').

Community
  • 1
  • 1
9000
  • 39,899
  • 9
  • 66
  • 104
6

myscript.py contains:

import sys
print(sys.argv[1].decode('string-escape'))

result abcd abcd

John Faulkner
  • 990
  • 7
  • 10
1

I don't know that you can parse entire strings without writing a custom parser but optparse supports sending inputs in different formats (hexidecimal, binary, etc).

from optparse import OptionParser
parser = OptionParser()
parser.add_option("-n", type="int", dest="num")

options, args = parser.parse_args()

print options

then when you run

C:\Users\John\Desktop\script.py -n 0b10

you get an output of

{'num': 2}

The reason I say you'll have to impletement a custom parser to make this work is because it isn't Python the changes the input but rather it is something the shell does. Python might have a built in module to handle this but I am not aware of it if it exists.

Community
  • 1
  • 1
John
  • 13,197
  • 7
  • 51
  • 101
  • ok you are the first to understand my problem. This is the right track, but my issue is I need tp pass in a long string that contains \x00 in a few spots. I dont want to pass in the whole string as int values. – Siavash Jul 03 '13 at 03:05