Search code examples
pythonpowershellinterpreterdouble-quotessingle-quotes

Why doesn't it work sometimes when using single quotes to surround the command in `python -c [command]` in PowerShell (and in command prompt as well)?


In the Python docs it says:

A second way of starting the interpreter is python -c *command* [arg] ..., which executes the statement(s) in command, analogous to the shell’s -c option. Since Python statements often contain spaces or other characters that are special to the shell, it is usually advised to quote command in its entirety with single quotes.

So to test this feature, I tried this in PowerShell:

> py -c 'print("Hello, World!")'

and it shows this error:

File "<string>", line 1
    print(Hello, World!)

However when I use double quotes instead it works just fine:

> py -c "print('Hello, World!')"

It seems it only happens for strings. For numbers it works fine. I think the issue here has something to do with using quotes. Why does it happen?


Solution

  • my guess is (just like in powershell) single quotes are not interpreted but strings which are strings. this means that python treats the first test py -c 'print("Hello, World!")' as all strings but py -c expects a command. whereas with double quotes python looks for functions (in your test print()) within the string and executes them.

    I did not find proof for this on the web but we have the same in powershell as this blog post describes