python判断文件是否打开_在Python中检查文件是否未打开(未被其他进程使用)

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

好吧,让我们假设你决定忍受这种可能性,并希望它不会发生。检查其他进程使用的文件取决于操作系统。

在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:

flist = proc.get_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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值