2012-03-06 91 views
1

我有一個需要sys.argv並且輸入可能包含特殊字符(分號)的腳本。我只需要輸入的字符串,但分號攪亂了一切..Python中的特殊字符轉義argv

我:

def myscript(text) 
    print text 


a = myscript(sys.argv[1]) 
print a 

我嘗試:

>> python script.py "With these words she greeted Prince Vasili Kuragin, a man of high rank and importance, who was the first to arrive at her reception. Anna Pavlovna had had a cough for some days. She was, as she said, suffering" from la grippe; grippe being then a new word in St. Petersburg"" 

我得到:

'With these words she greeted Prince Vasili Kuragin, a man of high rank and importance, who was the first to arrive at her reception. Anna Pavlovna had had a cough for some days. She was, as she said, suffering' 
None 
bash: grippe: command not found 

我只是想把整個字符串放到腳本中,不管裏面有什麼..

我想:

a = myscript(repr(sys.argv[1])) 
a = myscript(str(sys.argv[1])) 

回答

7

它不是蟒蛇的問題,你需要逃避它在調用外殼。只需簡單地將引號作爲\"和分號作爲\;即可。

$ python testme.py "With these words she greeted Prince Vasili Kuragin, a man of high rank and importance, who was the first to arrive at her reception. Anna Pavlovna had had a cough for some days. She was, as she said, suffering\" from la grippe; grippe being then a new word in St. Petersburg\"" 

With these words she greeted Prince Vasili Kuragin, a man of high rank and importance, who was the first to arrive at her reception. Anna Pavlovna had had a cough for some days. She was, as she said, suffering" from la grippe; grippe being then a new word in St. Petersburg" 
+0

輸入由用戶完成,並且始終不同。或者,也許我不明白的東西..? – Stpn 2012-03-06 19:58:54

+0

引號內的分號是可以的。發生了什麼事是第一個報價關閉了arg,分號讓shell執行了你的命令。你如何獲得用戶輸入? – 2012-03-06 20:01:36

+0

以及它從一個網站發送...我想我可以通過正則表達式在網頁上過濾所有內容,但想知道是否有更簡單的方法來做到這一點.. – Stpn 2012-03-06 20:04:20

2

這是不是一個問題,蟒蛇,它是一個慶典問題。 Bash認爲;(分號)正在分離一個新的bash命令。你需要逃避它。

+0

好的,我明白了,謝謝!有沒有什麼辦法可以在bash端強制轉義? – Stpn 2012-03-06 20:02:34