【问题标题】:Reticulate - Get Python result without assigning to variableReticulate - 在不分配给变量的情况下获取 Python 结果
【发布时间】:2020-01-16 04:20:42
【问题描述】:

如果可能的话,我想在 R 中打印 python 代码的结果(不分配给变量)。

这行得通:

library(reticualte)
py_run_string("print(2)")
2

这行得通:

p = py_run_string("x = 2")
p$x
2

我希望这个工作:

py_run_string("2")
2

背景:

即使不使用(打印),我也想阅读完整的 python 代码并捕获输出。

如果我打开 Python3.7 Shell 并仅执行“2”作为命令,输出将为“2”。这里是空的。

Github 请求链接:https://github.com/rstudio/reticulate/issues/595

【问题讨论】:

    标签: python r reticulate


    【解决方案1】:

    在尝试过这个之后,我会选择no

    试过了:

    return(
        py_run_string("2")
    )
    

    试过了:

    f <- function() {
       return( 
           py_run_string("2")
       )
    }
    
    f()
    

    std out 中似乎没有任何内容

    对比:

    b <- function() {
       return(2)
    }
    
    b()
    
    # Out[]:  2
    

    我猜它正在访问 python 的 local() 变量。

    还有:

    library(reticulate)
    
    py_run_string("2")
    ls()
    # Out[1]:   None
    
    
    a <- 3
    ls()
    # Out[2]:   'a'
    

    R 的局部变量中没有任何内容代表 py_run_string() 输出

    Github 请求链接:https://github.com/rstudio/reticulate/issues/595

    【讨论】:

    • 感谢您的回答,非常感谢。我也在 Github 上打开了一个问题。如果那里没有更新,我会接受你的回答,好吗?
    • 是的,没关系。仅供参考,我认为在 github 问题上有一种方法可以将它们标记为功能请求
    • 我进行了编辑。 (不小心对你的回答也sry)。
    • 不确定您是否在 Github 上收到通知。 Kevin Ushey 提供了答案。
    【解决方案2】:

    我在 Github 上从 Kevin Ushey 那里得到了答案。

    library(reticulate)
    
    py_evaluate <- function(code) {
      builtins <- import_builtins(convert = TRUE)
      globals <- py_eval("globals()", convert = FALSE)
      locals <- globals
      parsed <- builtins$compile(code, "<string>", "single")
      builtins$eval(parsed, globals, locals)
    }
    
    py_evaluate("2")
    

    请看这里:https://github.com/rstudio/reticulate/issues/595#issuecomment-531888843

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-08
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多