-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #568 from karthikrev/master
example/pidof.py same as pidof cli tool mentioned in TODO:
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |