Check for open files with Python in Linux

John Snow picture John Snow · Nov 20, 2013 · Viewed 13k times · Source

I'm looking for a way to determine which files are open in my whole system (Linux) using Python. I can't find any module that does this.

Or maybe the only way is with the command lsof?

Answer

treddy picture treddy · Nov 21, 2013

Update as of April, 2018 for more recent versions of psutil:

Newer versions of psutil now use a slightly different function name for this, open_files, as shown in the following example from their docs:

>>> import psutil
>>> f = open('file.ext', 'w')
>>> p = psutil.Process()
>>> p.open_files()
[popenfile(path='/home/giampaolo/svn/psutil/file.ext', fd=3)]

Original Answer / older version of psutil:

If you look in the documentation for the psutil python module (available on PyPI) you'll find a method that checks for open files on a given process. You'll probably want to get a list of all active PIDs as described in the related stack overflow response. Then use the method below:

get_open_files() Return regular files opened by process as a list of namedtuples including file absolute path name and file descriptor. Example:

>>> f = open('file.ext', 'w')
>>> p = psutil.Process(os.getpid())
>>> p.get_open_files()
[openfile(path='/home/giampaolo/svn/psutil/file.ext', fd=3)]

Changed in 0.2.1: OSX implementation rewritten in C; no longer requiring lsof. Changed in 0.4.1: FreeBSD implementation rewritten in C; no longer requiring lsof.

Edit: for iterating over the active PIDs psutil has another method (which is also referenced in the above previous stack overflow response):

psutil.process_iter()

Return an iterator yielding a Process class instances for all running processes on the local machine. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used.