【问题标题】:Call R Script from Python with arguments使用参数从 Python 调用 R 脚本
【发布时间】:2019-03-27 13:16:07
【问题描述】:

我有一个带有代码的 r 脚本:

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

我想使用 GUI 运行它并使用这个 python 代码提供一个选择的 csv 文件

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()

但不幸的是,这不起作用。我收到此错误,但不知道出了什么问题。

  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

我不明白为什么找不到文件。

【问题讨论】:

  • 你的路径正确吗? FileNotFoundError 告诉我你可能给了它一个相对路径,但这不是文件所在的路径
  • 我添加了 filename = '"' + filename + '"' 和 filename.replace("\\", "/") 但仍然得到相同的错误。 print(filename) 给我“C:/Users/name/Desktop/file.csv”
  • Python 脚本是否在与 R 相同的环境中运行?此外,使用内置os 模块中的os.path.join() 用于os-agonstic 文件路径。检查 Python 是否可以看到带有os.path.exists() 的路径。最后,请注意,R 有自己的 GUI 模块:gWidgets2RGtk2rattle!
  • 环境变量设置不正确。 FileNotFoundError 在这里有点令人困惑。感谢您的帮助!

标签: python r


【解决方案1】:

按照 cmets 的建议,检查

  • 您的路径正确且不包含空格或奇怪的字符
  • 文件确实存在于正确的位置

...如果没有帮助,您可以尝试使用subprocess.run 而不是subprocess.call

【讨论】:

    【解决方案2】:

    我对 python 一无所知,所以我无法帮助你,但你的 Rscript 正在调用参数的第零个元素,它只是一个空字符。

    R 从 1 开始索引。

    如果我的脚本是:

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

    它会返回:

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

    你的 RScript 应该是:

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

    另外,如果这是你的整个 Rscript,那么一旦 RScript 关闭,“MyData”就会消失。如果你想在 R 中创建一个文件,你需要使用:

    write.table(<whatever>)
    

    为您的数据使用适当的参数。

    【讨论】:

    • 谢谢你。如果没有你的帮助,我可能会遇到这种情况。
    猜你喜欢
    • 2017-05-29
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多