【问题标题】:Set up an automated R script in a Jupyter notebook在 Jupyter 笔记本中设置自动化 R 脚本
【发布时间】:2020-12-26 09:59:01
【问题描述】:

我有一个 R 脚本,它做了大量繁重的工作,偶尔会崩溃

我想用 Python 运行它,如果失败再试一次(有合理的尝试上限)。

理想情况下,我会从 Python 3.x 执行此操作。

这是我目前的代码:

#! /usr/bin/Rscript (I added this code to the top of my file)

subprocess.call("/pathto/MyrScript.r")

我的脚本打印出一堆有用的诊断信息。

这是我想做的事情:

  1. 从 Python 启动脚本 [完成]
  2. 如果脚本在运行时失败,请重试 [未完成]

我想我可以用类似的东西来做#2

try:
  subprocess.call("/pathto/MyrScript.r")
except:
  i+=1
  if i > 5: 
    print("Tried >5 times")
  else: 
    subprocess.call("/pathto/MyrScript.r")

您能帮我介绍一下#2 的背景吗?谢谢!

【问题讨论】:

  • 我可以将一个参数从 python 传递到 R 脚本吗?

标签: python r python-3.x


【解决方案1】:

通常在 shell 中,如果执行成功则返回 0。任何大于 0 的返回码都表示某种错误。

您可以在此处阅读有关 bash 输出的更多信息(假设您正在使用 linux 环境):https://askubuntu.com/questions/892604/meaning-of-exit-0-exit-1-and-exit-2-in-a-bash-script#:~:text=With%20bash%20commands%20the%20return,return%20to%20the%20command%20line

因此,如果您的子进程调用成功,它应该返回 0。

output=1
while output!=0:
   try:
        output=subprocess.call('fileaddress')
   except:
        i+=1
        print(f'Tried {i} times')

您可以将参数传递给 R 脚本,但您必须查看您的 R 脚本才能接受来自终端的参数。实际上,您不是从 python 传递参数,而是使用子进程模块 python 正在执行 bash 命令。因此,如果您能够使用参数从终端执行 R 脚本,则可以使用子进程执行相同的操作,但将命令和参数作为列表传递,例如:subprocess.call(['ls', '-l']

【讨论】:

  • 我最终使用了 R Script 命令并从 R 终端运行
猜你喜欢
  • 1970-01-01
  • 2020-08-26
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 2021-08-05
相关资源
最近更新 更多