0

Currently I have the following code:

bubble.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()

Running the following commands work fine on windows: bubble.py hello world bubble.py hello? bubble.py hello :)

But causes varying errors on macOS: zsh: no matches found hello? zsh: parse error near `)'

As disclaimer, I have little to none knowledge of macOS terminal. How to avoid the error and have the texts including the punctuations captured by argparse nargs?

Jobo Fernandez
  • 905
  • 4
  • 13
  • This is not a "problem" you can fix in argparse. Your command is first interpreted by the shell, which has its own rules and syntax. If you want to pass "special characters", which have a *special* meaning in the shell, you need to escape/quote them according to the shell's rules. Only after the shell has already interpreted your command is Python even invoked, and will received the already processed arguments. – deceze Mar 07 '23 at 12:51

1 Answers1

0

This is because the question mark and parentheses have special meaning in Zsh which get handled differently by the shell's parser.

The question mark is interpreted as a wildcard that matches any single character in a filename or path and parentheses can be used to run commands in a separate process, for command grouping or arithmetic expressions.

You can avoid the errors by escaping the characters so they are treated as literal characters

% python bubble.py hello\?
['hello?']
% python bubble.py hello :\)
['hello', ':)']

Or by enclosing the argument in single or double quotes

% python bubble.py 'hello?'
['hello?']
% python bubble.py hello ':)'
['hello', ':)']

It's worth noting that single and double quotes have different meanings in Zsh, where single quotes preserve the literal value of the characters enclosed, while double quotes can be used for variable interpolation or command substitution.

mickyhale
  • 46
  • 4