gpt4 book ai didi

python - 检查文件是否未打开或未被其他进程使用

转载 作者:IT老高 更新时间:2023-10-28 21:34:48 27 4
gpt4 key购买 nike

我的申请,我有以下要求:1. 有一个线程会定期将一些日志记录在文件中。日志文件将在一定的时间间隔内翻转。用于保持日志文件较小。2.还有另外一个线程也会定期处理这些日志文件。例如:将日志文件移动到其他地方,解析日志内容生成一些日志报告。

但是,有一个条件是第二个线程无法处理用于记录日志的日志文件。在代码方面,伪代码类似如下:

#code in second thread to process the log files
for logFile in os.listdir(logFolder):
if not file_is_open(logFile) or file_is_use(logFile):
ProcessLogFile(logFile) # move log file to other place, and generate log report....

那么,我如何检查文件是否已经打开或被其他进程使用?我在互联网上做了一些研究。并有一些结果:

try:
myfile = open(filename, "r+") # or "a+", whatever you need
except IOError:
print "Could not open file! Please close Excel!"

我试过这段代码,但不管我使用“r+”还是“a+”标志,它都不起作用

try:
os.remove(filename) # try to remove it directly
except OSError as e:
if e.errno == errno.ENOENT: # file doesn't exist
break

此代码可以工作,但无法达到我的要求,因为我不想删除文件以检查它是否打开。

最佳答案

试图找出一个文件是否正被另一个进程使用的一个问题是存在竞争条件的可能性。你可以检查一个文件,确定它没有被使用,然后就在你打开它之前,另一个进程(或线程)跳进来捕获它(甚至删除它)。

好的,假设您决定接受这种可能性并希望它不会发生。检查其他进程正在使用的文件取决于操作系统。

在 Linux 上这相当容易,只需遍历/proc 中的 PID。下面是一个生成器,它对特定 PID 正在使用的文件进行迭代:

def iterate_fds(pid):
dir = '/proc/'+str(pid)+'/fd'
if not os.access(dir,os.R_OK|os.X_OK): return

for fds in os.listdir(dir):
for fd in fds:
full_name = os.path.join(dir, fd)
try:
file = os.readlink(full_name)
if file == '/dev/null' or \
re.match(r'pipe:\[\d+\]',file) or \
re.match(r'socket:\[\d+\]',file):
file = None
except OSError as err:
if err.errno == 2:
file = None
else:
raise(err)

yield (fd,file)

在 Windows 上并不是那么简单,API 没有发布。有一个 sysinternals 工具 (handle.exe) 可以使用,但我推荐 PyPi 模块 psutil,它是可移植的(即它也可以在 Linux 上运行,并且可能在其他操作系统上):

import psutil

for proc in psutil.process_iter():
try:
# this returns the list of opened files by the current process
flist = proc.open_files()
if flist:
print(proc.pid,proc.name)
for nt in flist:
print("\t",nt.path)

# This catches a race condition where a process ends
# before we can examine its files
except psutil.NoSuchProcess as err:
print("****",err)

关于python - 检查文件是否未打开或未被其他进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11114492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com