使用网状包从 R 调用 Python
Calling Python from R with reticulate package
我想在 R 中执行一个 Python 脚本。我已经安装了 reticulate 并测试了 Python 版本已经在我的 R 会话中正确初始化。
py_config()
returns以下
python: C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate/python.exe
libpython: C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate/python36.dll
pythonhome: C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate
version: 3.6.10 |Anaconda, Inc.| (default, Jan 7 2020, 15:18:16) [MSC v.1916 64 bit (AMD64)]
Architecture: 64bit
numpy: C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate/Lib/site-packages/numpy
numpy_version: 1.18.1
现在,当我调用 Python 脚本时
py_run_file("PythonScript.py")
我在 R 中遇到以下错误
Error in py_run_file_impl(file, local, convert) :
ModuleNotFoundError: No module named 'requests'
我知道我需要安装请求包,但如何在我初始化的特定 Python 版本中安装它?
您需要先安装python模块requests
。
如果你安装了python,你应该已经安装了pip。
您可以在命令行中通过 运行 pip install requests
安装模块。
您可以编写一个函数来收集丢失的包并安装它们:
run_python_file <- function(python_file){
a = try(reticulate::py_run_file(python_file),silent=TRUE)
if(inherits(a,"try-error")& grepl("ModuleNotFoundError",a)){
system(sprintf("python -m pip install %s",gsub(".* |\W","",c(a))))
run_python_file(python_file)
}
else a
}
run_python_file("PythonScript.py")
我想在 R 中执行一个 Python 脚本。我已经安装了 reticulate 并测试了 Python 版本已经在我的 R 会话中正确初始化。
py_config()
returns以下
python: C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate/python.exe
libpython: C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate/python36.dll
pythonhome: C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate
version: 3.6.10 |Anaconda, Inc.| (default, Jan 7 2020, 15:18:16) [MSC v.1916 64 bit (AMD64)]
Architecture: 64bit
numpy: C:/Users/username/AppData/Local/r-miniconda/envs/r-reticulate/Lib/site-packages/numpy
numpy_version: 1.18.1
现在,当我调用 Python 脚本时
py_run_file("PythonScript.py")
我在 R 中遇到以下错误
Error in py_run_file_impl(file, local, convert) :
ModuleNotFoundError: No module named 'requests'
我知道我需要安装请求包,但如何在我初始化的特定 Python 版本中安装它?
您需要先安装python模块requests
。
如果你安装了python,你应该已经安装了pip。
您可以在命令行中通过 运行 pip install requests
安装模块。
您可以编写一个函数来收集丢失的包并安装它们:
run_python_file <- function(python_file){
a = try(reticulate::py_run_file(python_file),silent=TRUE)
if(inherits(a,"try-error")& grepl("ModuleNotFoundError",a)){
system(sprintf("python -m pip install %s",gsub(".* |\W","",c(a))))
run_python_file(python_file)
}
else a
}
run_python_file("PythonScript.py")