This question already has an answer here:
I have a problem with passing special characters to python from the command line. This is my script:
# -*- coding: utf-8 -*-
import sys
if __name__ =="__main__":
if len(sys.argv) == 2 :
str = sys.argv[1]
else :
str = '\r\nte st'
print (str)
And these are my test cases:
D:\>testArgv.py "\r\nt est"
\r\nt est
D:\>testArgv.py
te st
I want to know how to pass arguments to python from the command line to archieve a goal like the latter case. Or how I should change my script.
You can use
decode
with the'unicode_escape'
text encoding from thecodecs
module to transform a raw string into a typical ol' string:The end result is:
This applies to Python 3. In Python 2
str
types are pretty ambiguous as to what they represent; as such, they have adecode
method of their own which you can use instead. As a result, you could drop thefrom codecs import decode
and just change the line to:To get a similar result.
Addendum: Don't use names like
str
for your variables, they mask names for the built-in types Python has.