【问题标题】:RStudio doesn't load all Python modules via rPython callRStudio 不会通过 rPython 调用加载所有 Python 模块
【发布时间】: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 会话中运行代码,numberstring 的行为是否仍然会发生?
  • @BrenBarn 很好,如果我重新启动会话,我没有得到任何输出,只是错误。我更新了我的问题
  • 我无法真正调试它,因为我没有 rPython(它在 Windows 上不起作用),但我建议你尝试通过玩一个简单的方法来缩小原因.py 文件。尝试查看sys.path,看看它是否与您在外部运行程序时得到的相同等。

标签: python r rstudio


【解决方案1】:

我也有这个问题。问题是我的 bash 终端似乎调用了与 Rstudio 不同的 python。我还了解到,如果您只是尝试从 rPython 调用 Python.load(),那么使用基础 R 库中的 system() 可能会更好。

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

希望有帮助!

【讨论】:

  • 如何使用 rPython 显式调用你想要的 python?
  • 这个问题/答案应该会有所帮助:stackoverflow.com/questions/25383030/…
  • 我认为您的回答应该建议将 bash 结果与 R 结果进行比较:system("python --version")。然后描述如何解决这些差异。
猜你喜欢
  • 1970-01-01
  • 2015-09-01
  • 2012-04-19
  • 2018-11-02
  • 2018-05-04
  • 2022-08-22
  • 2012-11-07
  • 1970-01-01
  • 2010-10-13
相关资源
最近更新 更多