Validating open files with Python on Linux

Hello, I am looking for a way to determine which files are open on my entire system (Linux) using Python. I can not find any module that will do this.

Or maybe the only way is with the lsof command?

Thanks!

+6
source share
1 answer

If you look in the documentation for the psutil python module (available on PyPI), you will find a method that checks to open files in this process. You probably want to get a list of all active PIDs as described in the linked answer . Then use the following method:

get_open_files () Returns regular files opened by a process as a list of named elements, including an absolute file path and a 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 version 0.2.1: implementation of OSX rewritten in C; no longer required. Changed in version 0.4.1: implementation of FreeBSD is rewritten in C; lsof is no longer required.

Edit: for iterating over active PIDs, psutil has a different method (which is also mentioned in the previous answer):

psutil.process_iter ()

Returns an iterator that provides instances of the Process class for all running processes on the local machine. Each new Process instance is created only once, and then cached into an internal table, which is updated every time it is used.

+10
source

Source: https://habr.com/ru/post/958513/


All Articles