簡體   English   中英

Windows 在 subprocess.call() 上找不到文件

[英]Windows can't find the file on subprocess.call()

我收到以下錯誤:

WindowsError: [Error 2] The system cannot find the file specified

我的代碼是:

subprocess.call(["<<executable file found in PATH>>"])

Windows 7,64 位。 Python 3.x 最新,穩定。

有任何想法嗎?

謝謝,

當命令是內置shell=True ,在調用中添加shell=True

例如,對於dir您可以輸入:

import subprocess
subprocess.call('dir', shell=True)

文檔中引用:

在 Windows 上您唯一需要指定shell=True時間是您希望執行的命令已內置到 shell 中(例如dircopy )。 您不需要shell=True來運行批處理文件或基於控制台的可執行文件。

在 Windows 上,我相信subprocess模塊不會在PATH查找,除非您傳遞shell=True因為它在幕后使用CreateProcess() 但是,如果您傳遞的參數可能來自程序外部,則shell=True可能存在安全風險。 為了使subprocess shutil.which仍然能夠找到正確的可執行文件,您可以使用shutil.which 假設PATH的可執行文件名為frob

subprocess.call([shutil.which('frob'), arg1, arg2])

(這適用於 Python 3.3 及更高版本。)

在 Windows 上,您必須通過 cmd.exe 調用。 正如 Apalala 所提到的,Windows 命令是在 cmd.exe 中實現的,而不是作為單獨的可執行文件。

例如

subprocess.call(['cmd', '/c', 'dir'])

/c 告訴 cmd 運行以下命令

這比使用 shell=True 更安全,后者允許 shell 注入。

如果您使用的是 powershell,則其中將是subprocess.call(['powershell','-command','dir']) Powershell 支持大部分 POSIX 命令

經過多次摸索,我發現在 64 位機器上運行 32 位版本的 python 時運行位於 C:\\Windows\\System32\\ 中的文件是一個潛在問題,因為 Windows 試圖超越該進程,並且將對 C:\\Windows\\System32 的調用重定向到 C:\\Windows\\SysWOW64。

我在這里找到了一個如何解決這個問題的例子: http : //code.activestate.com/recipes/578035-disable-file-system-redirector/

從文檔中引用:

“在 Python 3.5 之前,這三個函數組成了子進程的高級 API。您現在可以在許多情況下使用 run(),但許多現有代碼調用這些函數。”

SO:代替 subprocess.call 使用 subprocess.run for Python 3.5 及更高版本

我在調用 PHP 時遇到了同樣的問題。 原因是 PHP 不在 PATH 中,因此找不到 PHP 命令。 但是 PowerShell 發現它確實存在於當前位置,如果我信任此命令,它建議將 'PHP' 替換為 '.\\PHP'。 然后它運行良好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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