简体   繁体   English

使用Rscript.exe Shell在Python中执行.R脚本

[英]Execute .R script within Python using Rscript.exe shell

I have an .R file saved locally at the following path: 我有一个.R文件保存在以下路径的本地:

Rfilepath = "C:\\python\\buyback_parse_guide.r"

The command for RScript.exe is: RScript.exe的命令是:

RScriptCmd = "C:\\Program Files\\R\\R-2.15.2\\bin\\Rscript.exe --vanilla"

I tried running: 我尝试跑步:

subprocess.call([RScriptCmd,Rfilepath],shell=True)

But it returns 1 -- and the .R script did not run successfully. 但是它返回1-并且.R脚本未成功运行。 What am I doing wrong? 我究竟做错了什么? I'm new to Python so this is probably a simple syntax error... I also tried these, but they all return 1: 我是Python的新手,所以这可能是一个简单的语法错误...我也尝试过这些,但是它们都返回1:

subprocess.call('"C:\Program Files\R\R-2.15.2\bin\Rscript.exe"',shell=True)

subprocess.call('"C:\\Program Files\\R\\R-2.15.2\\bin\\Rscript.exe"',shell=True)

subprocess.call('C:\Program Files\R\R-2.15.2\bin\Rscript.exe',shell=True)

subprocess.call('C:\\Program Files\\R\\R-2.15.2\\bin\\Rscript.exe',shell=True)

Thanks! 谢谢!

The RScriptCmd needs to be just the executable, no command line arguments. RScriptCmd只需是可执行文件,而无需命令行参数。 So: 所以:

RScriptCmd = "\"C:\\Program Files\\R\\R-2.15.2\\bin\\Rscript.exe\""

Then the Rfilepath can actually be all of the arguments - and renamed: 然后,Rfilepath实际上可以是所有参数-并重命名为:

 RArguments = "--vanilla \"C:\\python\\buyback_parse_guide.r\""

It looks like you have a similar problem to mine. 看来您遇到了类似的问题。 I had to reinstall RScript to a path which has no spaces. 我必须将RScript重新安装到没有空格的路径。

See: Running Rscript via Python using os.system() or subprocess() 请参阅: 使用os.system()或subprocess()通过Python运行Rscript

This is how I worked out the communication between Python and Rscript: 这就是我计算出Python和Rscript之间的通信的方式:

part in Python: 在Python中的一部分:

from subprocess import PIPE,Popen,call
p = subprocess.Popen([ path/to/RScript.exe, path/to/Script.R, Arg1], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
out = p.communicate()
outValue = out[0]

outValue contains the output-Value after executing the Script.R 执行Script.R后, outValue包含输出值。

part in the R-Script: 在R脚本中:

args <- commandArgs(TRUE)
argument1 <- as.character(args[1])
...
write(output, stdout())

output is the variable to send to Python output是要发送给Python的变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM