0

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?

Palle Due
  • 5,929
  • 4
  • 17
  • 32
diatom
  • 35
  • 6

2 Answers2

1

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

Guenther Schmitz
  • 1,955
  • 1
  • 9
  • 23
1

Just stumbled upon this question and this awesome answer

A short summary:

  • It has nothing to do with python -c. The fault's all PowerShell's.
  • It's a known thing and has being there for years.
  • PowerShell does a lot more parsing and escaping on the command you hand it, even if you told it to treat arguments literally. And when calling a native command (in contrast to a PowerShell cmdlet, python in this case), a single string CommandLine has to be contrived by PowerShell to invoke the underlying Win32 CreateProcess function.
  • PowerShell's counter-intuitive escaping approach when creating that single-string CommandLine will strip double quotes from command line arguments, properly escaped or not.

To bypass this feature, quote with single quotes or escape all double quotes with backslashes (\"). (Not being a valid escaping syntax in PS, \" will be ignored by PowerShell but correctly interpreted by Win32 function CommandLineToArgvW when building argv array from the single-string command line that the Windows process gets passed, as documented here.)