Python转义sys argv中的特殊字符

标签 python string bash command-line argv

我有一个采用 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/

相关文章:

java - Python 相当于 Java 的 BitSet

c - 在 C 中反转 2 个字符串

linux - 在 bash 中查找字符串并将其分配给变量

regex - 匹配备份文件 (`*~` )

python - 使用Python转换PDF坐标系

python - "group by"具有字典推导式的聚合函数

c++ - 使用字符串作为条件时减少 else if 语句的方法

bash - 在 bash 中的 printf %s 替换中有效地重用颜色代码

python - PyInvoke:如何处理任务的标准输入?

python - 函数 string.lstrip() 在 python 中返回空白字符串