Python转义sys argv中的特殊字符

Stp*_*tpn 1 python string bash command-line argv

我有一个脚本,需要sys.argv,输入可能包含特殊字符(分号).我只需要输入字符串,但分号混淆了一切......

我有:

def myscript(text)
    print text


a = myscript(sys.argv[1])
print a
Run Code Online (Sandbox Code Playgroud)

我尝试:

>>  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""
Run Code Online (Sandbox Code Playgroud)

我明白了:

'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
Run Code Online (Sandbox Code Playgroud)

我只想将整个字符串放入脚本中,无论内部是什么.

我试过了:

a = myscript(repr(sys.argv[1]))
a = myscript(str(sys.argv[1]))
Run Code Online (Sandbox Code Playgroud)

Not*_*fer 7

这不是python的问题,你需要在调用shell中转义它.简单地将引号转义为\"分号和分号\;.

$ 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"
Run Code Online (Sandbox Code Playgroud)