2016-01-24 83 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)的列表,你必須小心*不要重寫。 –