【发布时间】:2014-08-12 08:39:16
【问题描述】:
我在 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')
我可以使用 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(它似乎与其他已安装的 pip 模块相同)但导入 random 没有问题。
【问题讨论】:
-
您使用的是 virtualenv 还是任何其他复杂的安装/库路径设置?我看到this previous question...
-
没有,据我所知。
-
即使在新的 R 会话中运行代码,
number和string的行为是否仍然会发生? -
@BrenBarn 很好,如果我重新启动会话,我没有得到任何输出,只是错误。我更新了我的问题
-
我无法真正调试它,因为我没有 rPython(它在 Windows 上不起作用),但我建议你尝试通过玩一个简单的方法来缩小原因.py 文件。尝试查看
sys.path,看看它是否与您在外部运行程序时得到的相同等。