RStudio无法通过rPython调用加载所有Python模块

8 投票
1 回答
4852 浏览
提问于 2025-04-18 10:38

我在用 Bash 和 RStudio 运行同一个脚本时,遇到了一些意想不到的情况。

请看下面的内容。我有一个文件夹 "~/rpython",里面有两个脚本:

# test1.R

library(rPython)

setwd("~/rpython")

python.load("test1.py")

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

print(sqrt(number))
print(string)

# test1.py

import random, nltk

number = random.randint(1, 1000)

string = nltk.word_tokenize('home sweet home')

我可以在 Bash 中用 Rscript test1.R 来调用我的 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 这个模块(其他用 pip 安装的模块似乎也有同样的问题),但导入 random 模块却没有问题。

1 个回答

6

我也遇到过这个问题。问题在于我的bash终端似乎调用的是一个和Rstudio不一样的python。我还发现,如果你只是想从rPython中调用Python.load(),那么用R自带的system()函数可能会更好。

  1. 首先,找出你的bash终端正在调用哪个python。打开bash终端,输入 which python。对我来说(OS X 10.11.5),它显示的是 /usr/local/bin/python。现在我们知道了完整路径,可以明确调用这个python,避免R选择你电脑上其他地方可能安装的版本。
  2. 在R中使用 system() 来调用bash命令,而不是用 python.load(),并且要使用你脚本的完整路径。用你提供的脚本名和我提到的python路径,应该是 system('/usr/local/bin/python /path/to/file/test.py1')

希望这能帮到你!

撰写回答