Last Updated: February 25, 2016
·
3.097K
· filosottile

List all currently running Python scripts

def running_python_scripts():
    for p in psutil.process_iter():
        if not p.cmdline: continue
        if not os.path.basename(p.cmdline[0]).startswith('python'):
            continue
        try: cwd = p.getcwd()
        except psutil._error.AccessDenied: continue
        for n, arg in enumerate(p.cmdline[1:]):
            if arg == '--':
                if len(p.cmdline) > n+1 and p.cmdline[n+1] != '-':
                    path = p.cmdline[n+1]
                    yield os.path.normpath(os.path.join(cwd, path))
                break
            if arg in ('-c', '-m', '-'): break
            if arg.startswith('-'): continue
            yield os.path.normpath(os.path.join(cwd, arg))
            break

This is a simple generator that will use psutil to get a list of the running python scripts, returned as absolute paths. It attempts (probably correctly) to parse the Python invocation command line.

Will consider "python binaries" any executable that matches python*. Will skip any process it can't get the CWD of (probably catches only processes by the same user, or all if you run it as root)