-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
__init__.py
2460 lines (2088 loc) · 85.9 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""psutil is a cross-platform library for retrieving information on
running processes and system utilization (CPU, memory, disks, network,
sensors) in Python. Supported platforms:
- Linux
- Windows
- macOS
- FreeBSD
- OpenBSD
- NetBSD
- Sun Solaris
- AIX
Works with Python versions 2.7 and 3.6+.
"""
from __future__ import division
import collections
import contextlib
import datetime
import functools
import os
import signal
import subprocess
import sys
import threading
import time
try:
import pwd
except ImportError:
pwd = None
from . import _common
from ._common import AIX
from ._common import BSD
from ._common import CONN_CLOSE
from ._common import CONN_CLOSE_WAIT
from ._common import CONN_CLOSING
from ._common import CONN_ESTABLISHED
from ._common import CONN_FIN_WAIT1
from ._common import CONN_FIN_WAIT2
from ._common import CONN_LAST_ACK
from ._common import CONN_LISTEN
from ._common import CONN_NONE
from ._common import CONN_SYN_RECV
from ._common import CONN_SYN_SENT
from ._common import CONN_TIME_WAIT
from ._common import FREEBSD # NOQA
from ._common import LINUX
from ._common import MACOS
from ._common import NETBSD # NOQA
from ._common import NIC_DUPLEX_FULL
from ._common import NIC_DUPLEX_HALF
from ._common import NIC_DUPLEX_UNKNOWN
from ._common import OPENBSD # NOQA
from ._common import OSX # deprecated alias
from ._common import POSIX # NOQA
from ._common import POWER_TIME_UNKNOWN
from ._common import POWER_TIME_UNLIMITED
from ._common import STATUS_DEAD
from ._common import STATUS_DISK_SLEEP
from ._common import STATUS_IDLE
from ._common import STATUS_LOCKED
from ._common import STATUS_PARKED
from ._common import STATUS_RUNNING
from ._common import STATUS_SLEEPING
from ._common import STATUS_STOPPED
from ._common import STATUS_TRACING_STOP
from ._common import STATUS_WAITING
from ._common import STATUS_WAKING
from ._common import STATUS_ZOMBIE
from ._common import SUNOS
from ._common import WINDOWS
from ._common import AccessDenied
from ._common import Error
from ._common import NoSuchProcess
from ._common import TimeoutExpired
from ._common import ZombieProcess
from ._common import memoize_when_activated
from ._common import wrap_numbers as _wrap_numbers
from ._compat import PY3 as _PY3
from ._compat import PermissionError
from ._compat import ProcessLookupError
from ._compat import SubprocessTimeoutExpired as _SubprocessTimeoutExpired
from ._compat import long
if LINUX:
# This is public API and it will be retrieved from _pslinux.py
# via sys.modules.
PROCFS_PATH = "/proc"
from . import _pslinux as _psplatform
from ._pslinux import IOPRIO_CLASS_BE # NOQA
from ._pslinux import IOPRIO_CLASS_IDLE # NOQA
from ._pslinux import IOPRIO_CLASS_NONE # NOQA
from ._pslinux import IOPRIO_CLASS_RT # NOQA
elif WINDOWS:
from . import _pswindows as _psplatform
from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # NOQA
from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # NOQA
from ._psutil_windows import HIGH_PRIORITY_CLASS # NOQA
from ._psutil_windows import IDLE_PRIORITY_CLASS # NOQA
from ._psutil_windows import NORMAL_PRIORITY_CLASS # NOQA
from ._psutil_windows import REALTIME_PRIORITY_CLASS # NOQA
from ._pswindows import CONN_DELETE_TCB # NOQA
from ._pswindows import IOPRIO_HIGH # NOQA
from ._pswindows import IOPRIO_LOW # NOQA
from ._pswindows import IOPRIO_NORMAL # NOQA
from ._pswindows import IOPRIO_VERYLOW # NOQA
elif MACOS:
from . import _psosx as _psplatform
elif BSD:
from . import _psbsd as _psplatform
elif SUNOS:
from . import _pssunos as _psplatform
from ._pssunos import CONN_BOUND # NOQA
from ._pssunos import CONN_IDLE # NOQA
# This is public writable API which is read from _pslinux.py and
# _pssunos.py via sys.modules.
PROCFS_PATH = "/proc"
elif AIX:
from . import _psaix as _psplatform
# This is public API and it will be retrieved from _pslinux.py
# via sys.modules.
PROCFS_PATH = "/proc"
else: # pragma: no cover
raise NotImplementedError('platform %s is not supported' % sys.platform)
# fmt: off
__all__ = [
# exceptions
"Error", "NoSuchProcess", "ZombieProcess", "AccessDenied",
"TimeoutExpired",
# constants
"version_info", "__version__",
"STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
"STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
"STATUS_WAKING", "STATUS_LOCKED", "STATUS_WAITING", "STATUS_LOCKED",
"STATUS_PARKED",
"CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
"CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
"CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE",
# "CONN_IDLE", "CONN_BOUND",
"AF_LINK",
"NIC_DUPLEX_FULL", "NIC_DUPLEX_HALF", "NIC_DUPLEX_UNKNOWN",
"POWER_TIME_UNKNOWN", "POWER_TIME_UNLIMITED",
"BSD", "FREEBSD", "LINUX", "NETBSD", "OPENBSD", "MACOS", "OSX", "POSIX",
"SUNOS", "WINDOWS", "AIX",
# "RLIM_INFINITY", "RLIMIT_AS", "RLIMIT_CORE", "RLIMIT_CPU", "RLIMIT_DATA",
# "RLIMIT_FSIZE", "RLIMIT_LOCKS", "RLIMIT_MEMLOCK", "RLIMIT_NOFILE",
# "RLIMIT_NPROC", "RLIMIT_RSS", "RLIMIT_STACK", "RLIMIT_MSGQUEUE",
# "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIMIT_SIGPENDING",
# classes
"Process", "Popen",
# functions
"pid_exists", "pids", "process_iter", "wait_procs", # proc
"virtual_memory", "swap_memory", # memory
"cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count", # cpu
"cpu_stats", # "cpu_freq", "getloadavg"
"net_io_counters", "net_connections", "net_if_addrs", # network
"net_if_stats",
"disk_io_counters", "disk_partitions", "disk_usage", # disk
# "sensors_temperatures", "sensors_battery", "sensors_fans" # sensors
"users", "boot_time", # others
]
# fmt: on
__all__.extend(_psplatform.__extra__all__)
# Linux, FreeBSD
if hasattr(_psplatform.Process, "rlimit"):
# Populate global namespace with RLIM* constants.
from . import _psutil_posix
_globals = globals()
_name = None
for _name in dir(_psutil_posix):
if _name.startswith('RLIM') and _name.isupper():
_globals[_name] = getattr(_psutil_posix, _name)
__all__.append(_name)
del _globals, _name
AF_LINK = _psplatform.AF_LINK
__author__ = "Giampaolo Rodola'"
__version__ = "6.0.0"
version_info = tuple([int(num) for num in __version__.split('.')])
_timer = getattr(time, 'monotonic', time.time)
_TOTAL_PHYMEM = None
_LOWEST_PID = None
_SENTINEL = object()
# Sanity check in case the user messed up with psutil installation
# or did something weird with sys.path. In this case we might end
# up importing a python module using a C extension module which
# was compiled for a different version of psutil.
# We want to prevent that by failing sooner rather than later.
# See: https://github.com/giampaolo/psutil/issues/564
if int(__version__.replace('.', '')) != getattr(
_psplatform.cext, 'version', None
):
msg = "version conflict: %r C extension " % _psplatform.cext.__file__
msg += "module was built for another version of psutil"
if hasattr(_psplatform.cext, 'version'):
msg += " (%s instead of %s)" % (
'.'.join([x for x in str(_psplatform.cext.version)]),
__version__,
)
else:
msg += " (different than %s)" % __version__
msg += "; you may try to 'pip uninstall psutil', manually remove %s" % (
getattr(
_psplatform.cext,
"__file__",
"the existing psutil install directory",
)
)
msg += " or clean the virtual env somehow, then reinstall"
raise ImportError(msg)
# =====================================================================
# --- Utils
# =====================================================================
if hasattr(_psplatform, 'ppid_map'):
# Faster version (Windows and Linux).
_ppid_map = _psplatform.ppid_map
else: # pragma: no cover
def _ppid_map():
"""Return a {pid: ppid, ...} dict for all running processes in
one shot. Used to speed up Process.children().
"""
ret = {}
for pid in pids():
try:
ret[pid] = _psplatform.Process(pid).ppid()
except (NoSuchProcess, ZombieProcess):
pass
return ret
def _pprint_secs(secs):
"""Format seconds in a human readable form."""
now = time.time()
secs_ago = int(now - secs)
fmt = "%H:%M:%S" if secs_ago < 60 * 60 * 24 else "%Y-%m-%d %H:%M:%S"
return datetime.datetime.fromtimestamp(secs).strftime(fmt)
# =====================================================================
# --- Process class
# =====================================================================
class Process(object): # noqa: UP004
"""Represents an OS process with the given PID.
If PID is omitted current process PID (os.getpid()) is used.
Raise NoSuchProcess if PID does not exist.
Note that most of the methods of this class do not make sure that
the PID of the process being queried has been reused. That means
that you may end up retrieving information for another process.
The only exceptions for which process identity is pre-emptively
checked and guaranteed are:
- parent()
- children()
- nice() (set)
- ionice() (set)
- rlimit() (set)
- cpu_affinity (set)
- suspend()
- resume()
- send_signal()
- terminate()
- kill()
To prevent this problem for all other methods you can use
is_running() before querying the process.
"""
def __init__(self, pid=None):
self._init(pid)
def _init(self, pid, _ignore_nsp=False):
if pid is None:
pid = os.getpid()
else:
if not _PY3 and not isinstance(pid, (int, long)):
msg = "pid must be an integer (got %r)" % pid
raise TypeError(msg)
if pid < 0:
msg = "pid must be a positive integer (got %s)" % pid
raise ValueError(msg)
try:
_psplatform.cext.check_pid_range(pid)
except OverflowError:
msg = "process PID out of range (got %s)" % pid
raise NoSuchProcess(pid, msg=msg)
self._pid = pid
self._name = None
self._exe = None
self._create_time = None
self._gone = False
self._pid_reused = False
self._hash = None
self._lock = threading.RLock()
# used for caching on Windows only (on POSIX ppid may change)
self._ppid = None
# platform-specific modules define an _psplatform.Process
# implementation class
self._proc = _psplatform.Process(pid)
self._last_sys_cpu_times = None
self._last_proc_cpu_times = None
self._exitcode = _SENTINEL
# cache creation time for later use in is_running() method
try:
self.create_time()
except AccessDenied:
# We should never get here as AFAIK we're able to get
# process creation time on all platforms even as a
# limited user.
pass
except ZombieProcess:
# Zombies can still be queried by this class (although
# not always) and pids() return them so just go on.
pass
except NoSuchProcess:
if not _ignore_nsp:
msg = "process PID not found"
raise NoSuchProcess(pid, msg=msg)
else:
self._gone = True
# This pair is supposed to identify a Process instance
# univocally over time (the PID alone is not enough as
# it might refer to a process whose PID has been reused).
# This will be used later in __eq__() and is_running().
self._ident = (self.pid, self._create_time)
def __str__(self):
info = collections.OrderedDict()
info["pid"] = self.pid
if self._name:
info['name'] = self._name
with self.oneshot():
if self._pid_reused:
info["status"] = "terminated + PID reused"
else:
try:
info["name"] = self.name()
info["status"] = self.status()
except ZombieProcess:
info["status"] = "zombie"
except NoSuchProcess:
info["status"] = "terminated"
except AccessDenied:
pass
if self._exitcode not in (_SENTINEL, None):
info["exitcode"] = self._exitcode
if self._create_time is not None:
info['started'] = _pprint_secs(self._create_time)
return "%s.%s(%s)" % (
self.__class__.__module__,
self.__class__.__name__,
", ".join(["%s=%r" % (k, v) for k, v in info.items()]),
)
__repr__ = __str__
def __eq__(self, other):
# Test for equality with another Process object based
# on PID and creation time.
if not isinstance(other, Process):
return NotImplemented
if OPENBSD or NETBSD: # pragma: no cover
# Zombie processes on Open/NetBSD have a creation time of
# 0.0. This covers the case when a process started normally
# (so it has a ctime), then it turned into a zombie. It's
# important to do this because is_running() depends on
# __eq__.
pid1, ctime1 = self._ident
pid2, ctime2 = other._ident
if pid1 == pid2:
if ctime1 and not ctime2:
try:
return self.status() == STATUS_ZOMBIE
except Error:
pass
return self._ident == other._ident
def __ne__(self, other):
return not self == other
def __hash__(self):
if self._hash is None:
self._hash = hash(self._ident)
return self._hash
def _raise_if_pid_reused(self):
"""Raises NoSuchProcess in case process PID has been reused."""
if self._pid_reused or (not self.is_running() and self._pid_reused):
# We may directly raise NSP in here already if PID is just
# not running, but I prefer NSP to be raised naturally by
# the actual Process API call. This way unit tests will tell
# us if the API is broken (aka don't raise NSP when it
# should). We also remain consistent with all other "get"
# APIs which don't use _raise_if_pid_reused().
msg = "process no longer exists and its PID has been reused"
raise NoSuchProcess(self.pid, self._name, msg=msg)
@property
def pid(self):
"""The process PID."""
return self._pid
# --- utility methods
@contextlib.contextmanager
def oneshot(self):
"""Utility context manager which considerably speeds up the
retrieval of multiple process information at the same time.
Internally different process info (e.g. name, ppid, uids,
gids, ...) may be fetched by using the same routine, but
only one information is returned and the others are discarded.
When using this context manager the internal routine is
executed once (in the example below on name()) and the
other info are cached.
The cache is cleared when exiting the context manager block.
The advice is to use this every time you retrieve more than
one information about the process. If you're lucky, you'll
get a hell of a speedup.
>>> import psutil
>>> p = psutil.Process()
>>> with p.oneshot():
... p.name() # collect multiple info
... p.cpu_times() # return cached value
... p.cpu_percent() # return cached value
... p.create_time() # return cached value
...
>>>
"""
with self._lock:
if hasattr(self, "_cache"):
# NOOP: this covers the use case where the user enters the
# context twice:
#
# >>> with p.oneshot():
# ... with p.oneshot():
# ...
#
# Also, since as_dict() internally uses oneshot()
# I expect that the code below will be a pretty common
# "mistake" that the user will make, so let's guard
# against that:
#
# >>> with p.oneshot():
# ... p.as_dict()
# ...
yield
else:
try:
# cached in case cpu_percent() is used
self.cpu_times.cache_activate(self)
# cached in case memory_percent() is used
self.memory_info.cache_activate(self)
# cached in case parent() is used
self.ppid.cache_activate(self)
# cached in case username() is used
if POSIX:
self.uids.cache_activate(self)
# specific implementation cache
self._proc.oneshot_enter()
yield
finally:
self.cpu_times.cache_deactivate(self)
self.memory_info.cache_deactivate(self)
self.ppid.cache_deactivate(self)
if POSIX:
self.uids.cache_deactivate(self)
self._proc.oneshot_exit()
def as_dict(self, attrs=None, ad_value=None):
"""Utility method returning process information as a
hashable dictionary.
If *attrs* is specified it must be a list of strings
reflecting available Process class' attribute names
(e.g. ['cpu_times', 'name']) else all public (read
only) attributes are assumed.
*ad_value* is the value which gets assigned in case
AccessDenied or ZombieProcess exception is raised when
retrieving that particular process information.
"""
valid_names = _as_dict_attrnames
if attrs is not None:
if not isinstance(attrs, (list, tuple, set, frozenset)):
msg = "invalid attrs type %s" % type(attrs)
raise TypeError(msg)
attrs = set(attrs)
invalid_names = attrs - valid_names
if invalid_names:
msg = "invalid attr name%s %s" % (
"s" if len(invalid_names) > 1 else "",
", ".join(map(repr, invalid_names)),
)
raise ValueError(msg)
retdict = {}
ls = attrs or valid_names
with self.oneshot():
for name in ls:
try:
if name == 'pid':
ret = self.pid
else:
meth = getattr(self, name)
ret = meth()
except (AccessDenied, ZombieProcess):
ret = ad_value
except NotImplementedError:
# in case of not implemented functionality (may happen
# on old or exotic systems) we want to crash only if
# the user explicitly asked for that particular attr
if attrs:
raise
continue
retdict[name] = ret
return retdict
def parent(self):
"""Return the parent process as a Process object pre-emptively
checking whether PID has been reused.
If no parent is known return None.
"""
lowest_pid = _LOWEST_PID if _LOWEST_PID is not None else pids()[0]
if self.pid == lowest_pid:
return None
ppid = self.ppid()
if ppid is not None:
ctime = self.create_time()
try:
parent = Process(ppid)
if parent.create_time() <= ctime:
return parent
# ...else ppid has been reused by another process
except NoSuchProcess:
pass
def parents(self):
"""Return the parents of this process as a list of Process
instances. If no parents are known return an empty list.
"""
parents = []
proc = self.parent()
while proc is not None:
parents.append(proc)
proc = proc.parent()
return parents
def is_running(self):
"""Return whether this process is running.
It also checks if PID has been reused by another process, in
which case it will remove the process from `process_iter()`
internal cache and return False.
"""
if self._gone or self._pid_reused:
return False
try:
# Checking if PID is alive is not enough as the PID might
# have been reused by another process. Process identity /
# uniqueness over time is guaranteed by (PID + creation
# time) and that is verified in __eq__.
self._pid_reused = self != Process(self.pid)
if self._pid_reused:
# remove this PID from `process_iter()` internal cache
_pmap.pop(self.pid, None)
raise NoSuchProcess(self.pid)
return True
except ZombieProcess:
# We should never get here as it's already handled in
# Process.__init__; here just for extra safety.
return True
except NoSuchProcess:
self._gone = True
return False
# --- actual API
@memoize_when_activated
def ppid(self):
"""The process parent PID.
On Windows the return value is cached after first call.
"""
# On POSIX we don't want to cache the ppid as it may unexpectedly
# change to 1 (init) in case this process turns into a zombie:
# https://github.com/giampaolo/psutil/issues/321
# http://stackoverflow.com/questions/356722/
# XXX should we check creation time here rather than in
# Process.parent()?
self._raise_if_pid_reused()
if POSIX:
return self._proc.ppid()
else: # pragma: no cover
self._ppid = self._ppid or self._proc.ppid()
return self._ppid
def name(self):
"""The process name. The return value is cached after first call."""
# Process name is only cached on Windows as on POSIX it may
# change, see:
# https://github.com/giampaolo/psutil/issues/692
if WINDOWS and self._name is not None:
return self._name
name = self._proc.name()
if POSIX and len(name) >= 15:
# On UNIX the name gets truncated to the first 15 characters.
# If it matches the first part of the cmdline we return that
# one instead because it's usually more explicative.
# Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
try:
cmdline = self.cmdline()
except (AccessDenied, ZombieProcess):
# Just pass and return the truncated name: it's better
# than nothing. Note: there are actual cases where a
# zombie process can return a name() but not a
# cmdline(), see:
# https://github.com/giampaolo/psutil/issues/2239
pass
else:
if cmdline:
extended_name = os.path.basename(cmdline[0])
if extended_name.startswith(name):
name = extended_name
self._name = name
self._proc._name = name
return name
def exe(self):
"""The process executable as an absolute path.
May also be an empty string.
The return value is cached after first call.
"""
def guess_it(fallback):
# try to guess exe from cmdline[0] in absence of a native
# exe representation
cmdline = self.cmdline()
if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
exe = cmdline[0] # the possible exe
# Attempt to guess only in case of an absolute path.
# It is not safe otherwise as the process might have
# changed cwd.
if (
os.path.isabs(exe)
and os.path.isfile(exe)
and os.access(exe, os.X_OK)
):
return exe
if isinstance(fallback, AccessDenied):
raise fallback
return fallback
if self._exe is None:
try:
exe = self._proc.exe()
except AccessDenied as err:
return guess_it(fallback=err)
else:
if not exe:
# underlying implementation can legitimately return an
# empty string; if that's the case we don't want to
# raise AD while guessing from the cmdline
try:
exe = guess_it(fallback=exe)
except AccessDenied:
pass
self._exe = exe
return self._exe
def cmdline(self):
"""The command line this process has been called with."""
return self._proc.cmdline()
def status(self):
"""The process current status as a STATUS_* constant."""
try:
return self._proc.status()
except ZombieProcess:
return STATUS_ZOMBIE
def username(self):
"""The name of the user that owns the process.
On UNIX this is calculated by using *real* process uid.
"""
if POSIX:
if pwd is None:
# might happen if python was installed from sources
msg = "requires pwd module shipped with standard python"
raise ImportError(msg)
real_uid = self.uids().real
try:
return pwd.getpwuid(real_uid).pw_name
except KeyError:
# the uid can't be resolved by the system
return str(real_uid)
else:
return self._proc.username()
def create_time(self):
"""The process creation time as a floating point number
expressed in seconds since the epoch.
The return value is cached after first call.
"""
if self._create_time is None:
self._create_time = self._proc.create_time()
return self._create_time
def cwd(self):
"""Process current working directory as an absolute path."""
return self._proc.cwd()
def nice(self, value=None):
"""Get or set process niceness (priority)."""
if value is None:
return self._proc.nice_get()
else:
self._raise_if_pid_reused()
self._proc.nice_set(value)
if POSIX:
@memoize_when_activated
def uids(self):
"""Return process UIDs as a (real, effective, saved)
namedtuple.
"""
return self._proc.uids()
def gids(self):
"""Return process GIDs as a (real, effective, saved)
namedtuple.
"""
return self._proc.gids()
def terminal(self):
"""The terminal associated with this process, if any,
else None.
"""
return self._proc.terminal()
def num_fds(self):
"""Return the number of file descriptors opened by this
process (POSIX only).
"""
return self._proc.num_fds()
# Linux, BSD, AIX and Windows only
if hasattr(_psplatform.Process, "io_counters"):
def io_counters(self):
"""Return process I/O statistics as a
(read_count, write_count, read_bytes, write_bytes)
namedtuple.
Those are the number of read/write calls performed and the
amount of bytes read and written by the process.
"""
return self._proc.io_counters()
# Linux and Windows
if hasattr(_psplatform.Process, "ionice_get"):
def ionice(self, ioclass=None, value=None):
"""Get or set process I/O niceness (priority).
On Linux *ioclass* is one of the IOPRIO_CLASS_* constants.
*value* is a number which goes from 0 to 7. The higher the
value, the lower the I/O priority of the process.
On Windows only *ioclass* is used and it can be set to 2
(normal), 1 (low) or 0 (very low).
Available on Linux and Windows > Vista only.
"""
if ioclass is None:
if value is not None:
msg = "'ioclass' argument must be specified"
raise ValueError(msg)
return self._proc.ionice_get()
else:
self._raise_if_pid_reused()
return self._proc.ionice_set(ioclass, value)
# Linux / FreeBSD only
if hasattr(_psplatform.Process, "rlimit"):
def rlimit(self, resource, limits=None):
"""Get or set process resource limits as a (soft, hard)
tuple.
*resource* is one of the RLIMIT_* constants.
*limits* is supposed to be a (soft, hard) tuple.
See "man prlimit" for further info.
Available on Linux and FreeBSD only.
"""
if limits is not None:
self._raise_if_pid_reused()
return self._proc.rlimit(resource, limits)
# Windows, Linux and FreeBSD only
if hasattr(_psplatform.Process, "cpu_affinity_get"):
def cpu_affinity(self, cpus=None):
"""Get or set process CPU affinity.
If specified, *cpus* must be a list of CPUs for which you
want to set the affinity (e.g. [0, 1]).
If an empty list is passed, all egible CPUs are assumed
(and set).
(Windows, Linux and BSD only).
"""
if cpus is None:
return sorted(set(self._proc.cpu_affinity_get()))
else:
self._raise_if_pid_reused()
if not cpus:
if hasattr(self._proc, "_get_eligible_cpus"):
cpus = self._proc._get_eligible_cpus()
else:
cpus = tuple(range(len(cpu_times(percpu=True))))
self._proc.cpu_affinity_set(list(set(cpus)))
# Linux, FreeBSD, SunOS
if hasattr(_psplatform.Process, "cpu_num"):
def cpu_num(self):
"""Return what CPU this process is currently running on.
The returned number should be <= psutil.cpu_count()
and <= len(psutil.cpu_percent(percpu=True)).
It may be used in conjunction with
psutil.cpu_percent(percpu=True) to observe the system
workload distributed across CPUs.
"""
return self._proc.cpu_num()
# All platforms has it, but maybe not in the future.
if hasattr(_psplatform.Process, "environ"):
def environ(self):
"""The environment variables of the process as a dict. Note: this
might not reflect changes made after the process started.
"""
return self._proc.environ()
if WINDOWS:
def num_handles(self):
"""Return the number of handles opened by this process
(Windows only).
"""
return self._proc.num_handles()
def num_ctx_switches(self):
"""Return the number of voluntary and involuntary context
switches performed by this process.
"""
return self._proc.num_ctx_switches()
def num_threads(self):
"""Return the number of threads used by this process."""
return self._proc.num_threads()
if hasattr(_psplatform.Process, "threads"):
def threads(self):
"""Return threads opened by process as a list of
(id, user_time, system_time) namedtuples representing
thread id and thread CPU times (user/system).
On OpenBSD this method requires root access.
"""
return self._proc.threads()
def children(self, recursive=False):
"""Return the children of this process as a list of Process
instances, pre-emptively checking whether PID has been reused.
If *recursive* is True return all the parent descendants.
Example (A == this process):
A ─┐
│
├─ B (child) ─┐
│ └─ X (grandchild) ─┐
│ └─ Y (great grandchild)
├─ C (child)
└─ D (child)
>>> import psutil
>>> p = psutil.Process()
>>> p.children()
B, C, D
>>> p.children(recursive=True)
B, X, Y, C, D
Note that in the example above if process X disappears
process Y won't be listed as the reference to process A
is lost.
"""
self._raise_if_pid_reused()
ppid_map = _ppid_map()
ret = []
if not recursive:
for pid, ppid in ppid_map.items():
if ppid == self.pid:
try:
child = Process(pid)
# if child happens to be older than its parent
# (self) it means child's PID has been reused
if self.create_time() <= child.create_time():
ret.append(child)
except (NoSuchProcess, ZombieProcess):
pass
else:
# Construct a {pid: [child pids]} dict
reverse_ppid_map = collections.defaultdict(list)
for pid, ppid in ppid_map.items():
reverse_ppid_map[ppid].append(pid)
# Recursively traverse that dict, starting from self.pid,
# such that we only call Process() on actual children
seen = set()
stack = [self.pid]
while stack:
pid = stack.pop()
if pid in seen:
# Since pids can be reused while the ppid_map is
# constructed, there may be rare instances where
# there's a cycle in the recorded process "tree".
continue
seen.add(pid)
for child_pid in reverse_ppid_map[pid]:
try:
child = Process(child_pid)
# if child happens to be older than its parent
# (self) it means child's PID has been reused
intime = self.create_time() <= child.create_time()
if intime:
ret.append(child)
stack.append(child_pid)
except (NoSuchProcess, ZombieProcess):
pass
return ret
def cpu_percent(self, interval=None):
"""Return a float representing the current process CPU
utilization as a percentage.
When *interval* is 0.0 or None (default) compares process times
to system CPU times elapsed since last call, returning
immediately (non-blocking). That means that the first time