pass special character from the command line [dupl

2019-08-09 12:05发布

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.

1条回答
Evening l夕情丶
2楼-- · 2019-08-09 12:21

You can use decode with the 'unicode_escape' text encoding from the codecs module to transform a raw string into a typical ol' string:

# -*- coding: utf-8 -*-
import sys
from codecs import decode

if __name__ =="__main__":

    if len(sys.argv) == 2:
        my_str = decode(sys.argv[1], 'unicode_escape')
        # alternatively you transform it to a bytes obj and
        # then call decode with:
        # my_str = bytes(sys.argv[1], 'utf-8').decode('unicode_escape')
    else :
        my_str = '\r\nte st'
    print (my_str)

The end result is:

im@jim: python3 tt.py "\r\nt est"

t est

This applies to Python 3. In Python 2 str types are pretty ambiguous as to what they represent; as such, they have a decode method of their own which you can use instead. As a result, you could drop the from codecs import decode and just change the line to:

my_str.decode('string_escape')

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.

查看更多
登录 后发表回答