【问题标题】:check if file is available (not in use by another process) with R使用 R 检查文件是否可用(未被其他进程使用)
【发布时间】:2016-02-14 22:50:16
【问题描述】:

我如何检查一个文件是否不仅存在,而且目前没有被另一个进程使用?

上下文是我每次运行代码时都将输出写入同一个文件。输出是通过调用 system() 使用外部工具创建的。

当文件被打开(因为我想检查它的内容)并且在 system() 调用之前没有关闭时,一切都挂起。我想在覆盖之前检查文件是否可用。

我正在寻找 R 解决方案,但如果它与 R 接口,我也对控制台(system() 调用)解决方案感兴趣。我的工作笔记本电脑有带有 cygwin 的窗口,所以 DOS 和 UNIX 命令都可以。

【问题讨论】:

  • 我认为您可以使用tryCatch 并在错误写入 otehr 文件或其他文件时写入文件(但仅当文件在使用时无法重写时才有效)

标签: r file


【解决方案1】:

我认为你应该检查 R 是否可以写入文件,所以检查 open = "w":

file.opened <- function(path) {
  suppressWarnings(
    "try-error" %in% class(
      try(file(path, 
               open = "w"), 
          silent = TRUE
      )
    )
  )
}

当用户打开文件时返回TRUE,否则返回FALSE

【讨论】:

    【解决方案2】:

    您可以使用 unix 命令行中的 lsof 来确定当前打开了哪些文件:

    例如:

    lsof |grep test
    
    Myprocess  1234 user   12u     REG                1,4     100000         1234567 /Users/user/Folder/test.csv
    

    会告诉您是否正在使用任何带有单词 test 的文件以及正在使用什么过程。

    这个页面有很多有用的 lsof 示例:

    http://www.thegeekstuff.com/2012/08/lsof-command-examples/


    正如您所提到的,system 可用于直接从 R 调用控制台命令,例如 lsof

    system('lsof')
    

    你需要选择你的目录/文件名,然后应用适当的逻辑来判断文件是否打开:

    try(amiopen <- system('lsof |grep test', intern=T))
    
    if(is.na(amiopen[1])==T){print('Do some stuff with this file')}
    

    使用变量作为文件名 (as per this question):

    myfile <- 'somefilename.txt'
    try(amiopen <- system(sprintf("lsof |grep %s", myfile), intern=T))
    

    【讨论】:

      猜你喜欢
      • 2021-02-10
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 2014-02-19
      • 2021-11-23
      • 2014-07-12
      相关资源
      最近更新 更多