0

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 引用的函数。

提前感谢您的任何建议。

4

1 回答 1

0

这是一个答案。它没有按照我的要求提供“ ......一个已经存在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变量的赋值语句pythonprint(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许多情况下的输出更简单。

于 2022-01-23T20:31:13.487 回答