Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用R检查文件是否可用(未被其他进程使用)_R_File - Fatal编程技术网

使用R检查文件是否可用(未被其他进程使用)

使用R检查文件是否可用(未被其他进程使用),r,file,R,File,如何检查一个文件是否不仅存在,而且目前未被另一个进程使用 上下文是每次运行代码时,我都将输出写入同一个文件。通过调用system(),使用外部工具创建输出 当文件被打开(因为我想检查它的内容)并且在system()调用之前没有关闭时,所有的东西都会挂起。我想在覆盖之前检查文件是否可用 我正在寻找一个R解决方案,但如果它与R接口,我也对控制台(system()call)解决方案感兴趣。我的工作笔记本电脑有带cygwin的windows,所以DOS和UNIX命令都可以 您可以使用unix命令行中的l

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

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

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


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

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

例如:

lsof |grep test

Myprocess  1234 user   12u     REG                1,4     100000         1234567 /Users/user/Folder/test.csv
将向您显示是否正在使用任何带有单词test的文件以及使用哪个进程

本页有许多关于lsof的有用示例:


正如您所提到的,系统可用于直接从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')}

try(amiopen我想你应该检查R是否可以写入文件,所以检查
open=“w”


file.opened我认为您可以使用
tryCatch
并在错误时写入文件写入otehr文件或smthing(但只有在使用时无法重写文件时才有效)
myfile <- 'somefilename.txt'
try(amiopen <- system(sprintf("lsof |grep %s", myfile), intern=T))
file.opened <- function(path) {
  suppressWarnings(
    "try-error" %in% class(
      try(file(path, 
               open = "w"), 
          silent = TRUE
      )
    )
  )
}