diff options
author | Giampaolo Rodola' <g.rodola@gmail.com> | 2015-01-03 14:52:20 +0100 |
---|---|---|
committer | Giampaolo Rodola' <g.rodola@gmail.com> | 2015-01-03 14:52:20 +0100 |
commit | c8a3f82e3810b6fc5fe66ff2fae66062ddc1b539 (patch) | |
tree | 7546f30bfb503c784c90d1263f398c11fd21a4d7 | |
parent | 18230b9a3e59262655dce918193023772471061b (diff) | |
parent | 87384bab5e6324c3142fdd70eed78c5a18da0854 (diff) | |
download | psutil-c8a3f82e3810b6fc5fe66ff2fae66062ddc1b539.tar.gz |
Merge pull request #568 from karthikrev/master
example/pidof.py same as pidof cli tool mentioned in TODO:
-rwxr-xr-x | examples/pidof.py | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/examples/pidof.py b/examples/pidof.py new file mode 100755 index 00000000..c8f52999 --- /dev/null +++ b/examples/pidof.py @@ -0,0 +1,43 @@ +#!/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 /usr/bin/python +1140 1138 1136 1134 1133 1129 1127 1125 1121 1120 1119 +""" + +from __future__ import print_function +import psutil +import sys + + +def pidsof(pgm): + pids = [] + # Iterate on all proccesses and find matching cmdline and get list of + # corresponding PIDs + for proc in psutil.process_iter(): + try: + cmdline = proc.cmdline() + pid = proc.pid + except psutil.Error: + continue + if len(cmdline) > 0 and cmdline[0] == pgm: + pids.append(str(pid)) + return pids + + +def main(): + if len(sys.argv) != 2: + sys.exit('usage: %s pgm_name' % __file__) + else: + pgmname = sys.argv[1] + pids = pidsof(pgmname) + print(" ".join(pids)) + +if __name__ == '__main__': + main() |