网状不会实时打印到控制台

fde*_*sch 5 python r console-output reticulate

print()在循环结构中使用 Python 的(或据我所知,任何其他控制台输出生成)函数并通过R 中的网状运行代码,输出仅在执行完成后打印。例如,采用以下循环,每次迭代后进入休眠状态 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
")
Run Code Online (Sandbox Code Playgroud)

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

fde*_*sch 7

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

library(reticulate)

py_run_string("
import time

for i in range(5):
   print(str(i), flush = True)
   time.sleep(1.5)
")
Run Code Online (Sandbox Code Playgroud)


lok*_*oki 5

显然,您有时需要强制 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()
")
Run Code Online (Sandbox Code Playgroud)

看这里用 nohup 描述