2016-01-24 100 views
1

我从将特殊字符传递给python的命令行遇到问题。这是我的脚本:从命令行传递特殊字符

# -*- coding: utf-8 -*- 
import sys 

if __name__ =="__main__": 

    if len(sys.argv) == 2 : 
     str = sys.argv[1] 
    else : 
     str = '\r\nte st' 
    print (str) 

而这些是我的测试用例:

D:\>testArgv.py "\r\nt est" 
\r\nt est 

D:\>testArgv.py 

te st 

我想知道如何参数从命令行传递给蟒蛇archieve像后一种情况下一个目标。或者我应该如何改变我的剧本。

+0

为什么在没有主函数时检查'main'?你有没有试图打印你实际上在你的sys.argv中获得什么? – ishaan

+0

试试这个'python testArgv.py \\ r \\ nt est' – ishaan

+1

@ishaan对不起,我是python的新手,'main'函数只是来自另一个代码模板。 –

回答

2

可以使用decode'unicode_escape' text encodingcodecs模块到原始字符串转换为一个典型的醇”字符串:

# -*- 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) 

最终的结果是:

[email protected]: python3 tt.py "\r\nt est" 

t est 

这适用于Python 3. In Python 2 str types are pretty ambiguous as to what they represent;因此,他们有自己的decode方法,您可以改用它。其结果是,你可以放下from codecs import decode,只是将该行更改为:

my_str.decode('string_escape') 

要获得类似的结果。


附录不要为你的变量使用像str的名字,他们掩盖名称为内建类型Python有。

+0

为什么'if __name__ ==“__ main __”:'?我没有看到一个主要的方法。 – ishaan

+0

当Python直接执行模块,而不是通过导入可以说,它赋予'module .__ name__'属性等于'__main__'。所以当你直接执行这个模块时,'if'子句只有True。你不需要定义一个'main'方法。 –

+0

@ShenmeYiwei附录是你应该记住的东西,它可以导致细微的小虫子;这里是[内置函数](https://docs.python.org/3/library/functions.html)的列表,你必须小心*不要重写。 –