RStudio不通过rPython加载所有Python模块

2024-05-19 00:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在Bash和RStudio中运行同一个脚本时,我有一些意想不到的行为。在

请考虑以下几点。{1>包含两个文件夹的脚本:

# test1.R

library(rPython)

setwd("~/rpython")

python.load("test1.py")

number <- python.get("number")
string <- python.get("string")

print(sqrt(number))
print(string)

以及

^{pr2}$

我可以用Rscript test1.R从Bash调用我的R脚本,它按预期返回

>> Loading required package: RJSONIO
>> [1] 13.0384
>> [1] "home"  "sweet" "home"

如果我再次调用它会产生一个不同的随机数

>> Loading required package: RJSONIO
>> [1] 7.211103
>> [1] "home"  "sweet" "home" 

但是当我从RStudio运行同一个脚本(test1.R)时,事情变得很奇怪。这里是输出

# test1.R
> 
> library(rPython)
Loading required package: RJSONIO
> 
> setwd("~/rpython")
> 
> python.load("test1.py")
Error in python.exec(code, get.exception) : No module named nltk
> 
> number <- python.get("number")
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'number' is not defined
Error in python.get("number") : Variable not found
> string <- python.get("string")
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'string' is not defined
Error in python.get("string") : Variable not found
> 
> print(sqrt(number))
Error in print(sqrt(number)) : object 'number' not found
> print(string)
Error in print(string) : object 'string' not found

由于某些原因,当我从RStudio调用脚本时,Python解释器找不到模块nltk(似乎与其他安装的模块相同),但是导入random没有问题。在


Tags: in脚本numberhomegetstringrequirednot
1条回答
网友
1楼 · 发布于 2024-05-19 00:21:28

我也有这个问题。问题是我的bash终端似乎在调用一个不同于Rstudio的python。我也知道如果你只是想打电话Python.load()对于rPython,使用base R库中的system()可能会更好。在

  1. 找出bash终端调用的python。转到bash终端并运行which python。对我来说(OSX10.11.5),它是/usr/local/bin/python。现在我们知道了完整的路径,我们可以显式地调用它并阻止R选择可能安装在您机器某个角落的另一个版本。在
  2. 使用system()从R而不是python.load()调用bash命令,并使用脚本的完整路径。使用示例脚本名称和示例python路径,它将是system('/usr/local/bin/python /path/to/file/test.py1')

希望有帮助!在

相关问题 更多 >

    热门问题