【问题标题】:How do I catch an rpy2.rinterface.RRuntimeError in Python?如何在 Python 中捕获 rpy2.rinterface.RRuntimeError?
【发布时间】:2017-11-15 12:01:52
【问题描述】:

设置:

  • Python 3.5.3 |Continuum Analytics, Inc.| (默认,2017 年 3 月 6 日,12:15:08)
  • Mac OSX 10.13.1

问题:

我已经下载了以下R脚本https://github.com/daleroberts/heston/blob/master/heston.r 我使用包 RPy2 通过 Python 反复调用其中的一个函数。现在,对于我提供给 R 函数的一些输入,R 返回以下错误:

rpy2.rinterface.RRuntimeError:集成错误(PIntegrand,lower = 0, upper = Inf, lambda, vbar, eta, : 检测到舍入误差

如何在 Python 中捕获这个 RuntimeError?

【问题讨论】:

    标签: python r exception-handling runtime-error


    【解决方案1】:

    RRuntimeError 派生自 Exception,因此您应该能够像处理任何其他异常一样捕获它。

    try:
        # your code
    except rpy2.rinterface.RRuntimeError:
        # handle exception
    

    在 rpy2 v3.0 及更高版本中,RRuntimeError 似乎已移至别处(参见示例代码 from documentation),因此您可能需要改用它:

    try:
        # your code
    except rpy2.rinterface_lib.embedded.RRuntimeError:
        # handle exception
    

    更多信息:https://docs.python.org/3/tutorial/errors.html#handling-exceptions

    【讨论】:

    • 可能在这个路径下rpy2.rinterface.embedded.RRuntimeError
    • @wassname 是的,你可能是对的,我可能只是删除对源代码的引用,因为它最终总会过时。
    【解决方案2】:

    Python 使得捕获异常变得相对容易。

    try:
        # some code
    except Exception, e:
        # Log the exception.
    

    【讨论】:

    【解决方案3】:

    我无法让rpy2.rinterface.RRuntimeError 工作,但下面的解决方法对我有用。

    安装tryCatchLog:

    %%R
    install.packages('tryCatchLog')
    library('tryCatchLog')
    

    如果在函数中使用它:

    def test_R_error_handling():
      %R tryCatchLog( expr = result <- 'a'+2, finally = result <- -1 )
      result = ro.globalenv['result'][0]
      if result == -1:
        print(result)
        return
      else:
        print('\nFunction continued')
        return True
    

    这是关于 rpy2 错误处理的my post。我希望这对遇到同样问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      相关资源
      最近更新 更多