简体   繁体   English

从 Python (Windows) 运行 R 脚本时出现问题

[英]Problem running a R script from Python (Windows)

I've recently started programming in python for my job, so I'm quite new to it.我最近开始为我的工作使用 python 编程,所以我对它很陌生。 My goal is to create a graphic interface so that the user can run a program that I have been developing in R. The interface is done using the Tkinter module from python (version 3.3).我的目标是创建一个图形界面,以便用户可以运行我一直在 R 中开发的程序。该界面是使用 python(3.3 版)中的 Tkinter 模块完成的。

The problem comes when I have to call the R interpreter from python to run an R file that is generated (run.R file).当我必须从 python 调用 R 解释器来运行生成的 R 文件(run.R 文件)时,问题就出现了。 The curious thing is that this only happens when I try to run my script in Windows, not in Linux.奇怪的是,这只发生在我尝试在 Windows 中运行我的脚本时,而不是在 Linux 中。 In both cases, I am trying to use the os module from python.在这两种情况下,我都试图使用 python 中的 os 模块。

This is the code that is not working for Windows:这是不适用于 Windows 的代码:

os.chdir(outRW) #first I change the working directory to the one where the run.R file is

os.system("C:\R-3.6.1\bin\Rscript run.R")

When I execute this, it changes the directory successfully, but when it comes to calling the R interpreter, it shows me this error:当我执行它时,它成功地更改了目录,但是在调用 R 解释器时,它显示了这个错误:

The filename, directory name, or volume label syntax is incorrect.

However, I have tried running the "C:\\R-3.6.1\\bin\\Rscript run.R" command in the Windows Command Prompt and it works perfectly.但是,我尝试在 Windows 命令提示符中运行“C:\\R-3.6.1\\bin\\Rscript run.R”命令,它运行良好。 I have also tried adding the path to R to the environmental variables, but again I could only make it work in the Command Prompt, not with python.我还尝试将 R 的路径添加到环境变量中,但我再次只能使其在命令提示符下工作,而不能在 python 中工作。

I guess there is something very obvious that I am missing here, but I cannot see it.我想我在这里遗漏了一些非常明显的东西,但我看不到它。

Any help or comments are very much appreciated!非常感谢任何帮助或评论!

Thank you!谢谢!

Use double backslashes.使用双反斜杠。

In R you need to use double backslashes \\\\ , otherwise it'll try to interpret it as an Escape Character .R 中,您需要使用双反斜杠\\\\ ,否则它会尝试将其解释为转义字符

Use this and it will work:使用它,它将起作用:

os.system("C:\\R-3.6.1\\bin\\Rscript run.R")

Hope this helps.希望这可以帮助。

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

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