为什么有时在 PowerShell(以及命令提示符)中使用单引号将命令括在 `python -c [command]` 中时不起作用?

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)?

Python docs 中说:

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.

为了测试这个功能,我在 PowerShell 中尝试了这个:

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

它显​​示了这个错误:

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

然而,当我使用双引号时,它工作得很好:

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

似乎只发生在字符串上。对于数字,它工作正常。我认为这里的问题与使用引号有关。为什么会这样?

我的猜测是(就像在 powershell 中一样)不解释单引号,而是解释字符串。这意味着 python 将第一个测试 py -c 'print("Hello, World!")' 视为所有字符串,但 py -c 需要一个命令。而使用双引号 python 在字符串中查找函数(在您的测试 print() 中)并执行它们。

我没有在网上找到这方面的证据,但我们在 powershell 中拥有与 this blog post describes

相同的证据

刚刚偶然发现this question and this awesome answer

简短摘要:

  • python -c无关。故障全是 PowerShell 的。
  • 这是众所周知的事情,已经存在多年了。
  • PowerShell 对您传递给它的命令进行了更多的解析和转义,即使您告诉它按字面意思处理参数也是如此。当调用本机命令时(与 PowerShell cmdlet 相反,在这种情况下为 python),PowerShell 必须设计 单个字符串 CommandLine 来调用底层 Win32 CreateProcess 函数。
  • PowerShell 在创建 单字符串 CommandLine 时的反直觉转义方法将从命令行参数中去除双引号,无论是否正确转义。

要绕过此功能,请用单引号引用或用反斜杠转义所有双引号 (\")。 (在 PS 中不是有效的转义语法,\" 将被 PowerShell 忽略,但在从 Windows 流程获得通过,如记录 here。)