【问题标题】:reticulate doesn't print to console in real timereticulate 不会实时打印到控制台
【发布时间】:2020-06-29 08:40:53
【问题描述】:

在循环结构中使用 Python 的 print()(或据我所知,任何其他控制台输出生成)函数并通过 R 中的 reticulate 运行代码,输出仅在执行完毕。例如,采用以下循环,每次迭代后进入休眠 1.5 秒;循环结束后,运行编号全部打印出来。将 Python 代码保存到单独的 .py 文件然后运行 ​​reticulate::py_run_file() 时也是如此。

library(reticulate)

py_run_string("
import time

for i in range(5):
   print(str(i))
   time.sleep(1.5) # sleep for 1.5 sec
")

有谁知道这种行为是从哪里来的,如果可能的话,如何规避它?

【问题讨论】:

  • 这似乎是 python 的问题。当您将其放入脚本并使用nohup thisscript.py 运行它时,您会看到输出将被保留,直到脚本完成。这只是根据我的经验。不幸的是,我不知道为什么
  • 太棒了,在print() 调用之后插入sys.stdout.flush() 确实会在每次迭代时向控制台发送状态更新。谢谢!

标签: python r reticulate console-output


【解决方案1】:

为了将来参考,通过print(..., flush = True) 强制刷新流也可以正常工作(如here 建议的那样)并导致导入 sys 过时:

library(reticulate)

py_run_string("
import time

for i in range(5):
   print(str(i), flush = True)
   time.sleep(1.5)
")

【讨论】:

    【解决方案2】:

    显然,您有时需要强制 pyhton 导出标准输出。您可以通过在您的代码中添加sys.stdout.flush() 来做到这一点:

    library(reticulate)
    
    py_run_string("
    import time
    import sys
    
    for i in range(5):
       print(str(i))
       time.sleep(1.5) # sleep for 1.5 sec
       sys.stdout.flush()
    ")
    

    see over here described with nohup

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 2012-02-07
      • 2015-05-04
      • 2016-11-19
      • 2018-07-14
      • 1970-01-01
      相关资源
      最近更新 更多