从Python运行R脚本

10

我有一个R脚本,用于生成几个图形。我想要能够从Python中执行这个脚本。

我首先尝试了以下内容:

import subprocess
subprocess.call("/.../plottingfile.R", shell=True)

这给了我以下错误:

/bin/sh: /.../plottingfile.R: Permission denied
126

我不知道数字126代表什么。所有我的文件都在桌面上,所以我认为不需要任何特殊的权限?我认为这个错误可能与cwd = none有关,但我已经更改了它,仍然出现错误。

接下来,我尝试了以下操作:

subprocess.Popen(["R --vanilla --args </.../plottingfile.R>"], shell = True)

但这也给我带来了一个错误:

/bin/sh: Syntax error: end of file unexpected.

最近我尝试了:

subprocess.Popen("konsole | /.../plottingfile.R", shell = True)

这打开了一个新的 konsole 窗口,但没有运行任何 R 脚本。此外,我收到了以下错误:


/bin/sh: /.../plottingfile.R: Permission denied
感谢。

当您在没有Python的情况下从命令行运行此脚本时,它是否有效? - wespiserA
http://stackoverflow.com/questions/37350886/simple-way-to-pass-directory-to-r-script-using-python/37351221#37351221 - BMW
4个回答

12

首要的是,确保您的platttingfile.R脚本位于一个可以访问的地方。通常它在相同的目录中。

我在互联网上阅读到有一个叫做RScript的实用程序,可用于从命令行执行R脚本。因此,为了运行脚本,您将使用Python,如下所示:

import subprocess
retcode = subprocess.call(['/path/to/RScript','/path/to/plottingfile.R'])

如果成功完成,这将返回retcode 0。 如果你的plottingfile.R返回某种输出,它将被扔到STDOUT上。 如果它启动了某种GUI,则它会出现。

如果你想捕获stdout和stderr,可以这样做:

import subprocess
proc = subprocess.Popen(['/path/to/RScript','/path/to/plottingfile.R'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()


这对我有用。请在以下链接中查看一个聪明的方法,以获取普通命令行并在字符串上使用split()创建Popen所期望的确切数组。 - jatal

3

Shell错误126是一种执行错误。

"Permission denied"表示你有一个特定的“权限问题”。

进入文件并确保R/Python能够访问它。首先,我建议尝试以下操作:

$sudo chmod 777 /.../plottingfile.R

如果代码可以运行,请给它正确但不太容易访问的权限。

如果这不起作用,请尝试将R更改为Rscript。


0
你尝试过 chmod u+x /pathTo/Rscript.R 吗?

0

通常这种工作对我来说很顺利:

subprocess.Popen("R --vanilla /PATH/plottingfile.R", shell = True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接