簡體   English   中英

為什么 subprocess.run 不會執行一個簡單的命令?

[英]Why won't subprocess.run execute a simple command?

我跑:

Rscript hello_world.R

從我的cmd終端,目錄是:

C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara>

腳本運行良好。

但是,我希望 Python 運行它並將這個小腳本放在與上面相同的目錄中:

import subprocess
subprocess.run(['Rscript', 'hello_world.R'])

但是,當我從 VS Code 運行它時出現此錯誤:

Exception has occurred: FileNotFoundError
[WinError 2] The system cannot find the file specified

我接下來嘗試了:

subprocess.run(['Rscript', 'hello_world.R'], shell=True)

但我得到了:

'Rscript' is not recognized as an internal or external command, operable program or batch file.

作為參考,我在路徑中添加了以下內容:

C:\Program Files\R\R-3.6.3\bin\x64

我剛試過跑步

Rscript hello_world.R

來自 VS Code 中的cmd終端,該終端具有以下目錄集:

(polgara) C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara>

這也給出了錯誤:

'Rscript' is not recognized as an internal or external command, operable program or batch file.

一開始的(polgara)會是我問題的根源嗎? 我相信這是我的虛擬環境......?

請看一下:

“X 不是內部或外部命令、可運行程序或批處理文件”是什么原因?

修改系統環境變量Path后必須重新啟動 Windows 以確保所有進程都使用更新的Path

通常,任何可執行文件都可以在 Python 腳本中運行,而無需使用 Windows 命令處理器cmd.exe ,這意味着不使用shell=True 但是有必要指定具有完整限定文件名的可執行文件,即驅動器+路徑+名稱+擴展名,而不是在運行進程的當前目錄中,在這種情況下是python.exe解釋Python腳本。

我建議閱讀有關 function CreateProcessA的 Microsoft 文檔以及此頁面上引用的其他頁面,分別列在左側。 通過 Windows Z50484C19F1AFDAF3841A0D821ED393D2 了解有關創建進程的知識,Python 模塊進程(如cwd (子進程的當前工作目錄))的方法的所有參數更容易理解。

作為參數傳遞給Rscript.exe的 R 腳本文件名也應指定為由Rscript.exe找到的完整限定文件名,而與Rscript進程的當前目錄無關。

暫無
暫無

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

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