[英]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 文檔中它說:
啟動解釋器的第二種方法是
python -c *command* [arg]...
,它執行命令中的語句,類似於 shell 的-c
選項。 由於 Python 語句通常包含 shell 特有的空格或其他字符,因此通常建議使用單引號將整個命令引用。
所以為了測試這個特性,我在 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()
中)並執行它們。
我沒有在 web 上找到這方面的證據,但我們在 powershell 中也有相同的證據,正如 這篇博文所述
一個簡短的總結:
python -c
無關。 故障都是 PowerShell 的。CommandLine
has to be contrived by PowerShell to invoke the underlying Win32 CreateProcess
function.CommandLine
時違反直覺的 escaping 方法將從命令行 arguments 中去除雙引號,無論是否正確轉義。 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 Windows 進程通過的單字符串命令行,如此處所述。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.