2012-03-06 14 views
1

sys.argvを使用するスクリプトがあり、入力に特殊文字(セミコロン)が含まれている可能性があります。私が持っているsys argvのPythonエスケープ特殊文字

..私は単なる文字列として入力する必要がありますが、セミコロンがアップし、すべてを台無し:

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の問題ではありません、あなたは、呼び出し元のシェルにそれをエスケープする必要があります。単に引用符を\"とし、セミコロンを\;とするだけです。

$ 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

+0

引用符の中のセミコロンは大丈夫です。何が起こったのは、最初の引用がargを閉じ、セミコロンがシェルにあなたのコマンドを実行させたということでした。どのようにユーザー入力を取得していますか? –

+0

それはウェブサイトから送信されています...私は正規表現を通じてウェブ側のすべてをフィルタリングできると思いますが、それを行う簡単な方法があるかどうか疑問に思っていました。 – Stpn

2

これは、bashの問題だ、Pythonの問題ではありません。 Bashは;(セミコロン)が新しいbashコマンドを分離していると考えています。あなたはそれをエスケープする必要があります。

+0

よろしくお願いします、ありがとう!それでは、bash側で強制的にエスケープする方法はありますか? – Stpn