Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check what files are open in Python

I'm getting an error in a program that is supposed to run for a long time that too many files are open. Is there any way I can keep track of which files are open so I can print that list out occasionally and see where the problem is?

like image 847
Claudiu Avatar asked Jan 07 '10 20:01

Claudiu


People also ask

How do you see what files are open in Python?

The open() function is used in Python to open a file. Using the open() function is one way to check a particular file is opened or closed. If the open() function opens a previously opened file, then an IOError will be generated.

How do you check if a file is being used in Python?

In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False. Likewise, if you use if isdir() to check whether a certain file exists, the method returns False.

How do I close all open files in Python?

There is no way in python natively to track all opened files. To do that you should either track all the files yourself or always use the with statement to open files which automatically closes the file as it goes out of scope or encounters an error.


1 Answers

To list all open files in a cross-platform manner, I would recommend psutil.

#!/usr/bin/env python import psutil  for proc in psutil.process_iter():     print(proc.open_files()) 

The original question implicitly restricts the operation to the currently running process, which can be accessed through psutil's Process class.

proc = psutil.Process() print(proc.open_files()) 

Lastly, you'll want to run the code using an account with the appropriate permissions to access this information or you may see AccessDenied errors.

like image 84
jkhines Avatar answered Oct 13 '22 00:10

jkhines