python - 为什么 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)
是我问题的根源吗?我相信这是我的虚拟环境......?
解决方案
请看一下:
“X 不是内部或外部命令、可运行程序或批处理文件”是什么原因?
修改系统环境变量后必须重新启动 Windows,Path
以确保所有进程都使用更新Path
的 .
通常,任何可执行文件都可以在 Python 脚本中运行,而无需使用 Windows 命令处理器cmd.exe
,这意味着无需使用shell=True
. 但是有必要指定具有完整限定文件名的可执行文件,即驱动器+路径+名称+扩展名,而不是在当前目录中的运行进程,在这种情况下python.exe
解释Python脚本。
我建议阅读函数CreateProcessA的 Microsoft 文档以及此页面上引用的其他页面,分别列在左侧。Python模块子进程的方法的所有参数,如cwd
(子进程的当前工作目录),在了解Windows内核创建进程的知识后更容易理解。
作为参数传递的 R 脚本文件名Rscript.exe
也应指定为完全限定的文件名,以便独立于进程Rscript.exe
的当前目录找到。Rscript
推荐阅读
- apache-spark - spark 2.4.4 shuffle 数据似乎没有清理干净
- scala - 在容器中使用 Jsoupbrowser 的代理身份验证问题
- php - Laravel Lighthouse 配置 - 无法找到可发布的资源
- nodatime - 如何确保 NodaTime 对象始终“字符串化”为 ISO 格式?
- kotlin - How can I define Map of String or Int in Kotlin?
- flutter - 为什么捕获此异常不起作用?
- python - 在 Python 中检测重叠高斯分布的质心
- rabbitmq - 如何在任务管理器中识别rabbitmq进程?
- java - 在java中使用hashmap检查ip地址(用户输入)的重复值
- javascript - 角度转换日期数组