【问题标题】:Python escape special characters in sys argvPython转义sys argv中的特殊字符
【发布时间】:2012-03-24 08:28:02
【问题描述】:

我有一个使用 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 string bash command-line 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"
    

    【讨论】:

    • 输入由用户输入,总是不同的。或者,也许我不明白什么..?
    • 引号内的分号是可以的。发生的事情是第一个引号关闭了 arg,分号使 shell 执行您的命令。你是如何获得用户输入的?
    • 嗯,它是从网站发送的......我想我可以通过正则表达式过滤网络端的所有内容,但想知道是否有更简单的方法来做到这一点......
    • 这会有帮助吗? >>> re.escape('hello "world"') 'hello\\ \\"world\\"'
    【解决方案2】:

    这不是 python 问题,而是 bash 问题。 Bash 认为;(分号)正在分隔一个新的 bash 命令。你需要逃避它。

    【讨论】:

    • 好的,我明白了,谢谢!那么有什么方法可以在 bash 端强制转义?
    猜你喜欢
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多