这是一个答案。它没有按照我的要求提供“ ......一个已经存在python
的可以执行这种更简单的 shell 引用的函数”,因为现在看起来这样的引用函数在python
. 但是,它确实显示了我如何编写提供更简单输出(forpython-3.6
或以上)的引用机制:
def shellquote(item):
if not item:
return "''"
# Pre-escape any escape characters
item = item.replace('\\', r'\\')
if "'" not in item:
# Contains no single quotes, so we can
# single-quote the output.
return f"'{item}'"
else:
# Enclose in double quotes. We must escape
# "$" and "!", which which normally trigger
# expansion in double-quoted strings in shells.
# If it contains double quotes, escape them, also.
item = item.replace(r'$', r'\$') \
.replace(r'!', r'\!') \
.replace(r'"', r'\"')
return f'"{item}"'
对于python
不支持 f-strings 的早期版本,format
可以使用这些 f-strings 代替。
这里有些例子。左列显示程序中pythonString
变量的赋值语句python
。print(shellquote(pythonString))
右侧的列显示了从程序中调用时将出现在终端上的内容python
:
pythonString='ABC"DEF' printed output: 'ABC"DEF'
pythonString="ABC'DEF" printed output: "ABC'DEF"
pythonString='ABC\'DEF' printed output: "ABC'DEF"
pythonString="ABC\"DEF" printed output: 'ABC"DEF'
pythonString='ABC\\"DEF' printed output: 'ABC\\"DEF'
pythonString="ABC\\'DEF" printed output: "ABC\\'DEF"
pythonString="AB'C$DEF" printed output: "AB'C\$DEF"
pythonString='AB\'C$DEF' printed output: "AB'C\$DEF"
pythonString='AB"C$DEF' printed output: 'AB"C$DEF'
pythonString="AB\"C$DEF" printed output: 'AB"C$DEF'
pythonString='A\'B"C$DEF' printed output: "A'B\"C\$DEF"
pythonString='A\\\'B"C$DEF' printed output: "A\\'B\"C\$DEF"
这不是可以执行 shell 引用的唯一方法,但至少输出比shlex.quote
许多情况下的输出更简单。