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

Cpt*_*emo 8 python r rpython rstudio

我有一些意外的行为,从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)
Run Code Online (Sandbox Code Playgroud)

# test1.py

import random, nltk

number = random.randint(1, 1000)

string = nltk.word_tokenize('home sweet home')
Run Code Online (Sandbox Code Playgroud)

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

>> Loading required package: RJSONIO
>> [1] 13.0384
>> [1] "home"  "sweet" "home"
Run Code Online (Sandbox Code Playgroud)

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

>> Loading required package: RJSONIO
>> [1] 7.211103
>> [1] "home"  "sweet" "home" 
Run Code Online (Sandbox Code Playgroud)

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

# 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
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当我打电话从RStudio脚本,Python解释器无法找到该模块nltk(这似乎是与其他同样pip安装的模块),但有没有问题导入random.

Kev*_*lsh 6

我也有这个问题.问题是我的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')

希望有所帮助!