0

I'm trying to code a simple application that must read all currently open files within a certain directory. More specificly, I want to get a list of files open anywhere inside my Documents folder, but I don't want only the processes' IDs or process name, I want the full path of the open file.

The thing is I haven't quite found anything to do that. I couldn't do it neither in linux shell (using ps and lsof commands) nor using python's psutil library. None of these is giving me the information I need, which is only the path of currently open files in a dir.

Any advice?

P.S: I'm tagging this as python question (besides os related tags) because it would be a plus if it could be done using some python library.

tshepang
  • 12,111
  • 21
  • 91
  • 136
user3264316
  • 332
  • 3
  • 18
  • Are you using windows or linux? – Piotr Dabkowski Apr 06 '14 at 20:31
  • Look at this question if you haven't read it yet: http://stackoverflow.com/questions/589407/python-how-to-check-if-a-file-is-used-by-another-application – Piotr Dabkowski Apr 06 '14 at 20:42
  • Checking if files are open for writing (and therefore locked) is straightforward - see flock() or fcntl. Checking if a file is being read is harder. There are some suggestions that look worthwhile at [How to check if a file is open by another process (Java/Linux)?](http://stackoverflow.com/questions/9341505/how-to-check-if-a-file-is-open-by-another-process-java-linux). – Simon Apr 06 '14 at 20:48

1 Answers1

0

This seems to work (on Linux):

import subprocess
import shlex

cmd = shlex.split('lsof -F n +d .')
try:
    output = subprocess.check_output(cmd).splitlines()
except subprocess.CalledProcessError as err:
    output = err.output.splitlines()
output = [line[3:] for line in output if line.startswith('n./')]

# Out[3]: ['file.tmp']

it reads open files from current directory, non-recursively.

For recursive search, use +D option. Keep in mind, that it is vulnerable to race condition - when you get your ouput, situation might have changed already. It is always best to try to do something (open file), and check for failure, e.g. open file and catch exception or check for null FILE value in C.

m.wasowski
  • 6,329
  • 1
  • 23
  • 30