Fwd: is file open in system ? - other than lsof
bvidinli
bvidinli at gmail.com
Fri Apr 18 05:45:03 EDT 2008
the idea of eg does not work for me because,
what i do:
get list of files,
check 1st file open ?
process 1st file, (this may take several seconds... )
check 2nd file open? i have to check it here, because 2nd file may be
opened while i process file 1
process 2nd file, (this may take several seconds... )
and so on.. ....
in this case, having list of open files at begining of processes is useless...
anyway thanks.
---------- Forwarded message ----------
From: Nick Craig-Wood <nick at craig-wood.com>
Date: 17.Nis.2008 19:30
Subject: Re: is file open in system ? - other than lsof
To: python-list at python.org
Thomas Guettler <hv at tbz-pariv.de> wrote:
> bvidinli schrieb:
> > is there a way to find out if file open in system ? -
> > please write if you know a way other than lsof. because lsof if
slow for me.
> > i need a faster way.
> > i deal with thousands of files... so, i need a faster / python
way for this.
> > thanks.
>
> On Linux there are symlinks from /proc/PID/fd to the open
> files. You could use this:
>
> #!/usr/bin/env python
> import os
> pids=os.listdir('/proc')
> for pid in sorted(pids):
> try:
> int(pid)
> except ValueError:
> continue
> fd_dir=os.path.join('/proc', pid, 'fd')
> for file in os.listdir(fd_dir):
> try:
> link=os.readlink(os.path.join(fd_dir, file))
> except OSError:
> continue
> print pid, link
Unfortunately I think that is pretty much exactly what lsof does so is
unlikely to be any faster!
However if you have 1000s of files to check you only need to do the
above scan once and build a dict with all open files in whereas lsof
will do it once per call so that may be a useful speedup.
Eg
------------------------------------------------------------
import os
pids=os.listdir('/proc')
open_files = {}
for pid in sorted(pids):
try:
int(pid)
except ValueError:
continue
fd_dir=os.path.join('/proc', pid, 'fd')
try:
fds = os.listdir(fd_dir)
except OSError:
continue
for file in fds:
try:
link=os.readlink(os.path.join(fd_dir, file))
except OSError:
continue
if not os.path.exists(link):
continue
open_files.setdefault(link, []).append(pid)
for link in sorted(open_files.keys()):
print "%s : %s" % (link, ", ".join(map(str, open_files[link])))
------------------------------------------------------------
You might want to consider http://pyinotify.sourceforge.net/ depending
on exactly what you are doing...
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list
--
İ.Bahattin Vidinli
Elk-Elektronik Müh.
-------------------
iletisim bilgileri (Tercih sirasina gore):
skype: bvidinli (sesli gorusme icin, www.skype.com)
msn: bvidinli at iyibirisi.com
yahoo: bvidinli
+90.532.7990607
+90.505.5667711
More information about the Python-list
mailing list