试图找出文件是否被另一个进程使用的问题是竞争条件的可能性。您可以检查一个文件,确定它没有被使用,然后在打开它之前,另一个进程(或线程)跳入并抓取它(甚至删除它)。
好吧,让我们假设你决定忍受这种可能性,并希望它不会发生。检查其他进程使用的文件取决于操作系统。
在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)