簡體   English   中英

為什么有時在 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 文檔中它說:

啟動解釋器的第二種方法是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 的。
  • 這是眾所周知的事情,並且已經存在多年。
  • PowerShell 會根據您提交的命令進行更多的解析和 escaping,即使您告訴它按字面意思對待 arguments。 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 在創建單字符串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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM