Search code examples
zshdouble-quotessingle-quotes

Why does `python -c 'print('howdy')'` produce an error (in zsh), but `python -c 'print("howdy")'` does not?


When, in zsh, I execute python -c 'print('howdy')' from the command line, it produces the following error.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'howdy' is not defined

However, this python -c 'print("howdy")' does not, and instead produces the output expected by me, namely, howdy (as a string) is sent to stdout?

I thought python was agnostic on single or double quotes


Solution

  • Zsh is first parsing the command, following its own rules on quotes. To zsh, the command python -c 'print('howdy')' looks something like the following:

    • We're calling the program python
    • The first argument is -c
    • The second argument is 'print(' enclosed in quotes, followed by howdy, followed by ')' enclosed in quotes.

    Zsh is "expanding" this second argument to 'print(howdy)'. If you run this command in python you get the error you describe.