我有一个采用 sys.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]))
最佳答案
这不是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"
关于Python转义sys argv中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9590838/