Nithya
Nithya

Reputation: 644

python--can we find the directory of running processes using psutil?

I just want to kill all running "python" processes which are running from particular directory.. Means the files(sample.py) resides in specific folder.

For ex: C:\myFolder\* 

Using psutil can we find the path of the processes or kill all the process which are from C:\myFolder\* except some processess?

 import psutil
 for process in psutil.process_iter():
    print process.cmdline:

Upvotes: 3

Views: 8467

Answers (2)

Y. Du
Y. Du

Reputation: 11

If the scripts path in cmdline[1] is not an absolute path, you can use cwd() from psutil to get the working dir, after that, join the dir string with the script path string, and then you can get the location of the python scripts.

Upvotes: 1

Nabeel Ahmed
Nabeel Ahmed

Reputation: 19252

As per the comment, if you want to find file location for the running python scripts - use psutil.Process.name() == 'python' to filter the python processes. Then use os.path.abspath() to get the full path.

The following code example might work:

import psutil
import os

"""
Python script path using psutil
"""

processes = filter(lambda p: psutil.Process(p).name() == "python", psutil.pids())

scripts = []
paths = []
for pid in processes:
    try:
        scripts.append(psutil.Process(pid).cmdline()[1])
    except IndexError:
    pass

for script in scripts:
    paths.append(os.path.abspath(script))

print paths

Upvotes: 1

Related Questions