third_party/python/psutil/examples/pidof.py
author Andrew Halberstadt <ahalberstadt@mozilla.com>
Tue, 23 May 2017 15:34:24 -0400
changeset 583184 c84192848eca7948ec19ebb0a5328fb66d36531c
parent 286873 python/psutil/examples/pidof.py@2eea7ab5228dde61fdc8706ea8452df10da6dd1d
permissions -rwxr-xr-x
Bug 1346025 - Move vendored python modules from /python to /third_party/python MozReview-Commit-ID: 2rJafmwysUY

#!/usr/bin/env python

# Copyright (c) 2009, Giampaolo Rodola', karthikrev. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.


"""
A clone of 'pidof' cmdline utility.
$ pidof python
1140 1138 1136 1134 1133 1129 1127 1125 1121 1120 1119
"""

from __future__ import print_function
import psutil
import sys


def pidof(pgname):
    pids = []
    for proc in psutil.process_iter():
        # search for matches in the process name and cmdline
        try:
            name = proc.name()
        except psutil.Error:
            pass
        else:
            if name == pgname:
                pids.append(str(proc.pid))
                continue

        try:
            cmdline = proc.cmdline()
        except psutil.Error:
            pass
        else:
            if cmdline and cmdline[0] == pgname:
                pids.append(str(proc.pid))

    return pids


def main():
    if len(sys.argv) != 2:
        sys.exit('usage: %s pgname' % __file__)
    else:
        pgname = sys.argv[1]
    pids = pidof(pgname)
    if pids:
        print(" ".join(pids))

if __name__ == '__main__':
    main()