Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass in string as argument without it being treated as raw

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?

like image 274
Siavash Avatar asked Jan 29 '26 12:01

Siavash


2 Answers

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').

like image 133
9000 Avatar answered Jan 31 '26 01:01

9000


myscript.py contains:

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

result abcd abcd

like image 37
John Faulkner Avatar answered Jan 31 '26 02:01

John Faulkner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!