summaryrefslogtreecommitdiff
path: root/scripts/pidof.py
diff options
context:
space:
mode:
authorGiampaolo Rodola <g.rodola@gmail.com>2016-02-09 12:30:45 +0100
committerGiampaolo Rodola <g.rodola@gmail.com>2016-02-09 12:30:45 +0100
commit4b78815e7bd1354daa34d56e2b12276836b7cdf9 (patch)
treed79f771fcfbc251c87a1ccc60e129cdf3adfe7ae /scripts/pidof.py
parentab9f29bd2689ac9623e5ac078c880c2fae7743f3 (diff)
downloadpsutil-4b78815e7bd1354daa34d56e2b12276836b7cdf9.tar.gz
rename 'examples' dir to 'scripts'
Diffstat (limited to 'scripts/pidof.py')
-rwxr-xr-xscripts/pidof.py53
1 files changed, 53 insertions, 0 deletions
diff --git a/scripts/pidof.py b/scripts/pidof.py
new file mode 100755
index 00000000..8692a315
--- /dev/null
+++ b/scripts/pidof.py
@@ -0,0 +1,53 @@
+#!/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()