目前我有以下代码:
气泡.py
import argparse
parser = argparse.ArgumentParser(description="Create pixel art bubble speech image")
parser.add_argument('text', type=str, nargs='+', help="Text inside the bubble speech")
args = parser.parse_args()
运行以下命令在 Windows 上运行良好:
bubble.py hello world
bubble.py hello?
bubble.py hello :)
但在 macOS 上会导致各种错误:
zsh: no matches found hello?
zsh: parse error near `)'
作为免责声明,我对 macOS 终端几乎一无所知。如何避免错误并让包含 argparse nargs 捕获的标点符号的文本?
这是因为问号和括号在 Zsh 中有特殊的含义,shell 的解析器会以不同的方式处理它们。
问号被解释为匹配文件名或路径中任何单个字符的通配符,括号可用于在单独的进程中运行命令,用于命令分组或算术表达式。
您可以通过转义字符来避免错误,因此它们被视为文字字符
% python bubble.py hello\?
['hello?']
% python bubble.py hello :\)
['hello', ':)']
或者通过将参数括在单引号或双引号中
% python bubble.py 'hello?'
['hello?']
% python bubble.py hello ':)'
['hello', ':)']
值得注意的是,单引号和双引号在 Zsh 中有不同的含义,单引号保留包含的字符的字面值,而双引号可用于变量插值或命令替换。