首页 > 解决方案 > 为什么 subprocess.run 不会执行一个简单的命令?

问题描述

我跑:

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

cmd具有以下目录集的 VS Code 中的终端:

(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)是我问题的根源吗?我相信这是我的虚拟环境......?

标签: pythonrcmd

解决方案


请看一下:

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

修改系统环境变量后必须重新启动 Windows,Path以确保所有进程都使用更新Path的 .

通常,任何可执行文件都可以在 Python 脚本中运行,而无需使用 Windows 命令处理器cmd.exe,这意味着无需使用shell=True. 但是有必要指定具有完整限定文件名的可执行文件,即驱动器+路径+名称+扩展名,而不是在当前目录中的运行进程,在这种情况下python.exe解释Python脚本。

我建议阅读函数CreateProcessA的 Microsoft 文档以及此页面上引用的其他页面,分别列在左侧。Python模块进程的方法的所有参数,如cwd(子进程的当前工作目录),在了解Windows内核创建进程的知识后更容易理解。

作为参数传递的 R 脚本文件名Rscript.exe也应指定为完全限定的文件名,以便独立于进程Rscript.exe的当前目录找到。Rscript


推荐阅读