简体   繁体   中英

Call R Script from Python with arguments

I have ar Script with the code:

args = commandArgs(trailingOnly=TRUE)
myData <- read.csv(file=args[0])

I want to run this using a GUI and deliver a choosen csv file with this python code

from tkinter import filedialog
from tkinter import *
import subprocess

window = Tk()
window.geometry('500x200')
window.title("Wordcloud Creator")
lbl = Label(window, text="1. Please prepare a CSV (-Trennzeichen) file with the columns untgscod, berpos, SpezX3")
lbl.grid(column=0, row=0)
def runScript():
    filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("csv files","*.csv"),("all files","*.*")))
    subprocess.call(['Rscript', 'C:/Users/Name/Desktop/R-GUI/test.r', filename])
btn = Button(window, text="Select a file and start Cloud creation", command=runScript())
btn.grid(column=0, row=1)
window.mainloop()

But unfortunately this is not working. I get this error but do not know what is wrong.

  File "c:\Users\name\.vscode\extensions\ms-python.python-2019.2.5558\pythonFiles\lib\python\ptvsd\_vendored\pydevd\_pydev_bundle\pydev_monkey.py", line 444, in new_CreateProcess
    return getattr(_subprocess, original_name)(app_name, patch_arg_str_win(cmd_line), *args)
FileNotFoundError: [WinError 2] The system cannot find the file specified

I do not see why the file cannot be found.

As suggested in comments, check that

  • your paths are correct and do not contain empty spaces or weird characters
  • files do exist in correct location

...and if it doesn´t help, you could try to use subprocess.run instead of subprocess.call .

I don't know anything about python, so I can't help you there, but your Rscript is calling the zeroth element of your arguments, which is just an empty character.

R starts indexing at 1.

so if my script was:

args <- commandArgs(trailingOnly = TRUE)
print(args[0])

it would return:

[1] character(0) # this is R telling you that the atomic is a character, but it has zero length

Your RScript should be:

args <- commandArgs(trailingOnly = TRUE)
MyData <- read.csv(file = args[1])

Also, if that's your whole Rscript, 'MyData' is going to disappear as soon as that RScript closes. If you want to create a file in R, you'll need to use:

write.table(<whatever>)

with the appropriate arguments for your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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