Python3: shell 引用比 shlex.quote() 输出更简单?

Python3: shell quoting less complicated than shlex.quote() output?

python3.8中,我有这个代码:

import shlex
item = "ABC'DEF"
quoteditem = shlex.quote(item)
print(quoteditem)

这是输出:

'ABC'"'"'DEF'

在这个网页上很难辨别双引号和单引号,所以这是对打印内容的描述:

single-quote
ABC
single-quote
double-quote
single-quote
double-quote
single-quote
DEF
single-quote

这当然是一个正确的 shell 引用,但它不是唯一可能的 shell 引用,而且它过于复杂。

另一种可能就是这样:

"ABC'DEF"

还有第二种可能:

ABC\'DEF

我更喜欢这些更简单的版本。我知道如何编写 python 代码将复杂的版本转换为这些更简单的形式之一,但我想知道是否已经存在 python 函数可以执行这种更简单的 shell 引用。

提前感谢您的任何建议。

这是sort-of一个答案。它没有按照我的要求提供“...一个已经存在的python函数可以执行这种更简单的shell引用”,因为它现在python 中似乎不存在这样的引用函数。但是,它确实显示了我如何编写提供更简单输出的引用机制(对于 python-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}"'

对于不支持f-strings的python早期版本,可以使用format代替那些f-strings。

这里有一些例子。左列显示了 python 程序中 pythonString 变量的赋值语句。右侧列显示了当从 python 程序中调用 print(shellquote(pythonString)) 时将出现在终端上的内容:

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 的输出更简单。