【问题标题】:How can I escape any of the special shell characters in a Python string?如何转义 Python 字符串中的任何特殊 shell 字符?
【发布时间】:2015-01-24 00:23:50
【问题描述】:

如何转义 Python 字符串中的任何特殊 shell 字符?

以下字符需要转义:

$,!,#,&,",',(,),|,<,>,`,\,;

例如说我有这个字符串:

str="The$!cat#&ran\"'up()a|<>tree`\;"

TIA

【问题讨论】:

  • 你想做什么?
  • 这个字符串是用作字符串(这不是问题),还是传递给某个 shell 命令?
  • 题外话:请不要命名变量str。它将隐藏内置的 str 类。
  • 它传递给一个shell脚本,我这里只是用str,实际脚本有不同的名字。
  • 编辑队列已满?不知道他们是否都在试图移动“TIA”。此外,应该接受 shlex 的答案。即使 OP 在 2015 年使用 Python2,现在也不应该在 2021 年使用。

标签: python bash shell


【解决方案1】:

在 Python3 中,所需的电池包含在 shlex.quote 中。

shlex.quote(s)

返回字符串 s 的 shell 转义版本。返回的值是一个字符串,可以安全地用作 shell 命令行中的一个标记 [...]。

在你的例子中:

import shlex

s = "The$!cat#&ran\"'up()a|<>tree`\;"
print(shlex.quote(s))

输出:

'The$!cat#&ran"'"'"'up()a|<>tree`\;'

【讨论】:

  • shlex.quote 仅适用于 python3
  • Python 2.7 的等价物是 pipes.quote,与 Python 3 中的 shlex.quote 相同。
  • @SamRoberts,你到底想做什么?
  • 实际上,pipes.quote 并没有转义这 5 个字符:! $ ' " ` 有什么想法吗?
【解决方案2】:

re.sub 将完成这项工作:

re.sub("(!|\$|#|&|\"|\'|\(|\)|\||<|>|`|\\\|;)", r"\\\1", astr)

输出

The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\\;

【讨论】:

    【解决方案3】:

    不确定为什么要转义所有内容而不是尽可能多地引用,但是,应该这样做(如果需要,将 '@' 替换为字符串中不存在的另一个字符):

    >>> escape_these = r'([$!#&"()|<>`\;' + "'])"
    >>> print(re.sub(escape_these, r'@\1', s).replace('@','\\'))
    The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\;
    

    使用少一点的转义技巧可能是可行的,但不幸的事实是字符串、re 和 shell 都使用\(反斜杠)进行转义和其他特殊目的,确实使事情复杂化了位:-)。

    【讨论】:

      猜你喜欢
      • 2011-05-11
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 2017-04-02
      • 2011-05-07
      相关资源
      最近更新 更多