监视对 R 中文件的更改类似于尾部“跟随”

问题描述

我想知道是否有一种方法可以从 R 中监视文件内容,类似于 Linux 终端中 val uri = "@drawable/pic_top${i+1}" val imageResource = activity.resources.getIdentifier(uri,null,activity.packageName) val res = activity.getResources().getDrawable(imageResource) holder.view.imgDigit.setimageDrawable(res) (详细信息 here)的行为。

具体来说,我想要一个可以传递文件路径的函数

  • 文件的最后 tail -f 行打印到控制台
  • 按住控制台
  • 继续打印添加的任何新行

有一些悬而未决的问题,例如“如果文件中先前打印的行被修改怎么办?”老实说,我不确定 n 是如何处理的,但我对将日志文件流式传输到控制台很感兴趣,因此这与我目前的使用情况无关。

我在 tail -f?readLines 文档中环顾四周,我觉得我已经接近了,但我不太明白。另外,我无法想象我是第一个想要这样做的人,所以也许有一个既定的最佳实践(甚至是现有的功能)。非常感谢任何帮助。

谢谢!

解决方法

我使用 processx 包在这方面取得了进展。我创建了一个名为 fswatch.R 的 R 脚本:

library(processx)

monitor <- function(fpath = "test.csv",wait_monitor = 1000 * 60 * 2){
  system(paste0("touch ",fpath))
  
  print_last <- function(fpath){
    con <- file(fpath,"r",blocking = FALSE)
    lines <- readLines(con)
    print(lines[length(lines)])
    close(con)
  }
  
  if(file.exists(fpath)){
    print_last(fpath)
  }
  
  p <- process$new("fswatch",fpath,stdin = "|",stdout = "|",stderr = "|")
  
  while(
      # TRUE
      p$is_alive() & 
      file.exists(fpath)
    ){
    p$poll_io(wait_monitor)
    p$read_output()
    
    print_last(fpath)
    
    # call poll_io twice otherwise endless loop :shrug:
    p$poll_io(wait_monitor)
    p$read_output()
  }

  p$kill()
}

monitor()

然后我在 RStudio 中将脚本作为“作业”运行。

每次我写信给 test.csv 时,作业都会打印最后一行。我通过删除日志文件来停止监控:

log_path <- "test.csv"
write.table('1',log_path,sep = ",",col.names = FALSE,append = TRUE,row.names = FALSE)
write.table("2",row.names = FALSE)
unlink(log_path)