applied-ai-018 commited on
Commit
dcaaac4
·
verified ·
1 Parent(s): afd9ed8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/INSTALLER +1 -0
  2. llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/LICENSE +19 -0
  3. llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/METADATA +259 -0
  4. llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/RECORD +15 -0
  5. llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/WHEEL +4 -0
  6. llmeval-env/lib/python3.10/site-packages/numpy/__config__.py +162 -0
  7. llmeval-env/lib/python3.10/site-packages/numpy/__init__.cython-30.pxd +1050 -0
  8. llmeval-env/lib/python3.10/site-packages/numpy/__init__.pxd +1015 -0
  9. llmeval-env/lib/python3.10/site-packages/numpy/__init__.py +461 -0
  10. llmeval-env/lib/python3.10/site-packages/numpy/__init__.pyi +0 -0
  11. llmeval-env/lib/python3.10/site-packages/numpy/_globals.py +95 -0
  12. llmeval-env/lib/python3.10/site-packages/numpy/_pytesttester.pyi +18 -0
  13. llmeval-env/lib/python3.10/site-packages/numpy/ctypeslib.py +545 -0
  14. llmeval-env/lib/python3.10/site-packages/numpy/ctypeslib.pyi +251 -0
  15. llmeval-env/lib/python3.10/site-packages/numpy/matlib.py +378 -0
  16. llmeval-env/lib/python3.10/site-packages/numpy/py.typed +0 -0
  17. llmeval-env/lib/python3.10/site-packages/psutil/__init__.py +2492 -0
  18. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/__init__.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_common.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_compat.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_psaix.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_psbsd.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_pslinux.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_psosx.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_psposix.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_pssunos.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_pswindows.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/psutil/_common.py +983 -0
  29. llmeval-env/lib/python3.10/site-packages/psutil/_compat.py +483 -0
  30. llmeval-env/lib/python3.10/site-packages/psutil/_psaix.py +582 -0
  31. llmeval-env/lib/python3.10/site-packages/psutil/_pslinux.py +2366 -0
  32. llmeval-env/lib/python3.10/site-packages/psutil/_psosx.py +555 -0
  33. llmeval-env/lib/python3.10/site-packages/psutil/_psposix.py +243 -0
  34. llmeval-env/lib/python3.10/site-packages/psutil/_pssunos.py +756 -0
  35. llmeval-env/lib/python3.10/site-packages/psutil/_psutil_linux.abi3.so +0 -0
  36. llmeval-env/lib/python3.10/site-packages/psutil/_psutil_posix.abi3.so +0 -0
  37. llmeval-env/lib/python3.10/site-packages/psutil/_pswindows.py +1170 -0
  38. llmeval-env/lib/python3.10/site-packages/psutil/tests/__init__.py +2043 -0
  39. llmeval-env/lib/python3.10/site-packages/psutil/tests/__main__.py +12 -0
  40. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  41. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/__main__.cpython-310.pyc +0 -0
  42. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/runner.cpython-310.pyc +0 -0
  43. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_aix.cpython-310.pyc +0 -0
  44. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_bsd.cpython-310.pyc +0 -0
  45. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_connections.cpython-310.pyc +0 -0
  46. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_contracts.cpython-310.pyc +0 -0
  47. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_linux.cpython-310.pyc +0 -0
  48. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_memleaks.cpython-310.pyc +0 -0
  49. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_misc.cpython-310.pyc +0 -0
  50. llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_osx.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2012 Erik Rose
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7
+ of the Software, and to permit persons to whom the Software is furnished to do
8
+ so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/METADATA ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: more-itertools
3
+ Version: 10.2.0
4
+ Summary: More routines for operating on iterables, beyond itertools
5
+ Keywords: itertools,iterator,iteration,filter,peek,peekable,chunk,chunked
6
+ Author-email: Erik Rose <[email protected]>
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/x-rst
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Natural Language :: English
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Project-URL: Homepage, https://github.com/more-itertools/more-itertools
24
+
25
+ ==============
26
+ More Itertools
27
+ ==============
28
+
29
+ .. image:: https://readthedocs.org/projects/more-itertools/badge/?version=latest
30
+ :target: https://more-itertools.readthedocs.io/en/stable/
31
+
32
+ Python's ``itertools`` library is a gem - you can compose elegant solutions
33
+ for a variety of problems with the functions it provides. In ``more-itertools``
34
+ we collect additional building blocks, recipes, and routines for working with
35
+ Python iterables.
36
+
37
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
38
+ | Grouping | `chunked <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.chunked>`_, |
39
+ | | `ichunked <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.ichunked>`_, |
40
+ | | `chunked_even <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.chunked_even>`_, |
41
+ | | `sliced <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sliced>`_, |
42
+ | | `constrained_batches <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.constrained_batches>`_, |
43
+ | | `distribute <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distribute>`_, |
44
+ | | `divide <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.divide>`_, |
45
+ | | `split_at <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_at>`_, |
46
+ | | `split_before <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_before>`_, |
47
+ | | `split_after <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_after>`_, |
48
+ | | `split_into <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_into>`_, |
49
+ | | `split_when <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_when>`_, |
50
+ | | `bucket <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.bucket>`_, |
51
+ | | `unzip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unzip>`_, |
52
+ | | `batched <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.batched>`_, |
53
+ | | `grouper <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.grouper>`_, |
54
+ | | `partition <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.partition>`_, |
55
+ | | `transpose <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.transpose>`_ |
56
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
57
+ | Lookahead and lookback | `spy <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.spy>`_, |
58
+ | | `peekable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.peekable>`_, |
59
+ | | `seekable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.seekable>`_ |
60
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
61
+ | Windowing | `windowed <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.windowed>`_, |
62
+ | | `substrings <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.substrings>`_, |
63
+ | | `substrings_indexes <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.substrings_indexes>`_, |
64
+ | | `stagger <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.stagger>`_, |
65
+ | | `windowed_complete <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.windowed_complete>`_, |
66
+ | | `pairwise <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.pairwise>`_, |
67
+ | | `triplewise <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.triplewise>`_, |
68
+ | | `sliding_window <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sliding_window>`_, |
69
+ | | `subslices <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.subslices>`_ |
70
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
71
+ | Augmenting | `count_cycle <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.count_cycle>`_, |
72
+ | | `intersperse <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.intersperse>`_, |
73
+ | | `padded <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.padded>`_, |
74
+ | | `repeat_each <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.repeat_each>`_, |
75
+ | | `mark_ends <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.mark_ends>`_, |
76
+ | | `repeat_last <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.repeat_last>`_, |
77
+ | | `adjacent <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.adjacent>`_, |
78
+ | | `groupby_transform <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.groupby_transform>`_, |
79
+ | | `pad_none <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.pad_none>`_, |
80
+ | | `ncycles <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.ncycles>`_ |
81
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
82
+ | Combining | `collapse <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.collapse>`_, |
83
+ | | `sort_together <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sort_together>`_, |
84
+ | | `interleave <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave>`_, |
85
+ | | `interleave_longest <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave_longest>`_, |
86
+ | | `interleave_evenly <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave_evenly>`_, |
87
+ | | `zip_offset <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.zip_offset>`_, |
88
+ | | `zip_equal <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.zip_equal>`_, |
89
+ | | `zip_broadcast <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.zip_broadcast>`_, |
90
+ | | `dotproduct <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.dotproduct>`_, |
91
+ | | `convolve <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.convolve>`_, |
92
+ | | `flatten <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.flatten>`_, |
93
+ | | `roundrobin <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.roundrobin>`_, |
94
+ | | `prepend <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.prepend>`_, |
95
+ | | `value_chain <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.value_chain>`_, |
96
+ | | `partial_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.partial_product>`_ |
97
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
98
+ | Summarizing | `ilen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.ilen>`_, |
99
+ | | `unique_to_each <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_to_each>`_, |
100
+ | | `sample <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sample>`_, |
101
+ | | `consecutive_groups <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consecutive_groups>`_, |
102
+ | | `run_length <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.run_length>`_, |
103
+ | | `map_reduce <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.map_reduce>`_, |
104
+ | | `exactly_n <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.exactly_n>`_, |
105
+ | | `is_sorted <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.is_sorted>`_, |
106
+ | | `all_equal <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.all_equal>`_, |
107
+ | | `all_unique <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.all_unique>`_, |
108
+ | | `minmax <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.minmax>`_, |
109
+ | | `first_true <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.first_true>`_, |
110
+ | | `quantify <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.quantify>`_, |
111
+ | | `iequals <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iequals>`_ |
112
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
113
+ | Selecting | `islice_extended <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.islice_extended>`_, |
114
+ | | `first <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.first>`_, |
115
+ | | `last <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.last>`_, |
116
+ | | `one <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.one>`_, |
117
+ | | `only <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.only>`_, |
118
+ | | `strictly_n <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.strictly_n>`_, |
119
+ | | `strip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.strip>`_, |
120
+ | | `lstrip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.lstrip>`_, |
121
+ | | `rstrip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.rstrip>`_, |
122
+ | | `filter_except <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.filter_except>`_, |
123
+ | | `map_except <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.map_except>`_, |
124
+ | | `filter_map <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.filter_map>`_, |
125
+ | | `iter_suppress <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iter_suppress>`_, |
126
+ | | `nth_or_last <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_or_last>`_, |
127
+ | | `unique_in_window <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_in_window>`_, |
128
+ | | `before_and_after <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.before_and_after>`_, |
129
+ | | `nth <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth>`_, |
130
+ | | `take <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.take>`_, |
131
+ | | `tail <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.tail>`_, |
132
+ | | `unique_everseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_everseen>`_, |
133
+ | | `unique_justseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_justseen>`_, |
134
+ | | `duplicates_everseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.duplicates_everseen>`_, |
135
+ | | `duplicates_justseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.duplicates_justseen>`_, |
136
+ | | `classify_unique <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.classify_unique>`_, |
137
+ | | `longest_common_prefix <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.longest_common_prefix>`_, |
138
+ | | `takewhile_inclusive <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.takewhile_inclusive>`_ |
139
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
140
+ | Combinatorics | `distinct_permutations <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distinct_permutations>`_, |
141
+ | | `distinct_combinations <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distinct_combinations>`_, |
142
+ | | `circular_shifts <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.circular_shifts>`_, |
143
+ | | `partitions <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.partitions>`_, |
144
+ | | `set_partitions <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.set_partitions>`_, |
145
+ | | `product_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.product_index>`_, |
146
+ | | `combination_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.combination_index>`_, |
147
+ | | `permutation_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.permutation_index>`_, |
148
+ | | `combination_with_replacement_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.combination_with_replacement_index>`_, |
149
+ | | `gray_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.gray_product>`_, |
150
+ | | `outer_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.outer_product>`_, |
151
+ | | `powerset <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.powerset>`_, |
152
+ | | `random_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_product>`_, |
153
+ | | `random_permutation <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_permutation>`_, |
154
+ | | `random_combination <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_combination>`_, |
155
+ | | `random_combination_with_replacement <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_combination_with_replacement>`_, |
156
+ | | `nth_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_product>`_, |
157
+ | | `nth_permutation <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_permutation>`_, |
158
+ | | `nth_combination <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_combination>`_, |
159
+ | | `nth_combination_with_replacement <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_combination_with_replacement>`_ |
160
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
161
+ | Wrapping | `always_iterable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable>`_, |
162
+ | | `always_reversible <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_reversible>`_, |
163
+ | | `countable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.countable>`_, |
164
+ | | `consumer <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consumer>`_, |
165
+ | | `with_iter <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.with_iter>`_, |
166
+ | | `iter_except <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iter_except>`_ |
167
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
168
+ | Others | `locate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.locate>`_, |
169
+ | | `rlocate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.rlocate>`_, |
170
+ | | `replace <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.replace>`_, |
171
+ | | `numeric_range <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.numeric_range>`_, |
172
+ | | `side_effect <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.side_effect>`_, |
173
+ | | `iterate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iterate>`_, |
174
+ | | `difference <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.difference>`_, |
175
+ | | `make_decorator <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.make_decorator>`_, |
176
+ | | `SequenceView <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.SequenceView>`_, |
177
+ | | `time_limited <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.time_limited>`_, |
178
+ | | `map_if <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.map_if>`_, |
179
+ | | `iter_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iter_index>`_, |
180
+ | | `consume <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consume>`_, |
181
+ | | `tabulate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.tabulate>`_, |
182
+ | | `repeatfunc <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.repeatfunc>`_, |
183
+ | | `polynomial_from_roots <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.polynomial_from_roots>`_, |
184
+ | | `polynomial_eval <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.polynomial_eval>`_, |
185
+ | | `polynomial_derivative <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.polynomial_derivative>`_, |
186
+ | | `sieve <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sieve>`_, |
187
+ | | `factor <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.factor>`_, |
188
+ | | `matmul <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.matmul>`_, |
189
+ | | `sum_of_squares <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sum_of_squares>`_, |
190
+ | | `totient <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.totient>`_, |
191
+ | | `reshape <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.reshape>`_ |
192
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
193
+
194
+
195
+ Getting started
196
+ ===============
197
+
198
+ To get started, install the library with `pip <https://pip.pypa.io/en/stable/>`_:
199
+
200
+ .. code-block:: shell
201
+
202
+ pip install more-itertools
203
+
204
+ The recipes from the `itertools docs <https://docs.python.org/3/library/itertools.html#itertools-recipes>`_
205
+ are included in the top-level package:
206
+
207
+ .. code-block:: python
208
+
209
+ >>> from more_itertools import flatten
210
+ >>> iterable = [(0, 1), (2, 3)]
211
+ >>> list(flatten(iterable))
212
+ [0, 1, 2, 3]
213
+
214
+ Several new recipes are available as well:
215
+
216
+ .. code-block:: python
217
+
218
+ >>> from more_itertools import chunked
219
+ >>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8]
220
+ >>> list(chunked(iterable, 3))
221
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
222
+
223
+ >>> from more_itertools import spy
224
+ >>> iterable = (x * x for x in range(1, 6))
225
+ >>> head, iterable = spy(iterable, n=3)
226
+ >>> list(head)
227
+ [1, 4, 9]
228
+ >>> list(iterable)
229
+ [1, 4, 9, 16, 25]
230
+
231
+
232
+
233
+ For the full listing of functions, see the `API documentation <https://more-itertools.readthedocs.io/en/stable/api.html>`_.
234
+
235
+
236
+ Links elsewhere
237
+ ===============
238
+
239
+ Blog posts about ``more-itertools``:
240
+
241
+ * `Yo, I heard you like decorators <https://www.bbayles.com/index/decorator_factory>`__
242
+ * `Tour of Python Itertools <https://martinheinz.dev/blog/16>`__ (`Alternate <https://dev.to/martinheinz/tour-of-python-itertools-4122>`__)
243
+ * `Real-World Python More Itertools <https://www.gidware.com/real-world-more-itertools/>`_
244
+
245
+
246
+ Development
247
+ ===========
248
+
249
+ ``more-itertools`` is maintained by `@erikrose <https://github.com/erikrose>`_
250
+ and `@bbayles <https://github.com/bbayles>`_, with help from `many others <https://github.com/more-itertools/more-itertools/graphs/contributors>`_.
251
+ If you have a problem or suggestion, please file a bug or pull request in this
252
+ repository. Thanks for contributing!
253
+
254
+
255
+ Version History
256
+ ===============
257
+
258
+ The version history can be found in `documentation <https://more-itertools.readthedocs.io/en/stable/versions.html>`_.
259
+
llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/RECORD ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ more_itertools-10.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ more_itertools-10.2.0.dist-info/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053
3
+ more_itertools-10.2.0.dist-info/METADATA,sha256=lTIPxfD4IiP6aHzPjP4dXmzRRUmiXicAB6qnY82T-Gs,34886
4
+ more_itertools-10.2.0.dist-info/RECORD,,
5
+ more_itertools-10.2.0.dist-info/WHEEL,sha256=rSgq_JpHF9fHR1lx53qwg_1-2LypZE_qmcuXbVUq948,81
6
+ more_itertools/__init__.py,sha256=VodgFyRJvpnHbAMgseYRiP7r928FFOAakmQrl6J88os,149
7
+ more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43
8
+ more_itertools/__pycache__/__init__.cpython-310.pyc,,
9
+ more_itertools/__pycache__/more.cpython-310.pyc,,
10
+ more_itertools/__pycache__/recipes.cpython-310.pyc,,
11
+ more_itertools/more.py,sha256=jYdpbgXHf8yZDByPrhluxpe0D_IXRk2tfQnyfOFMi74,143045
12
+ more_itertools/more.pyi,sha256=KTHYeqr0rFbn1GWRnv0jY64JRNnKKT0kA3kmsah8DYQ,21044
13
+ more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ more_itertools/recipes.py,sha256=Rb3OhzJTCn2biutDEUSImbuY-8NDS1lkHt0My-uCOf4,27548
15
+ more_itertools/recipes.pyi,sha256=T1IuEVXCqw2NeJJNW036MtWi8BVfR8Ilpf7cBmvhBaQ,4436
llmeval-env/lib/python3.10/site-packages/more_itertools-10.2.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.8.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
llmeval-env/lib/python3.10/site-packages/numpy/__config__.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is generated by numpy's build process
2
+ # It contains system_info results at the time of building this package.
3
+ from enum import Enum
4
+ from numpy.core._multiarray_umath import (
5
+ __cpu_features__,
6
+ __cpu_baseline__,
7
+ __cpu_dispatch__,
8
+ )
9
+
10
+ __all__ = ["show"]
11
+ _built_with_meson = True
12
+
13
+
14
+ class DisplayModes(Enum):
15
+ stdout = "stdout"
16
+ dicts = "dicts"
17
+
18
+
19
+ def _cleanup(d):
20
+ """
21
+ Removes empty values in a `dict` recursively
22
+ This ensures we remove values that Meson could not provide to CONFIG
23
+ """
24
+ if isinstance(d, dict):
25
+ return {k: _cleanup(v) for k, v in d.items() if v and _cleanup(v)}
26
+ else:
27
+ return d
28
+
29
+
30
+ CONFIG = _cleanup(
31
+ {
32
+ "Compilers": {
33
+ "c": {
34
+ "name": "gcc",
35
+ "linker": r"ld.bfd",
36
+ "version": "10.2.1",
37
+ "commands": r"cc",
38
+ "args": r"-fno-strict-aliasing",
39
+ "linker args": r"-Wl,--strip-debug, -fno-strict-aliasing",
40
+ },
41
+ "cython": {
42
+ "name": "cython",
43
+ "linker": r"cython",
44
+ "version": "3.0.8",
45
+ "commands": r"cython",
46
+ "args": r"",
47
+ "linker args": r"",
48
+ },
49
+ "c++": {
50
+ "name": "gcc",
51
+ "linker": r"ld.bfd",
52
+ "version": "10.2.1",
53
+ "commands": r"c++",
54
+ "args": r"",
55
+ "linker args": r"-Wl,--strip-debug",
56
+ },
57
+ },
58
+ "Machine Information": {
59
+ "host": {
60
+ "cpu": "x86_64",
61
+ "family": "x86_64",
62
+ "endian": "little",
63
+ "system": "linux",
64
+ },
65
+ "build": {
66
+ "cpu": "x86_64",
67
+ "family": "x86_64",
68
+ "endian": "little",
69
+ "system": "linux",
70
+ },
71
+ "cross-compiled": bool("False".lower().replace("false", "")),
72
+ },
73
+ "Build Dependencies": {
74
+ "blas": {
75
+ "name": "openblas64",
76
+ "found": bool("True".lower().replace("false", "")),
77
+ "version": "0.3.23.dev",
78
+ "detection method": "pkgconfig",
79
+ "include directory": r"/usr/local/include",
80
+ "lib directory": r"/usr/local/lib",
81
+ "openblas configuration": r"USE_64BITINT=1 DYNAMIC_ARCH=1 DYNAMIC_OLDER= NO_CBLAS= NO_LAPACK= NO_LAPACKE= NO_AFFINITY=1 USE_OPENMP= HASWELL MAX_THREADS=2",
82
+ "pc file directory": r"/usr/local/lib/pkgconfig",
83
+ },
84
+ "lapack": {
85
+ "name": "dep139863411681952",
86
+ "found": bool("True".lower().replace("false", "")),
87
+ "version": "1.26.4",
88
+ "detection method": "internal",
89
+ "include directory": r"unknown",
90
+ "lib directory": r"unknown",
91
+ "openblas configuration": r"unknown",
92
+ "pc file directory": r"unknown",
93
+ },
94
+ },
95
+ "Python Information": {
96
+ "path": r"/opt/python/cp310-cp310/bin/python",
97
+ "version": "3.10",
98
+ },
99
+ "SIMD Extensions": {
100
+ "baseline": __cpu_baseline__,
101
+ "found": [
102
+ feature for feature in __cpu_dispatch__ if __cpu_features__[feature]
103
+ ],
104
+ "not found": [
105
+ feature for feature in __cpu_dispatch__ if not __cpu_features__[feature]
106
+ ],
107
+ },
108
+ }
109
+ )
110
+
111
+
112
+ def _check_pyyaml():
113
+ import yaml
114
+
115
+ return yaml
116
+
117
+
118
+ def show(mode=DisplayModes.stdout.value):
119
+ """
120
+ Show libraries and system information on which NumPy was built
121
+ and is being used
122
+
123
+ Parameters
124
+ ----------
125
+ mode : {`'stdout'`, `'dicts'`}, optional.
126
+ Indicates how to display the config information.
127
+ `'stdout'` prints to console, `'dicts'` returns a dictionary
128
+ of the configuration.
129
+
130
+ Returns
131
+ -------
132
+ out : {`dict`, `None`}
133
+ If mode is `'dicts'`, a dict is returned, else None
134
+
135
+ See Also
136
+ --------
137
+ get_include : Returns the directory containing NumPy C
138
+ header files.
139
+
140
+ Notes
141
+ -----
142
+ 1. The `'stdout'` mode will give more readable
143
+ output if ``pyyaml`` is installed
144
+
145
+ """
146
+ if mode == DisplayModes.stdout.value:
147
+ try: # Non-standard library, check import
148
+ yaml = _check_pyyaml()
149
+
150
+ print(yaml.dump(CONFIG))
151
+ except ModuleNotFoundError:
152
+ import warnings
153
+ import json
154
+
155
+ warnings.warn("Install `pyyaml` for better output", stacklevel=1)
156
+ print(json.dumps(CONFIG, indent=2))
157
+ elif mode == DisplayModes.dicts.value:
158
+ return CONFIG
159
+ else:
160
+ raise AttributeError(
161
+ f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}"
162
+ )
llmeval-env/lib/python3.10/site-packages/numpy/__init__.cython-30.pxd ADDED
@@ -0,0 +1,1050 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NumPy static imports for Cython >= 3.0
2
+ #
3
+ # If any of the PyArray_* functions are called, import_array must be
4
+ # called first. This is done automatically by Cython 3.0+ if a call
5
+ # is not detected inside of the module.
6
+ #
7
+ # Author: Dag Sverre Seljebotn
8
+ #
9
+
10
+ from cpython.ref cimport Py_INCREF
11
+ from cpython.object cimport PyObject, PyTypeObject, PyObject_TypeCheck
12
+ cimport libc.stdio as stdio
13
+
14
+
15
+ cdef extern from *:
16
+ # Leave a marker that the NumPy declarations came from NumPy itself and not from Cython.
17
+ # See https://github.com/cython/cython/issues/3573
18
+ """
19
+ /* Using NumPy API declarations from "numpy/__init__.cython-30.pxd" */
20
+ """
21
+
22
+
23
+ cdef extern from "Python.h":
24
+ ctypedef int Py_intptr_t
25
+
26
+ cdef extern from "numpy/arrayobject.h":
27
+ ctypedef Py_intptr_t npy_intp
28
+ ctypedef size_t npy_uintp
29
+
30
+ cdef enum NPY_TYPES:
31
+ NPY_BOOL
32
+ NPY_BYTE
33
+ NPY_UBYTE
34
+ NPY_SHORT
35
+ NPY_USHORT
36
+ NPY_INT
37
+ NPY_UINT
38
+ NPY_LONG
39
+ NPY_ULONG
40
+ NPY_LONGLONG
41
+ NPY_ULONGLONG
42
+ NPY_FLOAT
43
+ NPY_DOUBLE
44
+ NPY_LONGDOUBLE
45
+ NPY_CFLOAT
46
+ NPY_CDOUBLE
47
+ NPY_CLONGDOUBLE
48
+ NPY_OBJECT
49
+ NPY_STRING
50
+ NPY_UNICODE
51
+ NPY_VOID
52
+ NPY_DATETIME
53
+ NPY_TIMEDELTA
54
+ NPY_NTYPES
55
+ NPY_NOTYPE
56
+
57
+ NPY_INT8
58
+ NPY_INT16
59
+ NPY_INT32
60
+ NPY_INT64
61
+ NPY_INT128
62
+ NPY_INT256
63
+ NPY_UINT8
64
+ NPY_UINT16
65
+ NPY_UINT32
66
+ NPY_UINT64
67
+ NPY_UINT128
68
+ NPY_UINT256
69
+ NPY_FLOAT16
70
+ NPY_FLOAT32
71
+ NPY_FLOAT64
72
+ NPY_FLOAT80
73
+ NPY_FLOAT96
74
+ NPY_FLOAT128
75
+ NPY_FLOAT256
76
+ NPY_COMPLEX32
77
+ NPY_COMPLEX64
78
+ NPY_COMPLEX128
79
+ NPY_COMPLEX160
80
+ NPY_COMPLEX192
81
+ NPY_COMPLEX256
82
+ NPY_COMPLEX512
83
+
84
+ NPY_INTP
85
+
86
+ ctypedef enum NPY_ORDER:
87
+ NPY_ANYORDER
88
+ NPY_CORDER
89
+ NPY_FORTRANORDER
90
+ NPY_KEEPORDER
91
+
92
+ ctypedef enum NPY_CASTING:
93
+ NPY_NO_CASTING
94
+ NPY_EQUIV_CASTING
95
+ NPY_SAFE_CASTING
96
+ NPY_SAME_KIND_CASTING
97
+ NPY_UNSAFE_CASTING
98
+
99
+ ctypedef enum NPY_CLIPMODE:
100
+ NPY_CLIP
101
+ NPY_WRAP
102
+ NPY_RAISE
103
+
104
+ ctypedef enum NPY_SCALARKIND:
105
+ NPY_NOSCALAR,
106
+ NPY_BOOL_SCALAR,
107
+ NPY_INTPOS_SCALAR,
108
+ NPY_INTNEG_SCALAR,
109
+ NPY_FLOAT_SCALAR,
110
+ NPY_COMPLEX_SCALAR,
111
+ NPY_OBJECT_SCALAR
112
+
113
+ ctypedef enum NPY_SORTKIND:
114
+ NPY_QUICKSORT
115
+ NPY_HEAPSORT
116
+ NPY_MERGESORT
117
+
118
+ ctypedef enum NPY_SEARCHSIDE:
119
+ NPY_SEARCHLEFT
120
+ NPY_SEARCHRIGHT
121
+
122
+ enum:
123
+ # DEPRECATED since NumPy 1.7 ! Do not use in new code!
124
+ NPY_C_CONTIGUOUS
125
+ NPY_F_CONTIGUOUS
126
+ NPY_CONTIGUOUS
127
+ NPY_FORTRAN
128
+ NPY_OWNDATA
129
+ NPY_FORCECAST
130
+ NPY_ENSURECOPY
131
+ NPY_ENSUREARRAY
132
+ NPY_ELEMENTSTRIDES
133
+ NPY_ALIGNED
134
+ NPY_NOTSWAPPED
135
+ NPY_WRITEABLE
136
+ NPY_ARR_HAS_DESCR
137
+
138
+ NPY_BEHAVED
139
+ NPY_BEHAVED_NS
140
+ NPY_CARRAY
141
+ NPY_CARRAY_RO
142
+ NPY_FARRAY
143
+ NPY_FARRAY_RO
144
+ NPY_DEFAULT
145
+
146
+ NPY_IN_ARRAY
147
+ NPY_OUT_ARRAY
148
+ NPY_INOUT_ARRAY
149
+ NPY_IN_FARRAY
150
+ NPY_OUT_FARRAY
151
+ NPY_INOUT_FARRAY
152
+
153
+ NPY_UPDATE_ALL
154
+
155
+ enum:
156
+ # Added in NumPy 1.7 to replace the deprecated enums above.
157
+ NPY_ARRAY_C_CONTIGUOUS
158
+ NPY_ARRAY_F_CONTIGUOUS
159
+ NPY_ARRAY_OWNDATA
160
+ NPY_ARRAY_FORCECAST
161
+ NPY_ARRAY_ENSURECOPY
162
+ NPY_ARRAY_ENSUREARRAY
163
+ NPY_ARRAY_ELEMENTSTRIDES
164
+ NPY_ARRAY_ALIGNED
165
+ NPY_ARRAY_NOTSWAPPED
166
+ NPY_ARRAY_WRITEABLE
167
+ NPY_ARRAY_WRITEBACKIFCOPY
168
+
169
+ NPY_ARRAY_BEHAVED
170
+ NPY_ARRAY_BEHAVED_NS
171
+ NPY_ARRAY_CARRAY
172
+ NPY_ARRAY_CARRAY_RO
173
+ NPY_ARRAY_FARRAY
174
+ NPY_ARRAY_FARRAY_RO
175
+ NPY_ARRAY_DEFAULT
176
+
177
+ NPY_ARRAY_IN_ARRAY
178
+ NPY_ARRAY_OUT_ARRAY
179
+ NPY_ARRAY_INOUT_ARRAY
180
+ NPY_ARRAY_IN_FARRAY
181
+ NPY_ARRAY_OUT_FARRAY
182
+ NPY_ARRAY_INOUT_FARRAY
183
+
184
+ NPY_ARRAY_UPDATE_ALL
185
+
186
+ cdef enum:
187
+ NPY_MAXDIMS
188
+
189
+ npy_intp NPY_MAX_ELSIZE
190
+
191
+ ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *)
192
+
193
+ ctypedef struct PyArray_ArrayDescr:
194
+ # shape is a tuple, but Cython doesn't support "tuple shape"
195
+ # inside a non-PyObject declaration, so we have to declare it
196
+ # as just a PyObject*.
197
+ PyObject* shape
198
+
199
+ ctypedef struct PyArray_Descr:
200
+ pass
201
+
202
+ ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]:
203
+ # Use PyDataType_* macros when possible, however there are no macros
204
+ # for accessing some of the fields, so some are defined.
205
+ cdef PyTypeObject* typeobj
206
+ cdef char kind
207
+ cdef char type
208
+ # Numpy sometimes mutates this without warning (e.g. it'll
209
+ # sometimes change "|" to "<" in shared dtype objects on
210
+ # little-endian machines). If this matters to you, use
211
+ # PyArray_IsNativeByteOrder(dtype.byteorder) instead of
212
+ # directly accessing this field.
213
+ cdef char byteorder
214
+ cdef char flags
215
+ cdef int type_num
216
+ cdef int itemsize "elsize"
217
+ cdef int alignment
218
+ cdef object fields
219
+ cdef tuple names
220
+ # Use PyDataType_HASSUBARRAY to test whether this field is
221
+ # valid (the pointer can be NULL). Most users should access
222
+ # this field via the inline helper method PyDataType_SHAPE.
223
+ cdef PyArray_ArrayDescr* subarray
224
+
225
+ ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]:
226
+ # Use through macros
227
+ pass
228
+
229
+ ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]:
230
+ # Use through macros
231
+ pass
232
+
233
+ ctypedef struct PyArrayObject:
234
+ # For use in situations where ndarray can't replace PyArrayObject*,
235
+ # like PyArrayObject**.
236
+ pass
237
+
238
+ ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
239
+ cdef __cythonbufferdefaults__ = {"mode": "strided"}
240
+
241
+ # NOTE: no field declarations since direct access is deprecated since NumPy 1.7
242
+ # Instead, we use properties that map to the corresponding C-API functions.
243
+
244
+ @property
245
+ cdef inline PyObject* base(self) nogil:
246
+ """Returns a borrowed reference to the object owning the data/memory.
247
+ """
248
+ return PyArray_BASE(self)
249
+
250
+ @property
251
+ cdef inline dtype descr(self):
252
+ """Returns an owned reference to the dtype of the array.
253
+ """
254
+ return <dtype>PyArray_DESCR(self)
255
+
256
+ @property
257
+ cdef inline int ndim(self) nogil:
258
+ """Returns the number of dimensions in the array.
259
+ """
260
+ return PyArray_NDIM(self)
261
+
262
+ @property
263
+ cdef inline npy_intp *shape(self) nogil:
264
+ """Returns a pointer to the dimensions/shape of the array.
265
+ The number of elements matches the number of dimensions of the array (ndim).
266
+ Can return NULL for 0-dimensional arrays.
267
+ """
268
+ return PyArray_DIMS(self)
269
+
270
+ @property
271
+ cdef inline npy_intp *strides(self) nogil:
272
+ """Returns a pointer to the strides of the array.
273
+ The number of elements matches the number of dimensions of the array (ndim).
274
+ """
275
+ return PyArray_STRIDES(self)
276
+
277
+ @property
278
+ cdef inline npy_intp size(self) nogil:
279
+ """Returns the total size (in number of elements) of the array.
280
+ """
281
+ return PyArray_SIZE(self)
282
+
283
+ @property
284
+ cdef inline char* data(self) nogil:
285
+ """The pointer to the data buffer as a char*.
286
+ This is provided for legacy reasons to avoid direct struct field access.
287
+ For new code that needs this access, you probably want to cast the result
288
+ of `PyArray_DATA()` instead, which returns a 'void*'.
289
+ """
290
+ return PyArray_BYTES(self)
291
+
292
+ ctypedef unsigned char npy_bool
293
+
294
+ ctypedef signed char npy_byte
295
+ ctypedef signed short npy_short
296
+ ctypedef signed int npy_int
297
+ ctypedef signed long npy_long
298
+ ctypedef signed long long npy_longlong
299
+
300
+ ctypedef unsigned char npy_ubyte
301
+ ctypedef unsigned short npy_ushort
302
+ ctypedef unsigned int npy_uint
303
+ ctypedef unsigned long npy_ulong
304
+ ctypedef unsigned long long npy_ulonglong
305
+
306
+ ctypedef float npy_float
307
+ ctypedef double npy_double
308
+ ctypedef long double npy_longdouble
309
+
310
+ ctypedef signed char npy_int8
311
+ ctypedef signed short npy_int16
312
+ ctypedef signed int npy_int32
313
+ ctypedef signed long long npy_int64
314
+ ctypedef signed long long npy_int96
315
+ ctypedef signed long long npy_int128
316
+
317
+ ctypedef unsigned char npy_uint8
318
+ ctypedef unsigned short npy_uint16
319
+ ctypedef unsigned int npy_uint32
320
+ ctypedef unsigned long long npy_uint64
321
+ ctypedef unsigned long long npy_uint96
322
+ ctypedef unsigned long long npy_uint128
323
+
324
+ ctypedef float npy_float32
325
+ ctypedef double npy_float64
326
+ ctypedef long double npy_float80
327
+ ctypedef long double npy_float96
328
+ ctypedef long double npy_float128
329
+
330
+ ctypedef struct npy_cfloat:
331
+ float real
332
+ float imag
333
+
334
+ ctypedef struct npy_cdouble:
335
+ double real
336
+ double imag
337
+
338
+ ctypedef struct npy_clongdouble:
339
+ long double real
340
+ long double imag
341
+
342
+ ctypedef struct npy_complex64:
343
+ float real
344
+ float imag
345
+
346
+ ctypedef struct npy_complex128:
347
+ double real
348
+ double imag
349
+
350
+ ctypedef struct npy_complex160:
351
+ long double real
352
+ long double imag
353
+
354
+ ctypedef struct npy_complex192:
355
+ long double real
356
+ long double imag
357
+
358
+ ctypedef struct npy_complex256:
359
+ long double real
360
+ long double imag
361
+
362
+ ctypedef struct PyArray_Dims:
363
+ npy_intp *ptr
364
+ int len
365
+
366
+ int _import_array() except -1
367
+ # A second definition so _import_array isn't marked as used when we use it here.
368
+ # Do not use - subject to change any time.
369
+ int __pyx_import_array "_import_array"() except -1
370
+
371
+ #
372
+ # Macros from ndarrayobject.h
373
+ #
374
+ bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
375
+ bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
376
+ bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
377
+ bint PyArray_ISCONTIGUOUS(ndarray m) nogil
378
+ bint PyArray_ISWRITEABLE(ndarray m) nogil
379
+ bint PyArray_ISALIGNED(ndarray m) nogil
380
+
381
+ int PyArray_NDIM(ndarray) nogil
382
+ bint PyArray_ISONESEGMENT(ndarray) nogil
383
+ bint PyArray_ISFORTRAN(ndarray) nogil
384
+ int PyArray_FORTRANIF(ndarray) nogil
385
+
386
+ void* PyArray_DATA(ndarray) nogil
387
+ char* PyArray_BYTES(ndarray) nogil
388
+
389
+ npy_intp* PyArray_DIMS(ndarray) nogil
390
+ npy_intp* PyArray_STRIDES(ndarray) nogil
391
+ npy_intp PyArray_DIM(ndarray, size_t) nogil
392
+ npy_intp PyArray_STRIDE(ndarray, size_t) nogil
393
+
394
+ PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference!
395
+ PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype!
396
+ PyArray_Descr *PyArray_DTYPE(ndarray) nogil # returns borrowed reference to dtype! NP 1.7+ alias for descr.
397
+ int PyArray_FLAGS(ndarray) nogil
398
+ void PyArray_CLEARFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
399
+ void PyArray_ENABLEFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
400
+ npy_intp PyArray_ITEMSIZE(ndarray) nogil
401
+ int PyArray_TYPE(ndarray arr) nogil
402
+
403
+ object PyArray_GETITEM(ndarray arr, void *itemptr)
404
+ int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1
405
+
406
+ bint PyTypeNum_ISBOOL(int) nogil
407
+ bint PyTypeNum_ISUNSIGNED(int) nogil
408
+ bint PyTypeNum_ISSIGNED(int) nogil
409
+ bint PyTypeNum_ISINTEGER(int) nogil
410
+ bint PyTypeNum_ISFLOAT(int) nogil
411
+ bint PyTypeNum_ISNUMBER(int) nogil
412
+ bint PyTypeNum_ISSTRING(int) nogil
413
+ bint PyTypeNum_ISCOMPLEX(int) nogil
414
+ bint PyTypeNum_ISPYTHON(int) nogil
415
+ bint PyTypeNum_ISFLEXIBLE(int) nogil
416
+ bint PyTypeNum_ISUSERDEF(int) nogil
417
+ bint PyTypeNum_ISEXTENDED(int) nogil
418
+ bint PyTypeNum_ISOBJECT(int) nogil
419
+
420
+ bint PyDataType_ISBOOL(dtype) nogil
421
+ bint PyDataType_ISUNSIGNED(dtype) nogil
422
+ bint PyDataType_ISSIGNED(dtype) nogil
423
+ bint PyDataType_ISINTEGER(dtype) nogil
424
+ bint PyDataType_ISFLOAT(dtype) nogil
425
+ bint PyDataType_ISNUMBER(dtype) nogil
426
+ bint PyDataType_ISSTRING(dtype) nogil
427
+ bint PyDataType_ISCOMPLEX(dtype) nogil
428
+ bint PyDataType_ISPYTHON(dtype) nogil
429
+ bint PyDataType_ISFLEXIBLE(dtype) nogil
430
+ bint PyDataType_ISUSERDEF(dtype) nogil
431
+ bint PyDataType_ISEXTENDED(dtype) nogil
432
+ bint PyDataType_ISOBJECT(dtype) nogil
433
+ bint PyDataType_HASFIELDS(dtype) nogil
434
+ bint PyDataType_HASSUBARRAY(dtype) nogil
435
+
436
+ bint PyArray_ISBOOL(ndarray) nogil
437
+ bint PyArray_ISUNSIGNED(ndarray) nogil
438
+ bint PyArray_ISSIGNED(ndarray) nogil
439
+ bint PyArray_ISINTEGER(ndarray) nogil
440
+ bint PyArray_ISFLOAT(ndarray) nogil
441
+ bint PyArray_ISNUMBER(ndarray) nogil
442
+ bint PyArray_ISSTRING(ndarray) nogil
443
+ bint PyArray_ISCOMPLEX(ndarray) nogil
444
+ bint PyArray_ISPYTHON(ndarray) nogil
445
+ bint PyArray_ISFLEXIBLE(ndarray) nogil
446
+ bint PyArray_ISUSERDEF(ndarray) nogil
447
+ bint PyArray_ISEXTENDED(ndarray) nogil
448
+ bint PyArray_ISOBJECT(ndarray) nogil
449
+ bint PyArray_HASFIELDS(ndarray) nogil
450
+
451
+ bint PyArray_ISVARIABLE(ndarray) nogil
452
+
453
+ bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil
454
+ bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder
455
+ bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder
456
+ bint PyArray_ISNOTSWAPPED(ndarray) nogil
457
+ bint PyArray_ISBYTESWAPPED(ndarray) nogil
458
+
459
+ bint PyArray_FLAGSWAP(ndarray, int) nogil
460
+
461
+ bint PyArray_ISCARRAY(ndarray) nogil
462
+ bint PyArray_ISCARRAY_RO(ndarray) nogil
463
+ bint PyArray_ISFARRAY(ndarray) nogil
464
+ bint PyArray_ISFARRAY_RO(ndarray) nogil
465
+ bint PyArray_ISBEHAVED(ndarray) nogil
466
+ bint PyArray_ISBEHAVED_RO(ndarray) nogil
467
+
468
+
469
+ bint PyDataType_ISNOTSWAPPED(dtype) nogil
470
+ bint PyDataType_ISBYTESWAPPED(dtype) nogil
471
+
472
+ bint PyArray_DescrCheck(object)
473
+
474
+ bint PyArray_Check(object)
475
+ bint PyArray_CheckExact(object)
476
+
477
+ # Cannot be supported due to out arg:
478
+ # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&)
479
+ # bint PyArray_HasArrayInterface(op, out)
480
+
481
+
482
+ bint PyArray_IsZeroDim(object)
483
+ # Cannot be supported due to ## ## in macro:
484
+ # bint PyArray_IsScalar(object, verbatim work)
485
+ bint PyArray_CheckScalar(object)
486
+ bint PyArray_IsPythonNumber(object)
487
+ bint PyArray_IsPythonScalar(object)
488
+ bint PyArray_IsAnyScalar(object)
489
+ bint PyArray_CheckAnyScalar(object)
490
+
491
+ ndarray PyArray_GETCONTIGUOUS(ndarray)
492
+ bint PyArray_SAMESHAPE(ndarray, ndarray) nogil
493
+ npy_intp PyArray_SIZE(ndarray) nogil
494
+ npy_intp PyArray_NBYTES(ndarray) nogil
495
+
496
+ object PyArray_FROM_O(object)
497
+ object PyArray_FROM_OF(object m, int flags)
498
+ object PyArray_FROM_OT(object m, int type)
499
+ object PyArray_FROM_OTF(object m, int type, int flags)
500
+ object PyArray_FROMANY(object m, int type, int min, int max, int flags)
501
+ object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
502
+ object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
503
+ void PyArray_FILLWBYTE(object, int val)
504
+ npy_intp PyArray_REFCOUNT(object)
505
+ object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
506
+ unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
507
+ bint PyArray_EquivByteorders(int b1, int b2) nogil
508
+ object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
509
+ object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
510
+ #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr)
511
+ object PyArray_ToScalar(void* data, ndarray arr)
512
+
513
+ void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil
514
+ void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil
515
+ void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil
516
+ void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil
517
+
518
+ # Cannot be supported due to out arg
519
+ # void PyArray_DESCR_REPLACE(descr)
520
+
521
+
522
+ object PyArray_Copy(ndarray)
523
+ object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
524
+ object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
525
+ object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
526
+
527
+ object PyArray_Cast(ndarray mp, int type_num)
528
+ object PyArray_Take(ndarray ap, object items, int axis)
529
+ object PyArray_Put(ndarray ap, object items, object values)
530
+
531
+ void PyArray_ITER_RESET(flatiter it) nogil
532
+ void PyArray_ITER_NEXT(flatiter it) nogil
533
+ void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
534
+ void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
535
+ void* PyArray_ITER_DATA(flatiter it) nogil
536
+ bint PyArray_ITER_NOTDONE(flatiter it) nogil
537
+
538
+ void PyArray_MultiIter_RESET(broadcast multi) nogil
539
+ void PyArray_MultiIter_NEXT(broadcast multi) nogil
540
+ void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
541
+ void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
542
+ void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
543
+ void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
544
+ bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
545
+
546
+ # Functions from __multiarray_api.h
547
+
548
+ # Functions taking dtype and returning object/ndarray are disabled
549
+ # for now as they steal dtype references. I'm conservative and disable
550
+ # more than is probably needed until it can be checked further.
551
+ int PyArray_SetNumericOps (object) except -1
552
+ object PyArray_GetNumericOps ()
553
+ int PyArray_INCREF (ndarray) except * # uses PyArray_Item_INCREF...
554
+ int PyArray_XDECREF (ndarray) except * # uses PyArray_Item_DECREF...
555
+ void PyArray_SetStringFunction (object, int)
556
+ dtype PyArray_DescrFromType (int)
557
+ object PyArray_TypeObjectFromType (int)
558
+ char * PyArray_Zero (ndarray)
559
+ char * PyArray_One (ndarray)
560
+ #object PyArray_CastToType (ndarray, dtype, int)
561
+ int PyArray_CastTo (ndarray, ndarray) except -1
562
+ int PyArray_CastAnyTo (ndarray, ndarray) except -1
563
+ int PyArray_CanCastSafely (int, int) # writes errors
564
+ npy_bool PyArray_CanCastTo (dtype, dtype) # writes errors
565
+ int PyArray_ObjectType (object, int) except 0
566
+ dtype PyArray_DescrFromObject (object, dtype)
567
+ #ndarray* PyArray_ConvertToCommonType (object, int *)
568
+ dtype PyArray_DescrFromScalar (object)
569
+ dtype PyArray_DescrFromTypeObject (object)
570
+ npy_intp PyArray_Size (object)
571
+ #object PyArray_Scalar (void *, dtype, object)
572
+ #object PyArray_FromScalar (object, dtype)
573
+ void PyArray_ScalarAsCtype (object, void *)
574
+ #int PyArray_CastScalarToCtype (object, void *, dtype)
575
+ #int PyArray_CastScalarDirect (object, dtype, void *, int)
576
+ object PyArray_ScalarFromObject (object)
577
+ #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int)
578
+ object PyArray_FromDims (int, int *, int)
579
+ #object PyArray_FromDimsAndDataAndDescr (int, int *, dtype, char *)
580
+ #object PyArray_FromAny (object, dtype, int, int, int, object)
581
+ object PyArray_EnsureArray (object)
582
+ object PyArray_EnsureAnyArray (object)
583
+ #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *)
584
+ #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *)
585
+ #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp)
586
+ #object PyArray_FromIter (object, dtype, npy_intp)
587
+ object PyArray_Return (ndarray)
588
+ #object PyArray_GetField (ndarray, dtype, int)
589
+ #int PyArray_SetField (ndarray, dtype, int, object) except -1
590
+ object PyArray_Byteswap (ndarray, npy_bool)
591
+ object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER)
592
+ int PyArray_MoveInto (ndarray, ndarray) except -1
593
+ int PyArray_CopyInto (ndarray, ndarray) except -1
594
+ int PyArray_CopyAnyInto (ndarray, ndarray) except -1
595
+ int PyArray_CopyObject (ndarray, object) except -1
596
+ object PyArray_NewCopy (ndarray, NPY_ORDER)
597
+ object PyArray_ToList (ndarray)
598
+ object PyArray_ToString (ndarray, NPY_ORDER)
599
+ int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1
600
+ int PyArray_Dump (object, object, int) except -1
601
+ object PyArray_Dumps (object, int)
602
+ int PyArray_ValidType (int) # Cannot error
603
+ void PyArray_UpdateFlags (ndarray, int)
604
+ object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object)
605
+ #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object)
606
+ #dtype PyArray_DescrNew (dtype)
607
+ dtype PyArray_DescrNewFromType (int)
608
+ double PyArray_GetPriority (object, double) # clears errors as of 1.25
609
+ object PyArray_IterNew (object)
610
+ object PyArray_MultiIterNew (int, ...)
611
+
612
+ int PyArray_PyIntAsInt (object) except? -1
613
+ npy_intp PyArray_PyIntAsIntp (object)
614
+ int PyArray_Broadcast (broadcast) except -1
615
+ void PyArray_FillObjectArray (ndarray, object) except *
616
+ int PyArray_FillWithScalar (ndarray, object) except -1
617
+ npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
618
+ dtype PyArray_DescrNewByteorder (dtype, char)
619
+ object PyArray_IterAllButAxis (object, int *)
620
+ #object PyArray_CheckFromAny (object, dtype, int, int, int, object)
621
+ #object PyArray_FromArray (ndarray, dtype, int)
622
+ object PyArray_FromInterface (object)
623
+ object PyArray_FromStructInterface (object)
624
+ #object PyArray_FromArrayAttr (object, dtype, object)
625
+ #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*)
626
+ int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
627
+ object PyArray_NewFlagsObject (object)
628
+ npy_bool PyArray_CanCastScalar (type, type)
629
+ #int PyArray_CompareUCS4 (npy_ucs4 *, npy_ucs4 *, register size_t)
630
+ int PyArray_RemoveSmallest (broadcast) except -1
631
+ int PyArray_ElementStrides (object)
632
+ void PyArray_Item_INCREF (char *, dtype) except *
633
+ void PyArray_Item_XDECREF (char *, dtype) except *
634
+ object PyArray_FieldNames (object)
635
+ object PyArray_Transpose (ndarray, PyArray_Dims *)
636
+ object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
637
+ object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
638
+ object PyArray_PutMask (ndarray, object, object)
639
+ object PyArray_Repeat (ndarray, object, int)
640
+ object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
641
+ int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1
642
+ object PyArray_ArgSort (ndarray, int, NPY_SORTKIND)
643
+ object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *)
644
+ object PyArray_ArgMax (ndarray, int, ndarray)
645
+ object PyArray_ArgMin (ndarray, int, ndarray)
646
+ object PyArray_Reshape (ndarray, object)
647
+ object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
648
+ object PyArray_Squeeze (ndarray)
649
+ #object PyArray_View (ndarray, dtype, type)
650
+ object PyArray_SwapAxes (ndarray, int, int)
651
+ object PyArray_Max (ndarray, int, ndarray)
652
+ object PyArray_Min (ndarray, int, ndarray)
653
+ object PyArray_Ptp (ndarray, int, ndarray)
654
+ object PyArray_Mean (ndarray, int, int, ndarray)
655
+ object PyArray_Trace (ndarray, int, int, int, int, ndarray)
656
+ object PyArray_Diagonal (ndarray, int, int, int)
657
+ object PyArray_Clip (ndarray, object, object, ndarray)
658
+ object PyArray_Conjugate (ndarray, ndarray)
659
+ object PyArray_Nonzero (ndarray)
660
+ object PyArray_Std (ndarray, int, int, ndarray, int)
661
+ object PyArray_Sum (ndarray, int, int, ndarray)
662
+ object PyArray_CumSum (ndarray, int, int, ndarray)
663
+ object PyArray_Prod (ndarray, int, int, ndarray)
664
+ object PyArray_CumProd (ndarray, int, int, ndarray)
665
+ object PyArray_All (ndarray, int, ndarray)
666
+ object PyArray_Any (ndarray, int, ndarray)
667
+ object PyArray_Compress (ndarray, object, int, ndarray)
668
+ object PyArray_Flatten (ndarray, NPY_ORDER)
669
+ object PyArray_Ravel (ndarray, NPY_ORDER)
670
+ npy_intp PyArray_MultiplyList (npy_intp *, int)
671
+ int PyArray_MultiplyIntList (int *, int)
672
+ void * PyArray_GetPtr (ndarray, npy_intp*)
673
+ int PyArray_CompareLists (npy_intp *, npy_intp *, int)
674
+ #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype)
675
+ #int PyArray_As1D (object*, char **, int *, int)
676
+ #int PyArray_As2D (object*, char ***, int *, int *, int)
677
+ int PyArray_Free (object, void *)
678
+ #int PyArray_Converter (object, object*)
679
+ int PyArray_IntpFromSequence (object, npy_intp *, int) except -1
680
+ object PyArray_Concatenate (object, int)
681
+ object PyArray_InnerProduct (object, object)
682
+ object PyArray_MatrixProduct (object, object)
683
+ object PyArray_CopyAndTranspose (object)
684
+ object PyArray_Correlate (object, object, int)
685
+ int PyArray_TypestrConvert (int, int)
686
+ #int PyArray_DescrConverter (object, dtype*) except 0
687
+ #int PyArray_DescrConverter2 (object, dtype*) except 0
688
+ int PyArray_IntpConverter (object, PyArray_Dims *) except 0
689
+ #int PyArray_BufferConverter (object, chunk) except 0
690
+ int PyArray_AxisConverter (object, int *) except 0
691
+ int PyArray_BoolConverter (object, npy_bool *) except 0
692
+ int PyArray_ByteorderConverter (object, char *) except 0
693
+ int PyArray_OrderConverter (object, NPY_ORDER *) except 0
694
+ unsigned char PyArray_EquivTypes (dtype, dtype) # clears errors
695
+ #object PyArray_Zeros (int, npy_intp *, dtype, int)
696
+ #object PyArray_Empty (int, npy_intp *, dtype, int)
697
+ object PyArray_Where (object, object, object)
698
+ object PyArray_Arange (double, double, double, int)
699
+ #object PyArray_ArangeObj (object, object, object, dtype)
700
+ int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0
701
+ object PyArray_LexSort (object, int)
702
+ object PyArray_Round (ndarray, int, ndarray)
703
+ unsigned char PyArray_EquivTypenums (int, int)
704
+ int PyArray_RegisterDataType (dtype) except -1
705
+ int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1
706
+ int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1
707
+ #void PyArray_InitArrFuncs (PyArray_ArrFuncs *)
708
+ object PyArray_IntTupleFromIntp (int, npy_intp *)
709
+ int PyArray_TypeNumFromName (char *)
710
+ int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0
711
+ #int PyArray_OutputConverter (object, ndarray*) except 0
712
+ object PyArray_BroadcastToShape (object, npy_intp *, int)
713
+ void _PyArray_SigintHandler (int)
714
+ void* _PyArray_GetSigintBuf ()
715
+ #int PyArray_DescrAlignConverter (object, dtype*) except 0
716
+ #int PyArray_DescrAlignConverter2 (object, dtype*) except 0
717
+ int PyArray_SearchsideConverter (object, void *) except 0
718
+ object PyArray_CheckAxis (ndarray, int *, int)
719
+ npy_intp PyArray_OverflowMultiplyList (npy_intp *, int)
720
+ int PyArray_CompareString (char *, char *, size_t)
721
+ int PyArray_SetBaseObject(ndarray, base) except -1 # NOTE: steals a reference to base! Use "set_array_base()" instead.
722
+
723
+
724
+ # Typedefs that matches the runtime dtype objects in
725
+ # the numpy module.
726
+
727
+ # The ones that are commented out needs an IFDEF function
728
+ # in Cython to enable them only on the right systems.
729
+
730
+ ctypedef npy_int8 int8_t
731
+ ctypedef npy_int16 int16_t
732
+ ctypedef npy_int32 int32_t
733
+ ctypedef npy_int64 int64_t
734
+ #ctypedef npy_int96 int96_t
735
+ #ctypedef npy_int128 int128_t
736
+
737
+ ctypedef npy_uint8 uint8_t
738
+ ctypedef npy_uint16 uint16_t
739
+ ctypedef npy_uint32 uint32_t
740
+ ctypedef npy_uint64 uint64_t
741
+ #ctypedef npy_uint96 uint96_t
742
+ #ctypedef npy_uint128 uint128_t
743
+
744
+ ctypedef npy_float32 float32_t
745
+ ctypedef npy_float64 float64_t
746
+ #ctypedef npy_float80 float80_t
747
+ #ctypedef npy_float128 float128_t
748
+
749
+ ctypedef float complex complex64_t
750
+ ctypedef double complex complex128_t
751
+
752
+ # The int types are mapped a bit surprising --
753
+ # numpy.int corresponds to 'l' and numpy.long to 'q'
754
+ ctypedef npy_long int_t
755
+ ctypedef npy_longlong longlong_t
756
+
757
+ ctypedef npy_ulong uint_t
758
+ ctypedef npy_ulonglong ulonglong_t
759
+
760
+ ctypedef npy_intp intp_t
761
+ ctypedef npy_uintp uintp_t
762
+
763
+ ctypedef npy_double float_t
764
+ ctypedef npy_double double_t
765
+ ctypedef npy_longdouble longdouble_t
766
+
767
+ ctypedef npy_cfloat cfloat_t
768
+ ctypedef npy_cdouble cdouble_t
769
+ ctypedef npy_clongdouble clongdouble_t
770
+
771
+ ctypedef npy_cdouble complex_t
772
+
773
+ cdef inline object PyArray_MultiIterNew1(a):
774
+ return PyArray_MultiIterNew(1, <void*>a)
775
+
776
+ cdef inline object PyArray_MultiIterNew2(a, b):
777
+ return PyArray_MultiIterNew(2, <void*>a, <void*>b)
778
+
779
+ cdef inline object PyArray_MultiIterNew3(a, b, c):
780
+ return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
781
+
782
+ cdef inline object PyArray_MultiIterNew4(a, b, c, d):
783
+ return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
784
+
785
+ cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
786
+ return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
787
+
788
+ cdef inline tuple PyDataType_SHAPE(dtype d):
789
+ if PyDataType_HASSUBARRAY(d):
790
+ return <tuple>d.subarray.shape
791
+ else:
792
+ return ()
793
+
794
+
795
+ cdef extern from "numpy/ndarrayobject.h":
796
+ PyTypeObject PyTimedeltaArrType_Type
797
+ PyTypeObject PyDatetimeArrType_Type
798
+ ctypedef int64_t npy_timedelta
799
+ ctypedef int64_t npy_datetime
800
+
801
+ cdef extern from "numpy/ndarraytypes.h":
802
+ ctypedef struct PyArray_DatetimeMetaData:
803
+ NPY_DATETIMEUNIT base
804
+ int64_t num
805
+
806
+ cdef extern from "numpy/arrayscalars.h":
807
+
808
+ # abstract types
809
+ ctypedef class numpy.generic [object PyObject]:
810
+ pass
811
+ ctypedef class numpy.number [object PyObject]:
812
+ pass
813
+ ctypedef class numpy.integer [object PyObject]:
814
+ pass
815
+ ctypedef class numpy.signedinteger [object PyObject]:
816
+ pass
817
+ ctypedef class numpy.unsignedinteger [object PyObject]:
818
+ pass
819
+ ctypedef class numpy.inexact [object PyObject]:
820
+ pass
821
+ ctypedef class numpy.floating [object PyObject]:
822
+ pass
823
+ ctypedef class numpy.complexfloating [object PyObject]:
824
+ pass
825
+ ctypedef class numpy.flexible [object PyObject]:
826
+ pass
827
+ ctypedef class numpy.character [object PyObject]:
828
+ pass
829
+
830
+ ctypedef struct PyDatetimeScalarObject:
831
+ # PyObject_HEAD
832
+ npy_datetime obval
833
+ PyArray_DatetimeMetaData obmeta
834
+
835
+ ctypedef struct PyTimedeltaScalarObject:
836
+ # PyObject_HEAD
837
+ npy_timedelta obval
838
+ PyArray_DatetimeMetaData obmeta
839
+
840
+ ctypedef enum NPY_DATETIMEUNIT:
841
+ NPY_FR_Y
842
+ NPY_FR_M
843
+ NPY_FR_W
844
+ NPY_FR_D
845
+ NPY_FR_B
846
+ NPY_FR_h
847
+ NPY_FR_m
848
+ NPY_FR_s
849
+ NPY_FR_ms
850
+ NPY_FR_us
851
+ NPY_FR_ns
852
+ NPY_FR_ps
853
+ NPY_FR_fs
854
+ NPY_FR_as
855
+ NPY_FR_GENERIC
856
+
857
+
858
+ #
859
+ # ufunc API
860
+ #
861
+
862
+ cdef extern from "numpy/ufuncobject.h":
863
+
864
+ ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
865
+
866
+ ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]:
867
+ cdef:
868
+ int nin, nout, nargs
869
+ int identity
870
+ PyUFuncGenericFunction *functions
871
+ void **data
872
+ int ntypes
873
+ int check_return
874
+ char *name
875
+ char *types
876
+ char *doc
877
+ void *ptr
878
+ PyObject *obj
879
+ PyObject *userloops
880
+
881
+ cdef enum:
882
+ PyUFunc_Zero
883
+ PyUFunc_One
884
+ PyUFunc_None
885
+ UFUNC_ERR_IGNORE
886
+ UFUNC_ERR_WARN
887
+ UFUNC_ERR_RAISE
888
+ UFUNC_ERR_CALL
889
+ UFUNC_ERR_PRINT
890
+ UFUNC_ERR_LOG
891
+ UFUNC_MASK_DIVIDEBYZERO
892
+ UFUNC_MASK_OVERFLOW
893
+ UFUNC_MASK_UNDERFLOW
894
+ UFUNC_MASK_INVALID
895
+ UFUNC_SHIFT_DIVIDEBYZERO
896
+ UFUNC_SHIFT_OVERFLOW
897
+ UFUNC_SHIFT_UNDERFLOW
898
+ UFUNC_SHIFT_INVALID
899
+ UFUNC_FPE_DIVIDEBYZERO
900
+ UFUNC_FPE_OVERFLOW
901
+ UFUNC_FPE_UNDERFLOW
902
+ UFUNC_FPE_INVALID
903
+ UFUNC_ERR_DEFAULT
904
+ UFUNC_ERR_DEFAULT2
905
+
906
+ object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
907
+ void **, char *, int, int, int, int, char *, char *, int)
908
+ int PyUFunc_RegisterLoopForType(ufunc, int,
909
+ PyUFuncGenericFunction, int *, void *) except -1
910
+ void PyUFunc_f_f_As_d_d \
911
+ (char **, npy_intp *, npy_intp *, void *)
912
+ void PyUFunc_d_d \
913
+ (char **, npy_intp *, npy_intp *, void *)
914
+ void PyUFunc_f_f \
915
+ (char **, npy_intp *, npy_intp *, void *)
916
+ void PyUFunc_g_g \
917
+ (char **, npy_intp *, npy_intp *, void *)
918
+ void PyUFunc_F_F_As_D_D \
919
+ (char **, npy_intp *, npy_intp *, void *)
920
+ void PyUFunc_F_F \
921
+ (char **, npy_intp *, npy_intp *, void *)
922
+ void PyUFunc_D_D \
923
+ (char **, npy_intp *, npy_intp *, void *)
924
+ void PyUFunc_G_G \
925
+ (char **, npy_intp *, npy_intp *, void *)
926
+ void PyUFunc_O_O \
927
+ (char **, npy_intp *, npy_intp *, void *)
928
+ void PyUFunc_ff_f_As_dd_d \
929
+ (char **, npy_intp *, npy_intp *, void *)
930
+ void PyUFunc_ff_f \
931
+ (char **, npy_intp *, npy_intp *, void *)
932
+ void PyUFunc_dd_d \
933
+ (char **, npy_intp *, npy_intp *, void *)
934
+ void PyUFunc_gg_g \
935
+ (char **, npy_intp *, npy_intp *, void *)
936
+ void PyUFunc_FF_F_As_DD_D \
937
+ (char **, npy_intp *, npy_intp *, void *)
938
+ void PyUFunc_DD_D \
939
+ (char **, npy_intp *, npy_intp *, void *)
940
+ void PyUFunc_FF_F \
941
+ (char **, npy_intp *, npy_intp *, void *)
942
+ void PyUFunc_GG_G \
943
+ (char **, npy_intp *, npy_intp *, void *)
944
+ void PyUFunc_OO_O \
945
+ (char **, npy_intp *, npy_intp *, void *)
946
+ void PyUFunc_O_O_method \
947
+ (char **, npy_intp *, npy_intp *, void *)
948
+ void PyUFunc_OO_O_method \
949
+ (char **, npy_intp *, npy_intp *, void *)
950
+ void PyUFunc_On_Om \
951
+ (char **, npy_intp *, npy_intp *, void *)
952
+ int PyUFunc_GetPyValues \
953
+ (char *, int *, int *, PyObject **)
954
+ int PyUFunc_checkfperr \
955
+ (int, PyObject *, int *)
956
+ void PyUFunc_clearfperr()
957
+ int PyUFunc_getfperr()
958
+ int PyUFunc_handlefperr \
959
+ (int, PyObject *, int, int *) except -1
960
+ int PyUFunc_ReplaceLoopBySignature \
961
+ (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
962
+ object PyUFunc_FromFuncAndDataAndSignature \
963
+ (PyUFuncGenericFunction *, void **, char *, int, int, int,
964
+ int, char *, char *, int, char *)
965
+
966
+ int _import_umath() except -1
967
+
968
+ cdef inline void set_array_base(ndarray arr, object base):
969
+ Py_INCREF(base) # important to do this before stealing the reference below!
970
+ PyArray_SetBaseObject(arr, base)
971
+
972
+ cdef inline object get_array_base(ndarray arr):
973
+ base = PyArray_BASE(arr)
974
+ if base is NULL:
975
+ return None
976
+ return <object>base
977
+
978
+ # Versions of the import_* functions which are more suitable for
979
+ # Cython code.
980
+ cdef inline int import_array() except -1:
981
+ try:
982
+ __pyx_import_array()
983
+ except Exception:
984
+ raise ImportError("numpy.core.multiarray failed to import")
985
+
986
+ cdef inline int import_umath() except -1:
987
+ try:
988
+ _import_umath()
989
+ except Exception:
990
+ raise ImportError("numpy.core.umath failed to import")
991
+
992
+ cdef inline int import_ufunc() except -1:
993
+ try:
994
+ _import_umath()
995
+ except Exception:
996
+ raise ImportError("numpy.core.umath failed to import")
997
+
998
+
999
+ cdef inline bint is_timedelta64_object(object obj):
1000
+ """
1001
+ Cython equivalent of `isinstance(obj, np.timedelta64)`
1002
+
1003
+ Parameters
1004
+ ----------
1005
+ obj : object
1006
+
1007
+ Returns
1008
+ -------
1009
+ bool
1010
+ """
1011
+ return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
1012
+
1013
+
1014
+ cdef inline bint is_datetime64_object(object obj):
1015
+ """
1016
+ Cython equivalent of `isinstance(obj, np.datetime64)`
1017
+
1018
+ Parameters
1019
+ ----------
1020
+ obj : object
1021
+
1022
+ Returns
1023
+ -------
1024
+ bool
1025
+ """
1026
+ return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
1027
+
1028
+
1029
+ cdef inline npy_datetime get_datetime64_value(object obj) nogil:
1030
+ """
1031
+ returns the int64 value underlying scalar numpy datetime64 object
1032
+
1033
+ Note that to interpret this as a datetime, the corresponding unit is
1034
+ also needed. That can be found using `get_datetime64_unit`.
1035
+ """
1036
+ return (<PyDatetimeScalarObject*>obj).obval
1037
+
1038
+
1039
+ cdef inline npy_timedelta get_timedelta64_value(object obj) nogil:
1040
+ """
1041
+ returns the int64 value underlying scalar numpy timedelta64 object
1042
+ """
1043
+ return (<PyTimedeltaScalarObject*>obj).obval
1044
+
1045
+
1046
+ cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil:
1047
+ """
1048
+ returns the unit part of the dtype for a numpy datetime64 object.
1049
+ """
1050
+ return <NPY_DATETIMEUNIT>(<PyDatetimeScalarObject*>obj).obmeta.base
llmeval-env/lib/python3.10/site-packages/numpy/__init__.pxd ADDED
@@ -0,0 +1,1015 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NumPy static imports for Cython < 3.0
2
+ #
3
+ # If any of the PyArray_* functions are called, import_array must be
4
+ # called first.
5
+ #
6
+ # Author: Dag Sverre Seljebotn
7
+ #
8
+
9
+ DEF _buffer_format_string_len = 255
10
+
11
+ cimport cpython.buffer as pybuf
12
+ from cpython.ref cimport Py_INCREF
13
+ from cpython.mem cimport PyObject_Malloc, PyObject_Free
14
+ from cpython.object cimport PyObject, PyTypeObject
15
+ from cpython.buffer cimport PyObject_GetBuffer
16
+ from cpython.type cimport type
17
+ cimport libc.stdio as stdio
18
+
19
+ cdef extern from "Python.h":
20
+ ctypedef int Py_intptr_t
21
+ bint PyObject_TypeCheck(object obj, PyTypeObject* type)
22
+
23
+ cdef extern from "numpy/arrayobject.h":
24
+ ctypedef Py_intptr_t npy_intp
25
+ ctypedef size_t npy_uintp
26
+
27
+ cdef enum NPY_TYPES:
28
+ NPY_BOOL
29
+ NPY_BYTE
30
+ NPY_UBYTE
31
+ NPY_SHORT
32
+ NPY_USHORT
33
+ NPY_INT
34
+ NPY_UINT
35
+ NPY_LONG
36
+ NPY_ULONG
37
+ NPY_LONGLONG
38
+ NPY_ULONGLONG
39
+ NPY_FLOAT
40
+ NPY_DOUBLE
41
+ NPY_LONGDOUBLE
42
+ NPY_CFLOAT
43
+ NPY_CDOUBLE
44
+ NPY_CLONGDOUBLE
45
+ NPY_OBJECT
46
+ NPY_STRING
47
+ NPY_UNICODE
48
+ NPY_VOID
49
+ NPY_DATETIME
50
+ NPY_TIMEDELTA
51
+ NPY_NTYPES
52
+ NPY_NOTYPE
53
+
54
+ NPY_INT8
55
+ NPY_INT16
56
+ NPY_INT32
57
+ NPY_INT64
58
+ NPY_INT128
59
+ NPY_INT256
60
+ NPY_UINT8
61
+ NPY_UINT16
62
+ NPY_UINT32
63
+ NPY_UINT64
64
+ NPY_UINT128
65
+ NPY_UINT256
66
+ NPY_FLOAT16
67
+ NPY_FLOAT32
68
+ NPY_FLOAT64
69
+ NPY_FLOAT80
70
+ NPY_FLOAT96
71
+ NPY_FLOAT128
72
+ NPY_FLOAT256
73
+ NPY_COMPLEX32
74
+ NPY_COMPLEX64
75
+ NPY_COMPLEX128
76
+ NPY_COMPLEX160
77
+ NPY_COMPLEX192
78
+ NPY_COMPLEX256
79
+ NPY_COMPLEX512
80
+
81
+ NPY_INTP
82
+
83
+ ctypedef enum NPY_ORDER:
84
+ NPY_ANYORDER
85
+ NPY_CORDER
86
+ NPY_FORTRANORDER
87
+ NPY_KEEPORDER
88
+
89
+ ctypedef enum NPY_CASTING:
90
+ NPY_NO_CASTING
91
+ NPY_EQUIV_CASTING
92
+ NPY_SAFE_CASTING
93
+ NPY_SAME_KIND_CASTING
94
+ NPY_UNSAFE_CASTING
95
+
96
+ ctypedef enum NPY_CLIPMODE:
97
+ NPY_CLIP
98
+ NPY_WRAP
99
+ NPY_RAISE
100
+
101
+ ctypedef enum NPY_SCALARKIND:
102
+ NPY_NOSCALAR,
103
+ NPY_BOOL_SCALAR,
104
+ NPY_INTPOS_SCALAR,
105
+ NPY_INTNEG_SCALAR,
106
+ NPY_FLOAT_SCALAR,
107
+ NPY_COMPLEX_SCALAR,
108
+ NPY_OBJECT_SCALAR
109
+
110
+ ctypedef enum NPY_SORTKIND:
111
+ NPY_QUICKSORT
112
+ NPY_HEAPSORT
113
+ NPY_MERGESORT
114
+
115
+ ctypedef enum NPY_SEARCHSIDE:
116
+ NPY_SEARCHLEFT
117
+ NPY_SEARCHRIGHT
118
+
119
+ enum:
120
+ # DEPRECATED since NumPy 1.7 ! Do not use in new code!
121
+ NPY_C_CONTIGUOUS
122
+ NPY_F_CONTIGUOUS
123
+ NPY_CONTIGUOUS
124
+ NPY_FORTRAN
125
+ NPY_OWNDATA
126
+ NPY_FORCECAST
127
+ NPY_ENSURECOPY
128
+ NPY_ENSUREARRAY
129
+ NPY_ELEMENTSTRIDES
130
+ NPY_ALIGNED
131
+ NPY_NOTSWAPPED
132
+ NPY_WRITEABLE
133
+ NPY_ARR_HAS_DESCR
134
+
135
+ NPY_BEHAVED
136
+ NPY_BEHAVED_NS
137
+ NPY_CARRAY
138
+ NPY_CARRAY_RO
139
+ NPY_FARRAY
140
+ NPY_FARRAY_RO
141
+ NPY_DEFAULT
142
+
143
+ NPY_IN_ARRAY
144
+ NPY_OUT_ARRAY
145
+ NPY_INOUT_ARRAY
146
+ NPY_IN_FARRAY
147
+ NPY_OUT_FARRAY
148
+ NPY_INOUT_FARRAY
149
+
150
+ NPY_UPDATE_ALL
151
+
152
+ enum:
153
+ # Added in NumPy 1.7 to replace the deprecated enums above.
154
+ NPY_ARRAY_C_CONTIGUOUS
155
+ NPY_ARRAY_F_CONTIGUOUS
156
+ NPY_ARRAY_OWNDATA
157
+ NPY_ARRAY_FORCECAST
158
+ NPY_ARRAY_ENSURECOPY
159
+ NPY_ARRAY_ENSUREARRAY
160
+ NPY_ARRAY_ELEMENTSTRIDES
161
+ NPY_ARRAY_ALIGNED
162
+ NPY_ARRAY_NOTSWAPPED
163
+ NPY_ARRAY_WRITEABLE
164
+ NPY_ARRAY_WRITEBACKIFCOPY
165
+
166
+ NPY_ARRAY_BEHAVED
167
+ NPY_ARRAY_BEHAVED_NS
168
+ NPY_ARRAY_CARRAY
169
+ NPY_ARRAY_CARRAY_RO
170
+ NPY_ARRAY_FARRAY
171
+ NPY_ARRAY_FARRAY_RO
172
+ NPY_ARRAY_DEFAULT
173
+
174
+ NPY_ARRAY_IN_ARRAY
175
+ NPY_ARRAY_OUT_ARRAY
176
+ NPY_ARRAY_INOUT_ARRAY
177
+ NPY_ARRAY_IN_FARRAY
178
+ NPY_ARRAY_OUT_FARRAY
179
+ NPY_ARRAY_INOUT_FARRAY
180
+
181
+ NPY_ARRAY_UPDATE_ALL
182
+
183
+ cdef enum:
184
+ NPY_MAXDIMS
185
+
186
+ npy_intp NPY_MAX_ELSIZE
187
+
188
+ ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *)
189
+
190
+ ctypedef struct PyArray_ArrayDescr:
191
+ # shape is a tuple, but Cython doesn't support "tuple shape"
192
+ # inside a non-PyObject declaration, so we have to declare it
193
+ # as just a PyObject*.
194
+ PyObject* shape
195
+
196
+ ctypedef struct PyArray_Descr:
197
+ pass
198
+
199
+ ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]:
200
+ # Use PyDataType_* macros when possible, however there are no macros
201
+ # for accessing some of the fields, so some are defined.
202
+ cdef PyTypeObject* typeobj
203
+ cdef char kind
204
+ cdef char type
205
+ # Numpy sometimes mutates this without warning (e.g. it'll
206
+ # sometimes change "|" to "<" in shared dtype objects on
207
+ # little-endian machines). If this matters to you, use
208
+ # PyArray_IsNativeByteOrder(dtype.byteorder) instead of
209
+ # directly accessing this field.
210
+ cdef char byteorder
211
+ cdef char flags
212
+ cdef int type_num
213
+ cdef int itemsize "elsize"
214
+ cdef int alignment
215
+ cdef object fields
216
+ cdef tuple names
217
+ # Use PyDataType_HASSUBARRAY to test whether this field is
218
+ # valid (the pointer can be NULL). Most users should access
219
+ # this field via the inline helper method PyDataType_SHAPE.
220
+ cdef PyArray_ArrayDescr* subarray
221
+
222
+ ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]:
223
+ # Use through macros
224
+ pass
225
+
226
+ ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]:
227
+ cdef int numiter
228
+ cdef npy_intp size, index
229
+ cdef int nd
230
+ cdef npy_intp *dimensions
231
+ cdef void **iters
232
+
233
+ ctypedef struct PyArrayObject:
234
+ # For use in situations where ndarray can't replace PyArrayObject*,
235
+ # like PyArrayObject**.
236
+ pass
237
+
238
+ ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
239
+ cdef __cythonbufferdefaults__ = {"mode": "strided"}
240
+
241
+ cdef:
242
+ # Only taking a few of the most commonly used and stable fields.
243
+ # One should use PyArray_* macros instead to access the C fields.
244
+ char *data
245
+ int ndim "nd"
246
+ npy_intp *shape "dimensions"
247
+ npy_intp *strides
248
+ dtype descr # deprecated since NumPy 1.7 !
249
+ PyObject* base # NOT PUBLIC, DO NOT USE !
250
+
251
+
252
+
253
+ ctypedef unsigned char npy_bool
254
+
255
+ ctypedef signed char npy_byte
256
+ ctypedef signed short npy_short
257
+ ctypedef signed int npy_int
258
+ ctypedef signed long npy_long
259
+ ctypedef signed long long npy_longlong
260
+
261
+ ctypedef unsigned char npy_ubyte
262
+ ctypedef unsigned short npy_ushort
263
+ ctypedef unsigned int npy_uint
264
+ ctypedef unsigned long npy_ulong
265
+ ctypedef unsigned long long npy_ulonglong
266
+
267
+ ctypedef float npy_float
268
+ ctypedef double npy_double
269
+ ctypedef long double npy_longdouble
270
+
271
+ ctypedef signed char npy_int8
272
+ ctypedef signed short npy_int16
273
+ ctypedef signed int npy_int32
274
+ ctypedef signed long long npy_int64
275
+ ctypedef signed long long npy_int96
276
+ ctypedef signed long long npy_int128
277
+
278
+ ctypedef unsigned char npy_uint8
279
+ ctypedef unsigned short npy_uint16
280
+ ctypedef unsigned int npy_uint32
281
+ ctypedef unsigned long long npy_uint64
282
+ ctypedef unsigned long long npy_uint96
283
+ ctypedef unsigned long long npy_uint128
284
+
285
+ ctypedef float npy_float32
286
+ ctypedef double npy_float64
287
+ ctypedef long double npy_float80
288
+ ctypedef long double npy_float96
289
+ ctypedef long double npy_float128
290
+
291
+ ctypedef struct npy_cfloat:
292
+ float real
293
+ float imag
294
+
295
+ ctypedef struct npy_cdouble:
296
+ double real
297
+ double imag
298
+
299
+ ctypedef struct npy_clongdouble:
300
+ long double real
301
+ long double imag
302
+
303
+ ctypedef struct npy_complex64:
304
+ float real
305
+ float imag
306
+
307
+ ctypedef struct npy_complex128:
308
+ double real
309
+ double imag
310
+
311
+ ctypedef struct npy_complex160:
312
+ long double real
313
+ long double imag
314
+
315
+ ctypedef struct npy_complex192:
316
+ long double real
317
+ long double imag
318
+
319
+ ctypedef struct npy_complex256:
320
+ long double real
321
+ long double imag
322
+
323
+ ctypedef struct PyArray_Dims:
324
+ npy_intp *ptr
325
+ int len
326
+
327
+ int _import_array() except -1
328
+ # A second definition so _import_array isn't marked as used when we use it here.
329
+ # Do not use - subject to change any time.
330
+ int __pyx_import_array "_import_array"() except -1
331
+
332
+ #
333
+ # Macros from ndarrayobject.h
334
+ #
335
+ bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
336
+ bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
337
+ bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
338
+ bint PyArray_ISCONTIGUOUS(ndarray m) nogil
339
+ bint PyArray_ISWRITEABLE(ndarray m) nogil
340
+ bint PyArray_ISALIGNED(ndarray m) nogil
341
+
342
+ int PyArray_NDIM(ndarray) nogil
343
+ bint PyArray_ISONESEGMENT(ndarray) nogil
344
+ bint PyArray_ISFORTRAN(ndarray) nogil
345
+ int PyArray_FORTRANIF(ndarray) nogil
346
+
347
+ void* PyArray_DATA(ndarray) nogil
348
+ char* PyArray_BYTES(ndarray) nogil
349
+
350
+ npy_intp* PyArray_DIMS(ndarray) nogil
351
+ npy_intp* PyArray_STRIDES(ndarray) nogil
352
+ npy_intp PyArray_DIM(ndarray, size_t) nogil
353
+ npy_intp PyArray_STRIDE(ndarray, size_t) nogil
354
+
355
+ PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference!
356
+ PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype!
357
+ int PyArray_FLAGS(ndarray) nogil
358
+ npy_intp PyArray_ITEMSIZE(ndarray) nogil
359
+ int PyArray_TYPE(ndarray arr) nogil
360
+
361
+ object PyArray_GETITEM(ndarray arr, void *itemptr)
362
+ int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1
363
+
364
+ bint PyTypeNum_ISBOOL(int) nogil
365
+ bint PyTypeNum_ISUNSIGNED(int) nogil
366
+ bint PyTypeNum_ISSIGNED(int) nogil
367
+ bint PyTypeNum_ISINTEGER(int) nogil
368
+ bint PyTypeNum_ISFLOAT(int) nogil
369
+ bint PyTypeNum_ISNUMBER(int) nogil
370
+ bint PyTypeNum_ISSTRING(int) nogil
371
+ bint PyTypeNum_ISCOMPLEX(int) nogil
372
+ bint PyTypeNum_ISPYTHON(int) nogil
373
+ bint PyTypeNum_ISFLEXIBLE(int) nogil
374
+ bint PyTypeNum_ISUSERDEF(int) nogil
375
+ bint PyTypeNum_ISEXTENDED(int) nogil
376
+ bint PyTypeNum_ISOBJECT(int) nogil
377
+
378
+ bint PyDataType_ISBOOL(dtype) nogil
379
+ bint PyDataType_ISUNSIGNED(dtype) nogil
380
+ bint PyDataType_ISSIGNED(dtype) nogil
381
+ bint PyDataType_ISINTEGER(dtype) nogil
382
+ bint PyDataType_ISFLOAT(dtype) nogil
383
+ bint PyDataType_ISNUMBER(dtype) nogil
384
+ bint PyDataType_ISSTRING(dtype) nogil
385
+ bint PyDataType_ISCOMPLEX(dtype) nogil
386
+ bint PyDataType_ISPYTHON(dtype) nogil
387
+ bint PyDataType_ISFLEXIBLE(dtype) nogil
388
+ bint PyDataType_ISUSERDEF(dtype) nogil
389
+ bint PyDataType_ISEXTENDED(dtype) nogil
390
+ bint PyDataType_ISOBJECT(dtype) nogil
391
+ bint PyDataType_HASFIELDS(dtype) nogil
392
+ bint PyDataType_HASSUBARRAY(dtype) nogil
393
+
394
+ bint PyArray_ISBOOL(ndarray) nogil
395
+ bint PyArray_ISUNSIGNED(ndarray) nogil
396
+ bint PyArray_ISSIGNED(ndarray) nogil
397
+ bint PyArray_ISINTEGER(ndarray) nogil
398
+ bint PyArray_ISFLOAT(ndarray) nogil
399
+ bint PyArray_ISNUMBER(ndarray) nogil
400
+ bint PyArray_ISSTRING(ndarray) nogil
401
+ bint PyArray_ISCOMPLEX(ndarray) nogil
402
+ bint PyArray_ISPYTHON(ndarray) nogil
403
+ bint PyArray_ISFLEXIBLE(ndarray) nogil
404
+ bint PyArray_ISUSERDEF(ndarray) nogil
405
+ bint PyArray_ISEXTENDED(ndarray) nogil
406
+ bint PyArray_ISOBJECT(ndarray) nogil
407
+ bint PyArray_HASFIELDS(ndarray) nogil
408
+
409
+ bint PyArray_ISVARIABLE(ndarray) nogil
410
+
411
+ bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil
412
+ bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder
413
+ bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder
414
+ bint PyArray_ISNOTSWAPPED(ndarray) nogil
415
+ bint PyArray_ISBYTESWAPPED(ndarray) nogil
416
+
417
+ bint PyArray_FLAGSWAP(ndarray, int) nogil
418
+
419
+ bint PyArray_ISCARRAY(ndarray) nogil
420
+ bint PyArray_ISCARRAY_RO(ndarray) nogil
421
+ bint PyArray_ISFARRAY(ndarray) nogil
422
+ bint PyArray_ISFARRAY_RO(ndarray) nogil
423
+ bint PyArray_ISBEHAVED(ndarray) nogil
424
+ bint PyArray_ISBEHAVED_RO(ndarray) nogil
425
+
426
+
427
+ bint PyDataType_ISNOTSWAPPED(dtype) nogil
428
+ bint PyDataType_ISBYTESWAPPED(dtype) nogil
429
+
430
+ bint PyArray_DescrCheck(object)
431
+
432
+ bint PyArray_Check(object)
433
+ bint PyArray_CheckExact(object)
434
+
435
+ # Cannot be supported due to out arg:
436
+ # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&)
437
+ # bint PyArray_HasArrayInterface(op, out)
438
+
439
+
440
+ bint PyArray_IsZeroDim(object)
441
+ # Cannot be supported due to ## ## in macro:
442
+ # bint PyArray_IsScalar(object, verbatim work)
443
+ bint PyArray_CheckScalar(object)
444
+ bint PyArray_IsPythonNumber(object)
445
+ bint PyArray_IsPythonScalar(object)
446
+ bint PyArray_IsAnyScalar(object)
447
+ bint PyArray_CheckAnyScalar(object)
448
+
449
+ ndarray PyArray_GETCONTIGUOUS(ndarray)
450
+ bint PyArray_SAMESHAPE(ndarray, ndarray) nogil
451
+ npy_intp PyArray_SIZE(ndarray) nogil
452
+ npy_intp PyArray_NBYTES(ndarray) nogil
453
+
454
+ object PyArray_FROM_O(object)
455
+ object PyArray_FROM_OF(object m, int flags)
456
+ object PyArray_FROM_OT(object m, int type)
457
+ object PyArray_FROM_OTF(object m, int type, int flags)
458
+ object PyArray_FROMANY(object m, int type, int min, int max, int flags)
459
+ object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
460
+ object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
461
+ void PyArray_FILLWBYTE(object, int val)
462
+ npy_intp PyArray_REFCOUNT(object)
463
+ object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
464
+ unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
465
+ bint PyArray_EquivByteorders(int b1, int b2) nogil
466
+ object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
467
+ object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
468
+ #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr)
469
+ object PyArray_ToScalar(void* data, ndarray arr)
470
+
471
+ void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil
472
+ void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil
473
+ void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil
474
+ void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil
475
+
476
+ # Cannot be supported due to out arg
477
+ # void PyArray_DESCR_REPLACE(descr)
478
+
479
+
480
+ object PyArray_Copy(ndarray)
481
+ object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
482
+ object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
483
+ object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
484
+
485
+ object PyArray_Cast(ndarray mp, int type_num)
486
+ object PyArray_Take(ndarray ap, object items, int axis)
487
+ object PyArray_Put(ndarray ap, object items, object values)
488
+
489
+ void PyArray_ITER_RESET(flatiter it) nogil
490
+ void PyArray_ITER_NEXT(flatiter it) nogil
491
+ void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
492
+ void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
493
+ void* PyArray_ITER_DATA(flatiter it) nogil
494
+ bint PyArray_ITER_NOTDONE(flatiter it) nogil
495
+
496
+ void PyArray_MultiIter_RESET(broadcast multi) nogil
497
+ void PyArray_MultiIter_NEXT(broadcast multi) nogil
498
+ void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
499
+ void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
500
+ void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
501
+ void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
502
+ bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
503
+
504
+ # Functions from __multiarray_api.h
505
+
506
+ # Functions taking dtype and returning object/ndarray are disabled
507
+ # for now as they steal dtype references. I'm conservative and disable
508
+ # more than is probably needed until it can be checked further.
509
+ int PyArray_SetNumericOps (object) except -1
510
+ object PyArray_GetNumericOps ()
511
+ int PyArray_INCREF (ndarray) except * # uses PyArray_Item_INCREF...
512
+ int PyArray_XDECREF (ndarray) except * # uses PyArray_Item_DECREF...
513
+ void PyArray_SetStringFunction (object, int)
514
+ dtype PyArray_DescrFromType (int)
515
+ object PyArray_TypeObjectFromType (int)
516
+ char * PyArray_Zero (ndarray)
517
+ char * PyArray_One (ndarray)
518
+ #object PyArray_CastToType (ndarray, dtype, int)
519
+ int PyArray_CastTo (ndarray, ndarray) except -1
520
+ int PyArray_CastAnyTo (ndarray, ndarray) except -1
521
+ int PyArray_CanCastSafely (int, int) # writes errors
522
+ npy_bool PyArray_CanCastTo (dtype, dtype) # writes errors
523
+ int PyArray_ObjectType (object, int) except 0
524
+ dtype PyArray_DescrFromObject (object, dtype)
525
+ #ndarray* PyArray_ConvertToCommonType (object, int *)
526
+ dtype PyArray_DescrFromScalar (object)
527
+ dtype PyArray_DescrFromTypeObject (object)
528
+ npy_intp PyArray_Size (object)
529
+ #object PyArray_Scalar (void *, dtype, object)
530
+ #object PyArray_FromScalar (object, dtype)
531
+ void PyArray_ScalarAsCtype (object, void *)
532
+ #int PyArray_CastScalarToCtype (object, void *, dtype)
533
+ #int PyArray_CastScalarDirect (object, dtype, void *, int)
534
+ object PyArray_ScalarFromObject (object)
535
+ #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int)
536
+ object PyArray_FromDims (int, int *, int)
537
+ #object PyArray_FromDimsAndDataAndDescr (int, int *, dtype, char *)
538
+ #object PyArray_FromAny (object, dtype, int, int, int, object)
539
+ object PyArray_EnsureArray (object)
540
+ object PyArray_EnsureAnyArray (object)
541
+ #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *)
542
+ #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *)
543
+ #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp)
544
+ #object PyArray_FromIter (object, dtype, npy_intp)
545
+ object PyArray_Return (ndarray)
546
+ #object PyArray_GetField (ndarray, dtype, int)
547
+ #int PyArray_SetField (ndarray, dtype, int, object) except -1
548
+ object PyArray_Byteswap (ndarray, npy_bool)
549
+ object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER)
550
+ int PyArray_MoveInto (ndarray, ndarray) except -1
551
+ int PyArray_CopyInto (ndarray, ndarray) except -1
552
+ int PyArray_CopyAnyInto (ndarray, ndarray) except -1
553
+ int PyArray_CopyObject (ndarray, object) except -1
554
+ object PyArray_NewCopy (ndarray, NPY_ORDER)
555
+ object PyArray_ToList (ndarray)
556
+ object PyArray_ToString (ndarray, NPY_ORDER)
557
+ int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1
558
+ int PyArray_Dump (object, object, int) except -1
559
+ object PyArray_Dumps (object, int)
560
+ int PyArray_ValidType (int) # Cannot error
561
+ void PyArray_UpdateFlags (ndarray, int)
562
+ object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object)
563
+ #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object)
564
+ #dtype PyArray_DescrNew (dtype)
565
+ dtype PyArray_DescrNewFromType (int)
566
+ double PyArray_GetPriority (object, double) # clears errors as of 1.25
567
+ object PyArray_IterNew (object)
568
+ object PyArray_MultiIterNew (int, ...)
569
+
570
+ int PyArray_PyIntAsInt (object) except? -1
571
+ npy_intp PyArray_PyIntAsIntp (object)
572
+ int PyArray_Broadcast (broadcast) except -1
573
+ void PyArray_FillObjectArray (ndarray, object) except *
574
+ int PyArray_FillWithScalar (ndarray, object) except -1
575
+ npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
576
+ dtype PyArray_DescrNewByteorder (dtype, char)
577
+ object PyArray_IterAllButAxis (object, int *)
578
+ #object PyArray_CheckFromAny (object, dtype, int, int, int, object)
579
+ #object PyArray_FromArray (ndarray, dtype, int)
580
+ object PyArray_FromInterface (object)
581
+ object PyArray_FromStructInterface (object)
582
+ #object PyArray_FromArrayAttr (object, dtype, object)
583
+ #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*)
584
+ int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
585
+ object PyArray_NewFlagsObject (object)
586
+ npy_bool PyArray_CanCastScalar (type, type)
587
+ #int PyArray_CompareUCS4 (npy_ucs4 *, npy_ucs4 *, register size_t)
588
+ int PyArray_RemoveSmallest (broadcast) except -1
589
+ int PyArray_ElementStrides (object)
590
+ void PyArray_Item_INCREF (char *, dtype) except *
591
+ void PyArray_Item_XDECREF (char *, dtype) except *
592
+ object PyArray_FieldNames (object)
593
+ object PyArray_Transpose (ndarray, PyArray_Dims *)
594
+ object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
595
+ object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
596
+ object PyArray_PutMask (ndarray, object, object)
597
+ object PyArray_Repeat (ndarray, object, int)
598
+ object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
599
+ int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1
600
+ object PyArray_ArgSort (ndarray, int, NPY_SORTKIND)
601
+ object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *)
602
+ object PyArray_ArgMax (ndarray, int, ndarray)
603
+ object PyArray_ArgMin (ndarray, int, ndarray)
604
+ object PyArray_Reshape (ndarray, object)
605
+ object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
606
+ object PyArray_Squeeze (ndarray)
607
+ #object PyArray_View (ndarray, dtype, type)
608
+ object PyArray_SwapAxes (ndarray, int, int)
609
+ object PyArray_Max (ndarray, int, ndarray)
610
+ object PyArray_Min (ndarray, int, ndarray)
611
+ object PyArray_Ptp (ndarray, int, ndarray)
612
+ object PyArray_Mean (ndarray, int, int, ndarray)
613
+ object PyArray_Trace (ndarray, int, int, int, int, ndarray)
614
+ object PyArray_Diagonal (ndarray, int, int, int)
615
+ object PyArray_Clip (ndarray, object, object, ndarray)
616
+ object PyArray_Conjugate (ndarray, ndarray)
617
+ object PyArray_Nonzero (ndarray)
618
+ object PyArray_Std (ndarray, int, int, ndarray, int)
619
+ object PyArray_Sum (ndarray, int, int, ndarray)
620
+ object PyArray_CumSum (ndarray, int, int, ndarray)
621
+ object PyArray_Prod (ndarray, int, int, ndarray)
622
+ object PyArray_CumProd (ndarray, int, int, ndarray)
623
+ object PyArray_All (ndarray, int, ndarray)
624
+ object PyArray_Any (ndarray, int, ndarray)
625
+ object PyArray_Compress (ndarray, object, int, ndarray)
626
+ object PyArray_Flatten (ndarray, NPY_ORDER)
627
+ object PyArray_Ravel (ndarray, NPY_ORDER)
628
+ npy_intp PyArray_MultiplyList (npy_intp *, int)
629
+ int PyArray_MultiplyIntList (int *, int)
630
+ void * PyArray_GetPtr (ndarray, npy_intp*)
631
+ int PyArray_CompareLists (npy_intp *, npy_intp *, int)
632
+ #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype)
633
+ #int PyArray_As1D (object*, char **, int *, int)
634
+ #int PyArray_As2D (object*, char ***, int *, int *, int)
635
+ int PyArray_Free (object, void *)
636
+ #int PyArray_Converter (object, object*)
637
+ int PyArray_IntpFromSequence (object, npy_intp *, int) except -1
638
+ object PyArray_Concatenate (object, int)
639
+ object PyArray_InnerProduct (object, object)
640
+ object PyArray_MatrixProduct (object, object)
641
+ object PyArray_CopyAndTranspose (object)
642
+ object PyArray_Correlate (object, object, int)
643
+ int PyArray_TypestrConvert (int, int)
644
+ #int PyArray_DescrConverter (object, dtype*) except 0
645
+ #int PyArray_DescrConverter2 (object, dtype*) except 0
646
+ int PyArray_IntpConverter (object, PyArray_Dims *) except 0
647
+ #int PyArray_BufferConverter (object, chunk) except 0
648
+ int PyArray_AxisConverter (object, int *) except 0
649
+ int PyArray_BoolConverter (object, npy_bool *) except 0
650
+ int PyArray_ByteorderConverter (object, char *) except 0
651
+ int PyArray_OrderConverter (object, NPY_ORDER *) except 0
652
+ unsigned char PyArray_EquivTypes (dtype, dtype) # clears errors
653
+ #object PyArray_Zeros (int, npy_intp *, dtype, int)
654
+ #object PyArray_Empty (int, npy_intp *, dtype, int)
655
+ object PyArray_Where (object, object, object)
656
+ object PyArray_Arange (double, double, double, int)
657
+ #object PyArray_ArangeObj (object, object, object, dtype)
658
+ int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0
659
+ object PyArray_LexSort (object, int)
660
+ object PyArray_Round (ndarray, int, ndarray)
661
+ unsigned char PyArray_EquivTypenums (int, int)
662
+ int PyArray_RegisterDataType (dtype) except -1
663
+ int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1
664
+ int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1
665
+ #void PyArray_InitArrFuncs (PyArray_ArrFuncs *)
666
+ object PyArray_IntTupleFromIntp (int, npy_intp *)
667
+ int PyArray_TypeNumFromName (char *)
668
+ int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0
669
+ #int PyArray_OutputConverter (object, ndarray*) except 0
670
+ object PyArray_BroadcastToShape (object, npy_intp *, int)
671
+ void _PyArray_SigintHandler (int)
672
+ void* _PyArray_GetSigintBuf ()
673
+ #int PyArray_DescrAlignConverter (object, dtype*) except 0
674
+ #int PyArray_DescrAlignConverter2 (object, dtype*) except 0
675
+ int PyArray_SearchsideConverter (object, void *) except 0
676
+ object PyArray_CheckAxis (ndarray, int *, int)
677
+ npy_intp PyArray_OverflowMultiplyList (npy_intp *, int)
678
+ int PyArray_CompareString (char *, char *, size_t)
679
+ int PyArray_SetBaseObject(ndarray, base) except -1 # NOTE: steals a reference to base! Use "set_array_base()" instead.
680
+
681
+
682
+ # Typedefs that matches the runtime dtype objects in
683
+ # the numpy module.
684
+
685
+ # The ones that are commented out needs an IFDEF function
686
+ # in Cython to enable them only on the right systems.
687
+
688
+ ctypedef npy_int8 int8_t
689
+ ctypedef npy_int16 int16_t
690
+ ctypedef npy_int32 int32_t
691
+ ctypedef npy_int64 int64_t
692
+ #ctypedef npy_int96 int96_t
693
+ #ctypedef npy_int128 int128_t
694
+
695
+ ctypedef npy_uint8 uint8_t
696
+ ctypedef npy_uint16 uint16_t
697
+ ctypedef npy_uint32 uint32_t
698
+ ctypedef npy_uint64 uint64_t
699
+ #ctypedef npy_uint96 uint96_t
700
+ #ctypedef npy_uint128 uint128_t
701
+
702
+ ctypedef npy_float32 float32_t
703
+ ctypedef npy_float64 float64_t
704
+ #ctypedef npy_float80 float80_t
705
+ #ctypedef npy_float128 float128_t
706
+
707
+ ctypedef float complex complex64_t
708
+ ctypedef double complex complex128_t
709
+
710
+ # The int types are mapped a bit surprising --
711
+ # numpy.int corresponds to 'l' and numpy.long to 'q'
712
+ ctypedef npy_long int_t
713
+ ctypedef npy_longlong longlong_t
714
+
715
+ ctypedef npy_ulong uint_t
716
+ ctypedef npy_ulonglong ulonglong_t
717
+
718
+ ctypedef npy_intp intp_t
719
+ ctypedef npy_uintp uintp_t
720
+
721
+ ctypedef npy_double float_t
722
+ ctypedef npy_double double_t
723
+ ctypedef npy_longdouble longdouble_t
724
+
725
+ ctypedef npy_cfloat cfloat_t
726
+ ctypedef npy_cdouble cdouble_t
727
+ ctypedef npy_clongdouble clongdouble_t
728
+
729
+ ctypedef npy_cdouble complex_t
730
+
731
+ cdef inline object PyArray_MultiIterNew1(a):
732
+ return PyArray_MultiIterNew(1, <void*>a)
733
+
734
+ cdef inline object PyArray_MultiIterNew2(a, b):
735
+ return PyArray_MultiIterNew(2, <void*>a, <void*>b)
736
+
737
+ cdef inline object PyArray_MultiIterNew3(a, b, c):
738
+ return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
739
+
740
+ cdef inline object PyArray_MultiIterNew4(a, b, c, d):
741
+ return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
742
+
743
+ cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
744
+ return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
745
+
746
+ cdef inline tuple PyDataType_SHAPE(dtype d):
747
+ if PyDataType_HASSUBARRAY(d):
748
+ return <tuple>d.subarray.shape
749
+ else:
750
+ return ()
751
+
752
+
753
+ cdef extern from "numpy/ndarrayobject.h":
754
+ PyTypeObject PyTimedeltaArrType_Type
755
+ PyTypeObject PyDatetimeArrType_Type
756
+ ctypedef int64_t npy_timedelta
757
+ ctypedef int64_t npy_datetime
758
+
759
+ cdef extern from "numpy/ndarraytypes.h":
760
+ ctypedef struct PyArray_DatetimeMetaData:
761
+ NPY_DATETIMEUNIT base
762
+ int64_t num
763
+
764
+ cdef extern from "numpy/arrayscalars.h":
765
+
766
+ # abstract types
767
+ ctypedef class numpy.generic [object PyObject]:
768
+ pass
769
+ ctypedef class numpy.number [object PyObject]:
770
+ pass
771
+ ctypedef class numpy.integer [object PyObject]:
772
+ pass
773
+ ctypedef class numpy.signedinteger [object PyObject]:
774
+ pass
775
+ ctypedef class numpy.unsignedinteger [object PyObject]:
776
+ pass
777
+ ctypedef class numpy.inexact [object PyObject]:
778
+ pass
779
+ ctypedef class numpy.floating [object PyObject]:
780
+ pass
781
+ ctypedef class numpy.complexfloating [object PyObject]:
782
+ pass
783
+ ctypedef class numpy.flexible [object PyObject]:
784
+ pass
785
+ ctypedef class numpy.character [object PyObject]:
786
+ pass
787
+
788
+ ctypedef struct PyDatetimeScalarObject:
789
+ # PyObject_HEAD
790
+ npy_datetime obval
791
+ PyArray_DatetimeMetaData obmeta
792
+
793
+ ctypedef struct PyTimedeltaScalarObject:
794
+ # PyObject_HEAD
795
+ npy_timedelta obval
796
+ PyArray_DatetimeMetaData obmeta
797
+
798
+ ctypedef enum NPY_DATETIMEUNIT:
799
+ NPY_FR_Y
800
+ NPY_FR_M
801
+ NPY_FR_W
802
+ NPY_FR_D
803
+ NPY_FR_B
804
+ NPY_FR_h
805
+ NPY_FR_m
806
+ NPY_FR_s
807
+ NPY_FR_ms
808
+ NPY_FR_us
809
+ NPY_FR_ns
810
+ NPY_FR_ps
811
+ NPY_FR_fs
812
+ NPY_FR_as
813
+ NPY_FR_GENERIC
814
+
815
+
816
+ #
817
+ # ufunc API
818
+ #
819
+
820
+ cdef extern from "numpy/ufuncobject.h":
821
+
822
+ ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
823
+
824
+ ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]:
825
+ cdef:
826
+ int nin, nout, nargs
827
+ int identity
828
+ PyUFuncGenericFunction *functions
829
+ void **data
830
+ int ntypes
831
+ int check_return
832
+ char *name
833
+ char *types
834
+ char *doc
835
+ void *ptr
836
+ PyObject *obj
837
+ PyObject *userloops
838
+
839
+ cdef enum:
840
+ PyUFunc_Zero
841
+ PyUFunc_One
842
+ PyUFunc_None
843
+ UFUNC_ERR_IGNORE
844
+ UFUNC_ERR_WARN
845
+ UFUNC_ERR_RAISE
846
+ UFUNC_ERR_CALL
847
+ UFUNC_ERR_PRINT
848
+ UFUNC_ERR_LOG
849
+ UFUNC_MASK_DIVIDEBYZERO
850
+ UFUNC_MASK_OVERFLOW
851
+ UFUNC_MASK_UNDERFLOW
852
+ UFUNC_MASK_INVALID
853
+ UFUNC_SHIFT_DIVIDEBYZERO
854
+ UFUNC_SHIFT_OVERFLOW
855
+ UFUNC_SHIFT_UNDERFLOW
856
+ UFUNC_SHIFT_INVALID
857
+ UFUNC_FPE_DIVIDEBYZERO
858
+ UFUNC_FPE_OVERFLOW
859
+ UFUNC_FPE_UNDERFLOW
860
+ UFUNC_FPE_INVALID
861
+ UFUNC_ERR_DEFAULT
862
+ UFUNC_ERR_DEFAULT2
863
+
864
+ object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
865
+ void **, char *, int, int, int, int, char *, char *, int)
866
+ int PyUFunc_RegisterLoopForType(ufunc, int,
867
+ PyUFuncGenericFunction, int *, void *) except -1
868
+ void PyUFunc_f_f_As_d_d \
869
+ (char **, npy_intp *, npy_intp *, void *)
870
+ void PyUFunc_d_d \
871
+ (char **, npy_intp *, npy_intp *, void *)
872
+ void PyUFunc_f_f \
873
+ (char **, npy_intp *, npy_intp *, void *)
874
+ void PyUFunc_g_g \
875
+ (char **, npy_intp *, npy_intp *, void *)
876
+ void PyUFunc_F_F_As_D_D \
877
+ (char **, npy_intp *, npy_intp *, void *)
878
+ void PyUFunc_F_F \
879
+ (char **, npy_intp *, npy_intp *, void *)
880
+ void PyUFunc_D_D \
881
+ (char **, npy_intp *, npy_intp *, void *)
882
+ void PyUFunc_G_G \
883
+ (char **, npy_intp *, npy_intp *, void *)
884
+ void PyUFunc_O_O \
885
+ (char **, npy_intp *, npy_intp *, void *)
886
+ void PyUFunc_ff_f_As_dd_d \
887
+ (char **, npy_intp *, npy_intp *, void *)
888
+ void PyUFunc_ff_f \
889
+ (char **, npy_intp *, npy_intp *, void *)
890
+ void PyUFunc_dd_d \
891
+ (char **, npy_intp *, npy_intp *, void *)
892
+ void PyUFunc_gg_g \
893
+ (char **, npy_intp *, npy_intp *, void *)
894
+ void PyUFunc_FF_F_As_DD_D \
895
+ (char **, npy_intp *, npy_intp *, void *)
896
+ void PyUFunc_DD_D \
897
+ (char **, npy_intp *, npy_intp *, void *)
898
+ void PyUFunc_FF_F \
899
+ (char **, npy_intp *, npy_intp *, void *)
900
+ void PyUFunc_GG_G \
901
+ (char **, npy_intp *, npy_intp *, void *)
902
+ void PyUFunc_OO_O \
903
+ (char **, npy_intp *, npy_intp *, void *)
904
+ void PyUFunc_O_O_method \
905
+ (char **, npy_intp *, npy_intp *, void *)
906
+ void PyUFunc_OO_O_method \
907
+ (char **, npy_intp *, npy_intp *, void *)
908
+ void PyUFunc_On_Om \
909
+ (char **, npy_intp *, npy_intp *, void *)
910
+ int PyUFunc_GetPyValues \
911
+ (char *, int *, int *, PyObject **)
912
+ int PyUFunc_checkfperr \
913
+ (int, PyObject *, int *)
914
+ void PyUFunc_clearfperr()
915
+ int PyUFunc_getfperr()
916
+ int PyUFunc_handlefperr \
917
+ (int, PyObject *, int, int *) except -1
918
+ int PyUFunc_ReplaceLoopBySignature \
919
+ (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
920
+ object PyUFunc_FromFuncAndDataAndSignature \
921
+ (PyUFuncGenericFunction *, void **, char *, int, int, int,
922
+ int, char *, char *, int, char *)
923
+
924
+ int _import_umath() except -1
925
+
926
+ cdef inline void set_array_base(ndarray arr, object base):
927
+ Py_INCREF(base) # important to do this before stealing the reference below!
928
+ PyArray_SetBaseObject(arr, base)
929
+
930
+ cdef inline object get_array_base(ndarray arr):
931
+ base = PyArray_BASE(arr)
932
+ if base is NULL:
933
+ return None
934
+ return <object>base
935
+
936
+ # Versions of the import_* functions which are more suitable for
937
+ # Cython code.
938
+ cdef inline int import_array() except -1:
939
+ try:
940
+ __pyx_import_array()
941
+ except Exception:
942
+ raise ImportError("numpy.core.multiarray failed to import")
943
+
944
+ cdef inline int import_umath() except -1:
945
+ try:
946
+ _import_umath()
947
+ except Exception:
948
+ raise ImportError("numpy.core.umath failed to import")
949
+
950
+ cdef inline int import_ufunc() except -1:
951
+ try:
952
+ _import_umath()
953
+ except Exception:
954
+ raise ImportError("numpy.core.umath failed to import")
955
+
956
+ cdef extern from *:
957
+ # Leave a marker that the NumPy declarations came from this file
958
+ # See https://github.com/cython/cython/issues/3573
959
+ """
960
+ /* NumPy API declarations from "numpy/__init__.pxd" */
961
+ """
962
+
963
+
964
+ cdef inline bint is_timedelta64_object(object obj):
965
+ """
966
+ Cython equivalent of `isinstance(obj, np.timedelta64)`
967
+
968
+ Parameters
969
+ ----------
970
+ obj : object
971
+
972
+ Returns
973
+ -------
974
+ bool
975
+ """
976
+ return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
977
+
978
+
979
+ cdef inline bint is_datetime64_object(object obj):
980
+ """
981
+ Cython equivalent of `isinstance(obj, np.datetime64)`
982
+
983
+ Parameters
984
+ ----------
985
+ obj : object
986
+
987
+ Returns
988
+ -------
989
+ bool
990
+ """
991
+ return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
992
+
993
+
994
+ cdef inline npy_datetime get_datetime64_value(object obj) nogil:
995
+ """
996
+ returns the int64 value underlying scalar numpy datetime64 object
997
+
998
+ Note that to interpret this as a datetime, the corresponding unit is
999
+ also needed. That can be found using `get_datetime64_unit`.
1000
+ """
1001
+ return (<PyDatetimeScalarObject*>obj).obval
1002
+
1003
+
1004
+ cdef inline npy_timedelta get_timedelta64_value(object obj) nogil:
1005
+ """
1006
+ returns the int64 value underlying scalar numpy timedelta64 object
1007
+ """
1008
+ return (<PyTimedeltaScalarObject*>obj).obval
1009
+
1010
+
1011
+ cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil:
1012
+ """
1013
+ returns the unit part of the dtype for a numpy datetime64 object.
1014
+ """
1015
+ return <NPY_DATETIMEUNIT>(<PyDatetimeScalarObject*>obj).obmeta.base
llmeval-env/lib/python3.10/site-packages/numpy/__init__.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NumPy
3
+ =====
4
+
5
+ Provides
6
+ 1. An array object of arbitrary homogeneous items
7
+ 2. Fast mathematical operations over arrays
8
+ 3. Linear Algebra, Fourier Transforms, Random Number Generation
9
+
10
+ How to use the documentation
11
+ ----------------------------
12
+ Documentation is available in two forms: docstrings provided
13
+ with the code, and a loose standing reference guide, available from
14
+ `the NumPy homepage <https://numpy.org>`_.
15
+
16
+ We recommend exploring the docstrings using
17
+ `IPython <https://ipython.org>`_, an advanced Python shell with
18
+ TAB-completion and introspection capabilities. See below for further
19
+ instructions.
20
+
21
+ The docstring examples assume that `numpy` has been imported as ``np``::
22
+
23
+ >>> import numpy as np
24
+
25
+ Code snippets are indicated by three greater-than signs::
26
+
27
+ >>> x = 42
28
+ >>> x = x + 1
29
+
30
+ Use the built-in ``help`` function to view a function's docstring::
31
+
32
+ >>> help(np.sort)
33
+ ... # doctest: +SKIP
34
+
35
+ For some objects, ``np.info(obj)`` may provide additional help. This is
36
+ particularly true if you see the line "Help on ufunc object:" at the top
37
+ of the help() page. Ufuncs are implemented in C, not Python, for speed.
38
+ The native Python help() does not know how to view their help, but our
39
+ np.info() function does.
40
+
41
+ To search for documents containing a keyword, do::
42
+
43
+ >>> np.lookfor('keyword')
44
+ ... # doctest: +SKIP
45
+
46
+ General-purpose documents like a glossary and help on the basic concepts
47
+ of numpy are available under the ``doc`` sub-module::
48
+
49
+ >>> from numpy import doc
50
+ >>> help(doc)
51
+ ... # doctest: +SKIP
52
+
53
+ Available subpackages
54
+ ---------------------
55
+ lib
56
+ Basic functions used by several sub-packages.
57
+ random
58
+ Core Random Tools
59
+ linalg
60
+ Core Linear Algebra Tools
61
+ fft
62
+ Core FFT routines
63
+ polynomial
64
+ Polynomial tools
65
+ testing
66
+ NumPy testing tools
67
+ distutils
68
+ Enhancements to distutils with support for
69
+ Fortran compilers support and more (for Python <= 3.11).
70
+
71
+ Utilities
72
+ ---------
73
+ test
74
+ Run numpy unittests
75
+ show_config
76
+ Show numpy build configuration
77
+ matlib
78
+ Make everything matrices.
79
+ __version__
80
+ NumPy version string
81
+
82
+ Viewing documentation using IPython
83
+ -----------------------------------
84
+
85
+ Start IPython and import `numpy` usually under the alias ``np``: `import
86
+ numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
87
+ examples into the shell. To see which functions are available in `numpy`,
88
+ type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
89
+ ``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
90
+ down the list. To view the docstring for a function, use
91
+ ``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
92
+ the source code).
93
+
94
+ Copies vs. in-place operation
95
+ -----------------------------
96
+ Most of the functions in `numpy` return a copy of the array argument
97
+ (e.g., `np.sort`). In-place versions of these functions are often
98
+ available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
99
+ Exceptions to this rule are documented.
100
+
101
+ """
102
+ import sys
103
+ import warnings
104
+
105
+ from ._globals import _NoValue, _CopyMode
106
+ # These exceptions were moved in 1.25 and are hidden from __dir__()
107
+ from .exceptions import (
108
+ ComplexWarning, ModuleDeprecationWarning, VisibleDeprecationWarning,
109
+ TooHardError, AxisError)
110
+
111
+
112
+ # If a version with git hash was stored, use that instead
113
+ from . import version
114
+ from .version import __version__
115
+
116
+ # We first need to detect if we're being called as part of the numpy setup
117
+ # procedure itself in a reliable manner.
118
+ try:
119
+ __NUMPY_SETUP__
120
+ except NameError:
121
+ __NUMPY_SETUP__ = False
122
+
123
+ if __NUMPY_SETUP__:
124
+ sys.stderr.write('Running from numpy source directory.\n')
125
+ else:
126
+ # Allow distributors to run custom init code before importing numpy.core
127
+ from . import _distributor_init
128
+
129
+ try:
130
+ from numpy.__config__ import show as show_config
131
+ except ImportError as e:
132
+ msg = """Error importing numpy: you should not try to import numpy from
133
+ its source directory; please exit the numpy source tree, and relaunch
134
+ your python interpreter from there."""
135
+ raise ImportError(msg) from e
136
+
137
+ __all__ = [
138
+ 'exceptions', 'ModuleDeprecationWarning', 'VisibleDeprecationWarning',
139
+ 'ComplexWarning', 'TooHardError', 'AxisError']
140
+
141
+ # mapping of {name: (value, deprecation_msg)}
142
+ __deprecated_attrs__ = {}
143
+
144
+ from . import core
145
+ from .core import *
146
+ from . import compat
147
+ from . import exceptions
148
+ from . import dtypes
149
+ from . import lib
150
+ # NOTE: to be revisited following future namespace cleanup.
151
+ # See gh-14454 and gh-15672 for discussion.
152
+ from .lib import *
153
+
154
+ from . import linalg
155
+ from . import fft
156
+ from . import polynomial
157
+ from . import random
158
+ from . import ctypeslib
159
+ from . import ma
160
+ from . import matrixlib as _mat
161
+ from .matrixlib import *
162
+
163
+ # Deprecations introduced in NumPy 1.20.0, 2020-06-06
164
+ import builtins as _builtins
165
+
166
+ _msg = (
167
+ "module 'numpy' has no attribute '{n}'.\n"
168
+ "`np.{n}` was a deprecated alias for the builtin `{n}`. "
169
+ "To avoid this error in existing code, use `{n}` by itself. "
170
+ "Doing this will not modify any behavior and is safe. {extended_msg}\n"
171
+ "The aliases was originally deprecated in NumPy 1.20; for more "
172
+ "details and guidance see the original release note at:\n"
173
+ " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
174
+
175
+ _specific_msg = (
176
+ "If you specifically wanted the numpy scalar type, use `np.{}` here.")
177
+
178
+ _int_extended_msg = (
179
+ "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
180
+ "or `np.int32` to specify the precision. If you wish to review "
181
+ "your current use, check the release note link for "
182
+ "additional information.")
183
+
184
+ _type_info = [
185
+ ("object", ""), # The NumPy scalar only exists by name.
186
+ ("bool", _specific_msg.format("bool_")),
187
+ ("float", _specific_msg.format("float64")),
188
+ ("complex", _specific_msg.format("complex128")),
189
+ ("str", _specific_msg.format("str_")),
190
+ ("int", _int_extended_msg.format("int"))]
191
+
192
+ __former_attrs__ = {
193
+ n: _msg.format(n=n, extended_msg=extended_msg)
194
+ for n, extended_msg in _type_info
195
+ }
196
+
197
+ # Future warning introduced in NumPy 1.24.0, 2022-11-17
198
+ _msg = (
199
+ "`np.{n}` is a deprecated alias for `{an}`. (Deprecated NumPy 1.24)")
200
+
201
+ # Some of these are awkward (since `np.str` may be preferable in the long
202
+ # term), but overall the names ending in 0 seem undesirable
203
+ _type_info = [
204
+ ("bool8", bool_, "np.bool_"),
205
+ ("int0", intp, "np.intp"),
206
+ ("uint0", uintp, "np.uintp"),
207
+ ("str0", str_, "np.str_"),
208
+ ("bytes0", bytes_, "np.bytes_"),
209
+ ("void0", void, "np.void"),
210
+ ("object0", object_,
211
+ "`np.object0` is a deprecated alias for `np.object_`. "
212
+ "`object` can be used instead. (Deprecated NumPy 1.24)")]
213
+
214
+ # Some of these could be defined right away, but most were aliases to
215
+ # the Python objects and only removed in NumPy 1.24. Defining them should
216
+ # probably wait for NumPy 1.26 or 2.0.
217
+ # When defined, these should possibly not be added to `__all__` to avoid
218
+ # import with `from numpy import *`.
219
+ __future_scalars__ = {"bool", "long", "ulong", "str", "bytes", "object"}
220
+
221
+ __deprecated_attrs__.update({
222
+ n: (alias, _msg.format(n=n, an=an)) for n, alias, an in _type_info})
223
+
224
+ import math
225
+
226
+ __deprecated_attrs__['math'] = (math,
227
+ "`np.math` is a deprecated alias for the standard library `math` "
228
+ "module (Deprecated Numpy 1.25). Replace usages of `np.math` with "
229
+ "`math`")
230
+
231
+ del math, _msg, _type_info
232
+
233
+ from .core import abs
234
+ # now that numpy modules are imported, can initialize limits
235
+ core.getlimits._register_known_types()
236
+
237
+ __all__.extend(['__version__', 'show_config'])
238
+ __all__.extend(core.__all__)
239
+ __all__.extend(_mat.__all__)
240
+ __all__.extend(lib.__all__)
241
+ __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
242
+
243
+ # Remove min and max from __all__ to avoid `from numpy import *` override
244
+ # the builtins min/max. Temporary fix for 1.25.x/1.26.x, see gh-24229.
245
+ __all__.remove('min')
246
+ __all__.remove('max')
247
+ __all__.remove('round')
248
+
249
+ # Remove one of the two occurrences of `issubdtype`, which is exposed as
250
+ # both `numpy.core.issubdtype` and `numpy.lib.issubdtype`.
251
+ __all__.remove('issubdtype')
252
+
253
+ # These are exported by np.core, but are replaced by the builtins below
254
+ # remove them to ensure that we don't end up with `np.long == np.int_`,
255
+ # which would be a breaking change.
256
+ del long, unicode
257
+ __all__.remove('long')
258
+ __all__.remove('unicode')
259
+
260
+ # Remove things that are in the numpy.lib but not in the numpy namespace
261
+ # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
262
+ # that prevents adding more things to the main namespace by accident.
263
+ # The list below will grow until the `from .lib import *` fixme above is
264
+ # taken care of
265
+ __all__.remove('Arrayterator')
266
+ del Arrayterator
267
+
268
+ # These names were removed in NumPy 1.20. For at least one release,
269
+ # attempts to access these names in the numpy namespace will trigger
270
+ # a warning, and calling the function will raise an exception.
271
+ _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',
272
+ 'ppmt', 'pv', 'rate']
273
+ __expired_functions__ = {
274
+ name: (f'In accordance with NEP 32, the function {name} was removed '
275
+ 'from NumPy version 1.20. A replacement for this function '
276
+ 'is available in the numpy_financial library: '
277
+ 'https://pypi.org/project/numpy-financial')
278
+ for name in _financial_names}
279
+
280
+ # Filter out Cython harmless warnings
281
+ warnings.filterwarnings("ignore", message="numpy.dtype size changed")
282
+ warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
283
+ warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
284
+
285
+ # oldnumeric and numarray were removed in 1.9. In case some packages import
286
+ # but do not use them, we define them here for backward compatibility.
287
+ oldnumeric = 'removed'
288
+ numarray = 'removed'
289
+
290
+ def __getattr__(attr):
291
+ # Warn for expired attributes, and return a dummy function
292
+ # that always raises an exception.
293
+ import warnings
294
+ import math
295
+ try:
296
+ msg = __expired_functions__[attr]
297
+ except KeyError:
298
+ pass
299
+ else:
300
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
301
+
302
+ def _expired(*args, **kwds):
303
+ raise RuntimeError(msg)
304
+
305
+ return _expired
306
+
307
+ # Emit warnings for deprecated attributes
308
+ try:
309
+ val, msg = __deprecated_attrs__[attr]
310
+ except KeyError:
311
+ pass
312
+ else:
313
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
314
+ return val
315
+
316
+ if attr in __future_scalars__:
317
+ # And future warnings for those that will change, but also give
318
+ # the AttributeError
319
+ warnings.warn(
320
+ f"In the future `np.{attr}` will be defined as the "
321
+ "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
322
+
323
+ if attr in __former_attrs__:
324
+ raise AttributeError(__former_attrs__[attr])
325
+
326
+ if attr == 'testing':
327
+ import numpy.testing as testing
328
+ return testing
329
+ elif attr == 'Tester':
330
+ "Removed in NumPy 1.25.0"
331
+ raise RuntimeError("Tester was removed in NumPy 1.25.")
332
+
333
+ raise AttributeError("module {!r} has no attribute "
334
+ "{!r}".format(__name__, attr))
335
+
336
+ def __dir__():
337
+ public_symbols = globals().keys() | {'testing'}
338
+ public_symbols -= {
339
+ "core", "matrixlib",
340
+ # These were moved in 1.25 and may be deprecated eventually:
341
+ "ModuleDeprecationWarning", "VisibleDeprecationWarning",
342
+ "ComplexWarning", "TooHardError", "AxisError"
343
+ }
344
+ return list(public_symbols)
345
+
346
+ # Pytest testing
347
+ from numpy._pytesttester import PytestTester
348
+ test = PytestTester(__name__)
349
+ del PytestTester
350
+
351
+ def _sanity_check():
352
+ """
353
+ Quick sanity checks for common bugs caused by environment.
354
+ There are some cases e.g. with wrong BLAS ABI that cause wrong
355
+ results under specific runtime conditions that are not necessarily
356
+ achieved during test suite runs, and it is useful to catch those early.
357
+
358
+ See https://github.com/numpy/numpy/issues/8577 and other
359
+ similar bug reports.
360
+
361
+ """
362
+ try:
363
+ x = ones(2, dtype=float32)
364
+ if not abs(x.dot(x) - float32(2.0)) < 1e-5:
365
+ raise AssertionError()
366
+ except AssertionError:
367
+ msg = ("The current Numpy installation ({!r}) fails to "
368
+ "pass simple sanity checks. This can be caused for example "
369
+ "by incorrect BLAS library being linked in, or by mixing "
370
+ "package managers (pip, conda, apt, ...). Search closed "
371
+ "numpy issues for similar problems.")
372
+ raise RuntimeError(msg.format(__file__)) from None
373
+
374
+ _sanity_check()
375
+ del _sanity_check
376
+
377
+ def _mac_os_check():
378
+ """
379
+ Quick Sanity check for Mac OS look for accelerate build bugs.
380
+ Testing numpy polyfit calls init_dgelsd(LAPACK)
381
+ """
382
+ try:
383
+ c = array([3., 2., 1.])
384
+ x = linspace(0, 2, 5)
385
+ y = polyval(c, x)
386
+ _ = polyfit(x, y, 2, cov=True)
387
+ except ValueError:
388
+ pass
389
+
390
+ if sys.platform == "darwin":
391
+ from . import exceptions
392
+ with warnings.catch_warnings(record=True) as w:
393
+ _mac_os_check()
394
+ # Throw runtime error, if the test failed Check for warning and error_message
395
+ if len(w) > 0:
396
+ for _wn in w:
397
+ if _wn.category is exceptions.RankWarning:
398
+ # Ignore other warnings, they may not be relevant (see gh-25433).
399
+ error_message = f"{_wn.category.__name__}: {str(_wn.message)}"
400
+ msg = (
401
+ "Polyfit sanity test emitted a warning, most likely due "
402
+ "to using a buggy Accelerate backend."
403
+ "\nIf you compiled yourself, more information is available at:"
404
+ "\nhttps://numpy.org/devdocs/building/index.html"
405
+ "\nOtherwise report this to the vendor "
406
+ "that provided NumPy.\n\n{}\n".format(error_message))
407
+ raise RuntimeError(msg)
408
+ del _wn
409
+ del w
410
+ del _mac_os_check
411
+
412
+ # We usually use madvise hugepages support, but on some old kernels it
413
+ # is slow and thus better avoided.
414
+ # Specifically kernel version 4.6 had a bug fix which probably fixed this:
415
+ # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
416
+ import os
417
+ use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
418
+ if sys.platform == "linux" and use_hugepage is None:
419
+ # If there is an issue with parsing the kernel version,
420
+ # set use_hugepages to 0. Usage of LooseVersion will handle
421
+ # the kernel version parsing better, but avoided since it
422
+ # will increase the import time. See: #16679 for related discussion.
423
+ try:
424
+ use_hugepage = 1
425
+ kernel_version = os.uname().release.split(".")[:2]
426
+ kernel_version = tuple(int(v) for v in kernel_version)
427
+ if kernel_version < (4, 6):
428
+ use_hugepage = 0
429
+ except ValueError:
430
+ use_hugepages = 0
431
+ elif use_hugepage is None:
432
+ # This is not Linux, so it should not matter, just enable anyway
433
+ use_hugepage = 1
434
+ else:
435
+ use_hugepage = int(use_hugepage)
436
+
437
+ # Note that this will currently only make a difference on Linux
438
+ core.multiarray._set_madvise_hugepage(use_hugepage)
439
+ del use_hugepage
440
+
441
+ # Give a warning if NumPy is reloaded or imported on a sub-interpreter
442
+ # We do this from python, since the C-module may not be reloaded and
443
+ # it is tidier organized.
444
+ core.multiarray._multiarray_umath._reload_guard()
445
+
446
+ # default to "weak" promotion for "NumPy 2".
447
+ core._set_promotion_state(
448
+ os.environ.get("NPY_PROMOTION_STATE",
449
+ "weak" if _using_numpy2_behavior() else "legacy"))
450
+
451
+ # Tell PyInstaller where to find hook-numpy.py
452
+ def _pyinstaller_hooks_dir():
453
+ from pathlib import Path
454
+ return [str(Path(__file__).with_name("_pyinstaller").resolve())]
455
+
456
+ # Remove symbols imported for internal use
457
+ del os
458
+
459
+
460
+ # Remove symbols imported for internal use
461
+ del sys, warnings
llmeval-env/lib/python3.10/site-packages/numpy/__init__.pyi ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/numpy/_globals.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module defining global singleton classes.
3
+
4
+ This module raises a RuntimeError if an attempt to reload it is made. In that
5
+ way the identities of the classes defined here are fixed and will remain so
6
+ even if numpy itself is reloaded. In particular, a function like the following
7
+ will still work correctly after numpy is reloaded::
8
+
9
+ def foo(arg=np._NoValue):
10
+ if arg is np._NoValue:
11
+ ...
12
+
13
+ That was not the case when the singleton classes were defined in the numpy
14
+ ``__init__.py`` file. See gh-7844 for a discussion of the reload problem that
15
+ motivated this module.
16
+
17
+ """
18
+ import enum
19
+
20
+ from ._utils import set_module as _set_module
21
+
22
+ __all__ = ['_NoValue', '_CopyMode']
23
+
24
+
25
+ # Disallow reloading this module so as to preserve the identities of the
26
+ # classes defined here.
27
+ if '_is_loaded' in globals():
28
+ raise RuntimeError('Reloading numpy._globals is not allowed')
29
+ _is_loaded = True
30
+
31
+
32
+ class _NoValueType:
33
+ """Special keyword value.
34
+
35
+ The instance of this class may be used as the default value assigned to a
36
+ keyword if no other obvious default (e.g., `None`) is suitable,
37
+
38
+ Common reasons for using this keyword are:
39
+
40
+ - A new keyword is added to a function, and that function forwards its
41
+ inputs to another function or method which can be defined outside of
42
+ NumPy. For example, ``np.std(x)`` calls ``x.std``, so when a ``keepdims``
43
+ keyword was added that could only be forwarded if the user explicitly
44
+ specified ``keepdims``; downstream array libraries may not have added
45
+ the same keyword, so adding ``x.std(..., keepdims=keepdims)``
46
+ unconditionally could have broken previously working code.
47
+ - A keyword is being deprecated, and a deprecation warning must only be
48
+ emitted when the keyword is used.
49
+
50
+ """
51
+ __instance = None
52
+ def __new__(cls):
53
+ # ensure that only one instance exists
54
+ if not cls.__instance:
55
+ cls.__instance = super().__new__(cls)
56
+ return cls.__instance
57
+
58
+ def __repr__(self):
59
+ return "<no value>"
60
+
61
+
62
+ _NoValue = _NoValueType()
63
+
64
+
65
+ @_set_module("numpy")
66
+ class _CopyMode(enum.Enum):
67
+ """
68
+ An enumeration for the copy modes supported
69
+ by numpy.copy() and numpy.array(). The following three modes are supported,
70
+
71
+ - ALWAYS: This means that a deep copy of the input
72
+ array will always be taken.
73
+ - IF_NEEDED: This means that a deep copy of the input
74
+ array will be taken only if necessary.
75
+ - NEVER: This means that the deep copy will never be taken.
76
+ If a copy cannot be avoided then a `ValueError` will be
77
+ raised.
78
+
79
+ Note that the buffer-protocol could in theory do copies. NumPy currently
80
+ assumes an object exporting the buffer protocol will never do this.
81
+ """
82
+
83
+ ALWAYS = True
84
+ IF_NEEDED = False
85
+ NEVER = 2
86
+
87
+ def __bool__(self):
88
+ # For backwards compatibility
89
+ if self == _CopyMode.ALWAYS:
90
+ return True
91
+
92
+ if self == _CopyMode.IF_NEEDED:
93
+ return False
94
+
95
+ raise ValueError(f"{self} is neither True nor False.")
llmeval-env/lib/python3.10/site-packages/numpy/_pytesttester.pyi ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import Literal as L
3
+
4
+ __all__: list[str]
5
+
6
+ class PytestTester:
7
+ module_name: str
8
+ def __init__(self, module_name: str) -> None: ...
9
+ def __call__(
10
+ self,
11
+ label: L["fast", "full"] = ...,
12
+ verbose: int = ...,
13
+ extra_argv: None | Iterable[str] = ...,
14
+ doctests: L[False] = ...,
15
+ coverage: bool = ...,
16
+ durations: int = ...,
17
+ tests: None | Iterable[str] = ...,
18
+ ) -> bool: ...
llmeval-env/lib/python3.10/site-packages/numpy/ctypeslib.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ============================
3
+ ``ctypes`` Utility Functions
4
+ ============================
5
+
6
+ See Also
7
+ --------
8
+ load_library : Load a C library.
9
+ ndpointer : Array restype/argtype with verification.
10
+ as_ctypes : Create a ctypes array from an ndarray.
11
+ as_array : Create an ndarray from a ctypes array.
12
+
13
+ References
14
+ ----------
15
+ .. [1] "SciPy Cookbook: ctypes", https://scipy-cookbook.readthedocs.io/items/Ctypes.html
16
+
17
+ Examples
18
+ --------
19
+ Load the C library:
20
+
21
+ >>> _lib = np.ctypeslib.load_library('libmystuff', '.') #doctest: +SKIP
22
+
23
+ Our result type, an ndarray that must be of type double, be 1-dimensional
24
+ and is C-contiguous in memory:
25
+
26
+ >>> array_1d_double = np.ctypeslib.ndpointer(
27
+ ... dtype=np.double,
28
+ ... ndim=1, flags='CONTIGUOUS') #doctest: +SKIP
29
+
30
+ Our C-function typically takes an array and updates its values
31
+ in-place. For example::
32
+
33
+ void foo_func(double* x, int length)
34
+ {
35
+ int i;
36
+ for (i = 0; i < length; i++) {
37
+ x[i] = i*i;
38
+ }
39
+ }
40
+
41
+ We wrap it using:
42
+
43
+ >>> _lib.foo_func.restype = None #doctest: +SKIP
44
+ >>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP
45
+
46
+ Then, we're ready to call ``foo_func``:
47
+
48
+ >>> out = np.empty(15, dtype=np.double)
49
+ >>> _lib.foo_func(out, len(out)) #doctest: +SKIP
50
+
51
+ """
52
+ __all__ = ['load_library', 'ndpointer', 'c_intp', 'as_ctypes', 'as_array',
53
+ 'as_ctypes_type']
54
+
55
+ import os
56
+ from numpy import (
57
+ integer, ndarray, dtype as _dtype, asarray, frombuffer
58
+ )
59
+ from numpy.core.multiarray import _flagdict, flagsobj
60
+
61
+ try:
62
+ import ctypes
63
+ except ImportError:
64
+ ctypes = None
65
+
66
+ if ctypes is None:
67
+ def _dummy(*args, **kwds):
68
+ """
69
+ Dummy object that raises an ImportError if ctypes is not available.
70
+
71
+ Raises
72
+ ------
73
+ ImportError
74
+ If ctypes is not available.
75
+
76
+ """
77
+ raise ImportError("ctypes is not available.")
78
+ load_library = _dummy
79
+ as_ctypes = _dummy
80
+ as_array = _dummy
81
+ from numpy import intp as c_intp
82
+ _ndptr_base = object
83
+ else:
84
+ import numpy.core._internal as nic
85
+ c_intp = nic._getintp_ctype()
86
+ del nic
87
+ _ndptr_base = ctypes.c_void_p
88
+
89
+ # Adapted from Albert Strasheim
90
+ def load_library(libname, loader_path):
91
+ """
92
+ It is possible to load a library using
93
+
94
+ >>> lib = ctypes.cdll[<full_path_name>] # doctest: +SKIP
95
+
96
+ But there are cross-platform considerations, such as library file extensions,
97
+ plus the fact Windows will just load the first library it finds with that name.
98
+ NumPy supplies the load_library function as a convenience.
99
+
100
+ .. versionchanged:: 1.20.0
101
+ Allow libname and loader_path to take any
102
+ :term:`python:path-like object`.
103
+
104
+ Parameters
105
+ ----------
106
+ libname : path-like
107
+ Name of the library, which can have 'lib' as a prefix,
108
+ but without an extension.
109
+ loader_path : path-like
110
+ Where the library can be found.
111
+
112
+ Returns
113
+ -------
114
+ ctypes.cdll[libpath] : library object
115
+ A ctypes library object
116
+
117
+ Raises
118
+ ------
119
+ OSError
120
+ If there is no library with the expected extension, or the
121
+ library is defective and cannot be loaded.
122
+ """
123
+ # Convert path-like objects into strings
124
+ libname = os.fsdecode(libname)
125
+ loader_path = os.fsdecode(loader_path)
126
+
127
+ ext = os.path.splitext(libname)[1]
128
+ if not ext:
129
+ import sys
130
+ import sysconfig
131
+ # Try to load library with platform-specific name, otherwise
132
+ # default to libname.[so|dll|dylib]. Sometimes, these files are
133
+ # built erroneously on non-linux platforms.
134
+ base_ext = ".so"
135
+ if sys.platform.startswith("darwin"):
136
+ base_ext = ".dylib"
137
+ elif sys.platform.startswith("win"):
138
+ base_ext = ".dll"
139
+ libname_ext = [libname + base_ext]
140
+ so_ext = sysconfig.get_config_var("EXT_SUFFIX")
141
+ if not so_ext == base_ext:
142
+ libname_ext.insert(0, libname + so_ext)
143
+ else:
144
+ libname_ext = [libname]
145
+
146
+ loader_path = os.path.abspath(loader_path)
147
+ if not os.path.isdir(loader_path):
148
+ libdir = os.path.dirname(loader_path)
149
+ else:
150
+ libdir = loader_path
151
+
152
+ for ln in libname_ext:
153
+ libpath = os.path.join(libdir, ln)
154
+ if os.path.exists(libpath):
155
+ try:
156
+ return ctypes.cdll[libpath]
157
+ except OSError:
158
+ ## defective lib file
159
+ raise
160
+ ## if no successful return in the libname_ext loop:
161
+ raise OSError("no file with expected extension")
162
+
163
+
164
+ def _num_fromflags(flaglist):
165
+ num = 0
166
+ for val in flaglist:
167
+ num += _flagdict[val]
168
+ return num
169
+
170
+ _flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE',
171
+ 'OWNDATA', 'WRITEBACKIFCOPY']
172
+ def _flags_fromnum(num):
173
+ res = []
174
+ for key in _flagnames:
175
+ value = _flagdict[key]
176
+ if (num & value):
177
+ res.append(key)
178
+ return res
179
+
180
+
181
+ class _ndptr(_ndptr_base):
182
+ @classmethod
183
+ def from_param(cls, obj):
184
+ if not isinstance(obj, ndarray):
185
+ raise TypeError("argument must be an ndarray")
186
+ if cls._dtype_ is not None \
187
+ and obj.dtype != cls._dtype_:
188
+ raise TypeError("array must have data type %s" % cls._dtype_)
189
+ if cls._ndim_ is not None \
190
+ and obj.ndim != cls._ndim_:
191
+ raise TypeError("array must have %d dimension(s)" % cls._ndim_)
192
+ if cls._shape_ is not None \
193
+ and obj.shape != cls._shape_:
194
+ raise TypeError("array must have shape %s" % str(cls._shape_))
195
+ if cls._flags_ is not None \
196
+ and ((obj.flags.num & cls._flags_) != cls._flags_):
197
+ raise TypeError("array must have flags %s" %
198
+ _flags_fromnum(cls._flags_))
199
+ return obj.ctypes
200
+
201
+
202
+ class _concrete_ndptr(_ndptr):
203
+ """
204
+ Like _ndptr, but with `_shape_` and `_dtype_` specified.
205
+
206
+ Notably, this means the pointer has enough information to reconstruct
207
+ the array, which is not generally true.
208
+ """
209
+ def _check_retval_(self):
210
+ """
211
+ This method is called when this class is used as the .restype
212
+ attribute for a shared-library function, to automatically wrap the
213
+ pointer into an array.
214
+ """
215
+ return self.contents
216
+
217
+ @property
218
+ def contents(self):
219
+ """
220
+ Get an ndarray viewing the data pointed to by this pointer.
221
+
222
+ This mirrors the `contents` attribute of a normal ctypes pointer
223
+ """
224
+ full_dtype = _dtype((self._dtype_, self._shape_))
225
+ full_ctype = ctypes.c_char * full_dtype.itemsize
226
+ buffer = ctypes.cast(self, ctypes.POINTER(full_ctype)).contents
227
+ return frombuffer(buffer, dtype=full_dtype).squeeze(axis=0)
228
+
229
+
230
+ # Factory for an array-checking class with from_param defined for
231
+ # use with ctypes argtypes mechanism
232
+ _pointer_type_cache = {}
233
+ def ndpointer(dtype=None, ndim=None, shape=None, flags=None):
234
+ """
235
+ Array-checking restype/argtypes.
236
+
237
+ An ndpointer instance is used to describe an ndarray in restypes
238
+ and argtypes specifications. This approach is more flexible than
239
+ using, for example, ``POINTER(c_double)``, since several restrictions
240
+ can be specified, which are verified upon calling the ctypes function.
241
+ These include data type, number of dimensions, shape and flags. If a
242
+ given array does not satisfy the specified restrictions,
243
+ a ``TypeError`` is raised.
244
+
245
+ Parameters
246
+ ----------
247
+ dtype : data-type, optional
248
+ Array data-type.
249
+ ndim : int, optional
250
+ Number of array dimensions.
251
+ shape : tuple of ints, optional
252
+ Array shape.
253
+ flags : str or tuple of str
254
+ Array flags; may be one or more of:
255
+
256
+ - C_CONTIGUOUS / C / CONTIGUOUS
257
+ - F_CONTIGUOUS / F / FORTRAN
258
+ - OWNDATA / O
259
+ - WRITEABLE / W
260
+ - ALIGNED / A
261
+ - WRITEBACKIFCOPY / X
262
+
263
+ Returns
264
+ -------
265
+ klass : ndpointer type object
266
+ A type object, which is an ``_ndtpr`` instance containing
267
+ dtype, ndim, shape and flags information.
268
+
269
+ Raises
270
+ ------
271
+ TypeError
272
+ If a given array does not satisfy the specified restrictions.
273
+
274
+ Examples
275
+ --------
276
+ >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,
277
+ ... ndim=1,
278
+ ... flags='C_CONTIGUOUS')]
279
+ ... #doctest: +SKIP
280
+ >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64))
281
+ ... #doctest: +SKIP
282
+
283
+ """
284
+
285
+ # normalize dtype to an Optional[dtype]
286
+ if dtype is not None:
287
+ dtype = _dtype(dtype)
288
+
289
+ # normalize flags to an Optional[int]
290
+ num = None
291
+ if flags is not None:
292
+ if isinstance(flags, str):
293
+ flags = flags.split(',')
294
+ elif isinstance(flags, (int, integer)):
295
+ num = flags
296
+ flags = _flags_fromnum(num)
297
+ elif isinstance(flags, flagsobj):
298
+ num = flags.num
299
+ flags = _flags_fromnum(num)
300
+ if num is None:
301
+ try:
302
+ flags = [x.strip().upper() for x in flags]
303
+ except Exception as e:
304
+ raise TypeError("invalid flags specification") from e
305
+ num = _num_fromflags(flags)
306
+
307
+ # normalize shape to an Optional[tuple]
308
+ if shape is not None:
309
+ try:
310
+ shape = tuple(shape)
311
+ except TypeError:
312
+ # single integer -> 1-tuple
313
+ shape = (shape,)
314
+
315
+ cache_key = (dtype, ndim, shape, num)
316
+
317
+ try:
318
+ return _pointer_type_cache[cache_key]
319
+ except KeyError:
320
+ pass
321
+
322
+ # produce a name for the new type
323
+ if dtype is None:
324
+ name = 'any'
325
+ elif dtype.names is not None:
326
+ name = str(id(dtype))
327
+ else:
328
+ name = dtype.str
329
+ if ndim is not None:
330
+ name += "_%dd" % ndim
331
+ if shape is not None:
332
+ name += "_"+"x".join(str(x) for x in shape)
333
+ if flags is not None:
334
+ name += "_"+"_".join(flags)
335
+
336
+ if dtype is not None and shape is not None:
337
+ base = _concrete_ndptr
338
+ else:
339
+ base = _ndptr
340
+
341
+ klass = type("ndpointer_%s"%name, (base,),
342
+ {"_dtype_": dtype,
343
+ "_shape_" : shape,
344
+ "_ndim_" : ndim,
345
+ "_flags_" : num})
346
+ _pointer_type_cache[cache_key] = klass
347
+ return klass
348
+
349
+
350
+ if ctypes is not None:
351
+ def _ctype_ndarray(element_type, shape):
352
+ """ Create an ndarray of the given element type and shape """
353
+ for dim in shape[::-1]:
354
+ element_type = dim * element_type
355
+ # prevent the type name include np.ctypeslib
356
+ element_type.__module__ = None
357
+ return element_type
358
+
359
+
360
+ def _get_scalar_type_map():
361
+ """
362
+ Return a dictionary mapping native endian scalar dtype to ctypes types
363
+ """
364
+ ct = ctypes
365
+ simple_types = [
366
+ ct.c_byte, ct.c_short, ct.c_int, ct.c_long, ct.c_longlong,
367
+ ct.c_ubyte, ct.c_ushort, ct.c_uint, ct.c_ulong, ct.c_ulonglong,
368
+ ct.c_float, ct.c_double,
369
+ ct.c_bool,
370
+ ]
371
+ return {_dtype(ctype): ctype for ctype in simple_types}
372
+
373
+
374
+ _scalar_type_map = _get_scalar_type_map()
375
+
376
+
377
+ def _ctype_from_dtype_scalar(dtype):
378
+ # swapping twice ensure that `=` is promoted to <, >, or |
379
+ dtype_with_endian = dtype.newbyteorder('S').newbyteorder('S')
380
+ dtype_native = dtype.newbyteorder('=')
381
+ try:
382
+ ctype = _scalar_type_map[dtype_native]
383
+ except KeyError as e:
384
+ raise NotImplementedError(
385
+ "Converting {!r} to a ctypes type".format(dtype)
386
+ ) from None
387
+
388
+ if dtype_with_endian.byteorder == '>':
389
+ ctype = ctype.__ctype_be__
390
+ elif dtype_with_endian.byteorder == '<':
391
+ ctype = ctype.__ctype_le__
392
+
393
+ return ctype
394
+
395
+
396
+ def _ctype_from_dtype_subarray(dtype):
397
+ element_dtype, shape = dtype.subdtype
398
+ ctype = _ctype_from_dtype(element_dtype)
399
+ return _ctype_ndarray(ctype, shape)
400
+
401
+
402
+ def _ctype_from_dtype_structured(dtype):
403
+ # extract offsets of each field
404
+ field_data = []
405
+ for name in dtype.names:
406
+ field_dtype, offset = dtype.fields[name][:2]
407
+ field_data.append((offset, name, _ctype_from_dtype(field_dtype)))
408
+
409
+ # ctypes doesn't care about field order
410
+ field_data = sorted(field_data, key=lambda f: f[0])
411
+
412
+ if len(field_data) > 1 and all(offset == 0 for offset, name, ctype in field_data):
413
+ # union, if multiple fields all at address 0
414
+ size = 0
415
+ _fields_ = []
416
+ for offset, name, ctype in field_data:
417
+ _fields_.append((name, ctype))
418
+ size = max(size, ctypes.sizeof(ctype))
419
+
420
+ # pad to the right size
421
+ if dtype.itemsize != size:
422
+ _fields_.append(('', ctypes.c_char * dtype.itemsize))
423
+
424
+ # we inserted manual padding, so always `_pack_`
425
+ return type('union', (ctypes.Union,), dict(
426
+ _fields_=_fields_,
427
+ _pack_=1,
428
+ __module__=None,
429
+ ))
430
+ else:
431
+ last_offset = 0
432
+ _fields_ = []
433
+ for offset, name, ctype in field_data:
434
+ padding = offset - last_offset
435
+ if padding < 0:
436
+ raise NotImplementedError("Overlapping fields")
437
+ if padding > 0:
438
+ _fields_.append(('', ctypes.c_char * padding))
439
+
440
+ _fields_.append((name, ctype))
441
+ last_offset = offset + ctypes.sizeof(ctype)
442
+
443
+
444
+ padding = dtype.itemsize - last_offset
445
+ if padding > 0:
446
+ _fields_.append(('', ctypes.c_char * padding))
447
+
448
+ # we inserted manual padding, so always `_pack_`
449
+ return type('struct', (ctypes.Structure,), dict(
450
+ _fields_=_fields_,
451
+ _pack_=1,
452
+ __module__=None,
453
+ ))
454
+
455
+
456
+ def _ctype_from_dtype(dtype):
457
+ if dtype.fields is not None:
458
+ return _ctype_from_dtype_structured(dtype)
459
+ elif dtype.subdtype is not None:
460
+ return _ctype_from_dtype_subarray(dtype)
461
+ else:
462
+ return _ctype_from_dtype_scalar(dtype)
463
+
464
+
465
+ def as_ctypes_type(dtype):
466
+ r"""
467
+ Convert a dtype into a ctypes type.
468
+
469
+ Parameters
470
+ ----------
471
+ dtype : dtype
472
+ The dtype to convert
473
+
474
+ Returns
475
+ -------
476
+ ctype
477
+ A ctype scalar, union, array, or struct
478
+
479
+ Raises
480
+ ------
481
+ NotImplementedError
482
+ If the conversion is not possible
483
+
484
+ Notes
485
+ -----
486
+ This function does not losslessly round-trip in either direction.
487
+
488
+ ``np.dtype(as_ctypes_type(dt))`` will:
489
+
490
+ - insert padding fields
491
+ - reorder fields to be sorted by offset
492
+ - discard field titles
493
+
494
+ ``as_ctypes_type(np.dtype(ctype))`` will:
495
+
496
+ - discard the class names of `ctypes.Structure`\ s and
497
+ `ctypes.Union`\ s
498
+ - convert single-element `ctypes.Union`\ s into single-element
499
+ `ctypes.Structure`\ s
500
+ - insert padding fields
501
+
502
+ """
503
+ return _ctype_from_dtype(_dtype(dtype))
504
+
505
+
506
+ def as_array(obj, shape=None):
507
+ """
508
+ Create a numpy array from a ctypes array or POINTER.
509
+
510
+ The numpy array shares the memory with the ctypes object.
511
+
512
+ The shape parameter must be given if converting from a ctypes POINTER.
513
+ The shape parameter is ignored if converting from a ctypes array
514
+ """
515
+ if isinstance(obj, ctypes._Pointer):
516
+ # convert pointers to an array of the desired shape
517
+ if shape is None:
518
+ raise TypeError(
519
+ 'as_array() requires a shape argument when called on a '
520
+ 'pointer')
521
+ p_arr_type = ctypes.POINTER(_ctype_ndarray(obj._type_, shape))
522
+ obj = ctypes.cast(obj, p_arr_type).contents
523
+
524
+ return asarray(obj)
525
+
526
+
527
+ def as_ctypes(obj):
528
+ """Create and return a ctypes object from a numpy array. Actually
529
+ anything that exposes the __array_interface__ is accepted."""
530
+ ai = obj.__array_interface__
531
+ if ai["strides"]:
532
+ raise TypeError("strided arrays not supported")
533
+ if ai["version"] != 3:
534
+ raise TypeError("only __array_interface__ version 3 supported")
535
+ addr, readonly = ai["data"]
536
+ if readonly:
537
+ raise TypeError("readonly arrays unsupported")
538
+
539
+ # can't use `_dtype((ai["typestr"], ai["shape"]))` here, as it overflows
540
+ # dtype.itemsize (gh-14214)
541
+ ctype_scalar = as_ctypes_type(ai["typestr"])
542
+ result_type = _ctype_ndarray(ctype_scalar, ai["shape"])
543
+ result = result_type.from_address(addr)
544
+ result.__keep = obj
545
+ return result
llmeval-env/lib/python3.10/site-packages/numpy/ctypeslib.pyi ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NOTE: Numpy's mypy plugin is used for importing the correct
2
+ # platform-specific `ctypes._SimpleCData[int]` sub-type
3
+ from ctypes import c_int64 as _c_intp
4
+
5
+ import os
6
+ import sys
7
+ import ctypes
8
+ from collections.abc import Iterable, Sequence
9
+ from typing import (
10
+ Literal as L,
11
+ Any,
12
+ Union,
13
+ TypeVar,
14
+ Generic,
15
+ overload,
16
+ ClassVar,
17
+ )
18
+
19
+ from numpy import (
20
+ ndarray,
21
+ dtype,
22
+ generic,
23
+ bool_,
24
+ byte,
25
+ short,
26
+ intc,
27
+ int_,
28
+ longlong,
29
+ ubyte,
30
+ ushort,
31
+ uintc,
32
+ uint,
33
+ ulonglong,
34
+ single,
35
+ double,
36
+ longdouble,
37
+ void,
38
+ )
39
+ from numpy.core._internal import _ctypes
40
+ from numpy.core.multiarray import flagsobj
41
+ from numpy._typing import (
42
+ # Arrays
43
+ NDArray,
44
+ _ArrayLike,
45
+
46
+ # Shapes
47
+ _ShapeLike,
48
+
49
+ # DTypes
50
+ DTypeLike,
51
+ _DTypeLike,
52
+ _VoidDTypeLike,
53
+ _BoolCodes,
54
+ _UByteCodes,
55
+ _UShortCodes,
56
+ _UIntCCodes,
57
+ _UIntCodes,
58
+ _ULongLongCodes,
59
+ _ByteCodes,
60
+ _ShortCodes,
61
+ _IntCCodes,
62
+ _IntCodes,
63
+ _LongLongCodes,
64
+ _SingleCodes,
65
+ _DoubleCodes,
66
+ _LongDoubleCodes,
67
+ )
68
+
69
+ # TODO: Add a proper `_Shape` bound once we've got variadic typevars
70
+ _DType = TypeVar("_DType", bound=dtype[Any])
71
+ _DTypeOptional = TypeVar("_DTypeOptional", bound=None | dtype[Any])
72
+ _SCT = TypeVar("_SCT", bound=generic)
73
+
74
+ _FlagsKind = L[
75
+ 'C_CONTIGUOUS', 'CONTIGUOUS', 'C',
76
+ 'F_CONTIGUOUS', 'FORTRAN', 'F',
77
+ 'ALIGNED', 'A',
78
+ 'WRITEABLE', 'W',
79
+ 'OWNDATA', 'O',
80
+ 'WRITEBACKIFCOPY', 'X',
81
+ ]
82
+
83
+ # TODO: Add a shape typevar once we have variadic typevars (PEP 646)
84
+ class _ndptr(ctypes.c_void_p, Generic[_DTypeOptional]):
85
+ # In practice these 4 classvars are defined in the dynamic class
86
+ # returned by `ndpointer`
87
+ _dtype_: ClassVar[_DTypeOptional]
88
+ _shape_: ClassVar[None]
89
+ _ndim_: ClassVar[None | int]
90
+ _flags_: ClassVar[None | list[_FlagsKind]]
91
+
92
+ @overload
93
+ @classmethod
94
+ def from_param(cls: type[_ndptr[None]], obj: ndarray[Any, Any]) -> _ctypes[Any]: ...
95
+ @overload
96
+ @classmethod
97
+ def from_param(cls: type[_ndptr[_DType]], obj: ndarray[Any, _DType]) -> _ctypes[Any]: ...
98
+
99
+ class _concrete_ndptr(_ndptr[_DType]):
100
+ _dtype_: ClassVar[_DType]
101
+ _shape_: ClassVar[tuple[int, ...]]
102
+ @property
103
+ def contents(self) -> ndarray[Any, _DType]: ...
104
+
105
+ def load_library(
106
+ libname: str | bytes | os.PathLike[str] | os.PathLike[bytes],
107
+ loader_path: str | bytes | os.PathLike[str] | os.PathLike[bytes],
108
+ ) -> ctypes.CDLL: ...
109
+
110
+ __all__: list[str]
111
+
112
+ c_intp = _c_intp
113
+
114
+ @overload
115
+ def ndpointer(
116
+ dtype: None = ...,
117
+ ndim: int = ...,
118
+ shape: None | _ShapeLike = ...,
119
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
120
+ ) -> type[_ndptr[None]]: ...
121
+ @overload
122
+ def ndpointer(
123
+ dtype: _DTypeLike[_SCT],
124
+ ndim: int = ...,
125
+ *,
126
+ shape: _ShapeLike,
127
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
128
+ ) -> type[_concrete_ndptr[dtype[_SCT]]]: ...
129
+ @overload
130
+ def ndpointer(
131
+ dtype: DTypeLike,
132
+ ndim: int = ...,
133
+ *,
134
+ shape: _ShapeLike,
135
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
136
+ ) -> type[_concrete_ndptr[dtype[Any]]]: ...
137
+ @overload
138
+ def ndpointer(
139
+ dtype: _DTypeLike[_SCT],
140
+ ndim: int = ...,
141
+ shape: None = ...,
142
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
143
+ ) -> type[_ndptr[dtype[_SCT]]]: ...
144
+ @overload
145
+ def ndpointer(
146
+ dtype: DTypeLike,
147
+ ndim: int = ...,
148
+ shape: None = ...,
149
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
150
+ ) -> type[_ndptr[dtype[Any]]]: ...
151
+
152
+ @overload
153
+ def as_ctypes_type(dtype: _BoolCodes | _DTypeLike[bool_] | type[ctypes.c_bool]) -> type[ctypes.c_bool]: ...
154
+ @overload
155
+ def as_ctypes_type(dtype: _ByteCodes | _DTypeLike[byte] | type[ctypes.c_byte]) -> type[ctypes.c_byte]: ...
156
+ @overload
157
+ def as_ctypes_type(dtype: _ShortCodes | _DTypeLike[short] | type[ctypes.c_short]) -> type[ctypes.c_short]: ...
158
+ @overload
159
+ def as_ctypes_type(dtype: _IntCCodes | _DTypeLike[intc] | type[ctypes.c_int]) -> type[ctypes.c_int]: ...
160
+ @overload
161
+ def as_ctypes_type(dtype: _IntCodes | _DTypeLike[int_] | type[int | ctypes.c_long]) -> type[ctypes.c_long]: ...
162
+ @overload
163
+ def as_ctypes_type(dtype: _LongLongCodes | _DTypeLike[longlong] | type[ctypes.c_longlong]) -> type[ctypes.c_longlong]: ...
164
+ @overload
165
+ def as_ctypes_type(dtype: _UByteCodes | _DTypeLike[ubyte] | type[ctypes.c_ubyte]) -> type[ctypes.c_ubyte]: ...
166
+ @overload
167
+ def as_ctypes_type(dtype: _UShortCodes | _DTypeLike[ushort] | type[ctypes.c_ushort]) -> type[ctypes.c_ushort]: ...
168
+ @overload
169
+ def as_ctypes_type(dtype: _UIntCCodes | _DTypeLike[uintc] | type[ctypes.c_uint]) -> type[ctypes.c_uint]: ...
170
+ @overload
171
+ def as_ctypes_type(dtype: _UIntCodes | _DTypeLike[uint] | type[ctypes.c_ulong]) -> type[ctypes.c_ulong]: ...
172
+ @overload
173
+ def as_ctypes_type(dtype: _ULongLongCodes | _DTypeLike[ulonglong] | type[ctypes.c_ulonglong]) -> type[ctypes.c_ulonglong]: ...
174
+ @overload
175
+ def as_ctypes_type(dtype: _SingleCodes | _DTypeLike[single] | type[ctypes.c_float]) -> type[ctypes.c_float]: ...
176
+ @overload
177
+ def as_ctypes_type(dtype: _DoubleCodes | _DTypeLike[double] | type[float | ctypes.c_double]) -> type[ctypes.c_double]: ...
178
+ @overload
179
+ def as_ctypes_type(dtype: _LongDoubleCodes | _DTypeLike[longdouble] | type[ctypes.c_longdouble]) -> type[ctypes.c_longdouble]: ...
180
+ @overload
181
+ def as_ctypes_type(dtype: _VoidDTypeLike) -> type[Any]: ... # `ctypes.Union` or `ctypes.Structure`
182
+ @overload
183
+ def as_ctypes_type(dtype: str) -> type[Any]: ...
184
+
185
+ @overload
186
+ def as_array(obj: ctypes._PointerLike, shape: Sequence[int]) -> NDArray[Any]: ...
187
+ @overload
188
+ def as_array(obj: _ArrayLike[_SCT], shape: None | _ShapeLike = ...) -> NDArray[_SCT]: ...
189
+ @overload
190
+ def as_array(obj: object, shape: None | _ShapeLike = ...) -> NDArray[Any]: ...
191
+
192
+ @overload
193
+ def as_ctypes(obj: bool_) -> ctypes.c_bool: ...
194
+ @overload
195
+ def as_ctypes(obj: byte) -> ctypes.c_byte: ...
196
+ @overload
197
+ def as_ctypes(obj: short) -> ctypes.c_short: ...
198
+ @overload
199
+ def as_ctypes(obj: intc) -> ctypes.c_int: ...
200
+ @overload
201
+ def as_ctypes(obj: int_) -> ctypes.c_long: ...
202
+ @overload
203
+ def as_ctypes(obj: longlong) -> ctypes.c_longlong: ...
204
+ @overload
205
+ def as_ctypes(obj: ubyte) -> ctypes.c_ubyte: ...
206
+ @overload
207
+ def as_ctypes(obj: ushort) -> ctypes.c_ushort: ...
208
+ @overload
209
+ def as_ctypes(obj: uintc) -> ctypes.c_uint: ...
210
+ @overload
211
+ def as_ctypes(obj: uint) -> ctypes.c_ulong: ...
212
+ @overload
213
+ def as_ctypes(obj: ulonglong) -> ctypes.c_ulonglong: ...
214
+ @overload
215
+ def as_ctypes(obj: single) -> ctypes.c_float: ...
216
+ @overload
217
+ def as_ctypes(obj: double) -> ctypes.c_double: ...
218
+ @overload
219
+ def as_ctypes(obj: longdouble) -> ctypes.c_longdouble: ...
220
+ @overload
221
+ def as_ctypes(obj: void) -> Any: ... # `ctypes.Union` or `ctypes.Structure`
222
+ @overload
223
+ def as_ctypes(obj: NDArray[bool_]) -> ctypes.Array[ctypes.c_bool]: ...
224
+ @overload
225
+ def as_ctypes(obj: NDArray[byte]) -> ctypes.Array[ctypes.c_byte]: ...
226
+ @overload
227
+ def as_ctypes(obj: NDArray[short]) -> ctypes.Array[ctypes.c_short]: ...
228
+ @overload
229
+ def as_ctypes(obj: NDArray[intc]) -> ctypes.Array[ctypes.c_int]: ...
230
+ @overload
231
+ def as_ctypes(obj: NDArray[int_]) -> ctypes.Array[ctypes.c_long]: ...
232
+ @overload
233
+ def as_ctypes(obj: NDArray[longlong]) -> ctypes.Array[ctypes.c_longlong]: ...
234
+ @overload
235
+ def as_ctypes(obj: NDArray[ubyte]) -> ctypes.Array[ctypes.c_ubyte]: ...
236
+ @overload
237
+ def as_ctypes(obj: NDArray[ushort]) -> ctypes.Array[ctypes.c_ushort]: ...
238
+ @overload
239
+ def as_ctypes(obj: NDArray[uintc]) -> ctypes.Array[ctypes.c_uint]: ...
240
+ @overload
241
+ def as_ctypes(obj: NDArray[uint]) -> ctypes.Array[ctypes.c_ulong]: ...
242
+ @overload
243
+ def as_ctypes(obj: NDArray[ulonglong]) -> ctypes.Array[ctypes.c_ulonglong]: ...
244
+ @overload
245
+ def as_ctypes(obj: NDArray[single]) -> ctypes.Array[ctypes.c_float]: ...
246
+ @overload
247
+ def as_ctypes(obj: NDArray[double]) -> ctypes.Array[ctypes.c_double]: ...
248
+ @overload
249
+ def as_ctypes(obj: NDArray[longdouble]) -> ctypes.Array[ctypes.c_longdouble]: ...
250
+ @overload
251
+ def as_ctypes(obj: NDArray[void]) -> ctypes.Array[Any]: ... # `ctypes.Union` or `ctypes.Structure`
llmeval-env/lib/python3.10/site-packages/numpy/matlib.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ # 2018-05-29, PendingDeprecationWarning added to matrix.__new__
4
+ # 2020-01-23, numpy 1.19.0 PendingDeprecatonWarning
5
+ warnings.warn("Importing from numpy.matlib is deprecated since 1.19.0. "
6
+ "The matrix subclass is not the recommended way to represent "
7
+ "matrices or deal with linear algebra (see "
8
+ "https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). "
9
+ "Please adjust your code to use regular ndarray. ",
10
+ PendingDeprecationWarning, stacklevel=2)
11
+
12
+ import numpy as np
13
+ from numpy.matrixlib.defmatrix import matrix, asmatrix
14
+ # Matlib.py contains all functions in the numpy namespace with a few
15
+ # replacements. See doc/source/reference/routines.matlib.rst for details.
16
+ # Need * as we're copying the numpy namespace.
17
+ from numpy import * # noqa: F403
18
+
19
+ __version__ = np.__version__
20
+
21
+ __all__ = np.__all__[:] # copy numpy namespace
22
+ __all__ += ['rand', 'randn', 'repmat']
23
+
24
+ def empty(shape, dtype=None, order='C'):
25
+ """Return a new matrix of given shape and type, without initializing entries.
26
+
27
+ Parameters
28
+ ----------
29
+ shape : int or tuple of int
30
+ Shape of the empty matrix.
31
+ dtype : data-type, optional
32
+ Desired output data-type.
33
+ order : {'C', 'F'}, optional
34
+ Whether to store multi-dimensional data in row-major
35
+ (C-style) or column-major (Fortran-style) order in
36
+ memory.
37
+
38
+ See Also
39
+ --------
40
+ empty_like, zeros
41
+
42
+ Notes
43
+ -----
44
+ `empty`, unlike `zeros`, does not set the matrix values to zero,
45
+ and may therefore be marginally faster. On the other hand, it requires
46
+ the user to manually set all the values in the array, and should be
47
+ used with caution.
48
+
49
+ Examples
50
+ --------
51
+ >>> import numpy.matlib
52
+ >>> np.matlib.empty((2, 2)) # filled with random data
53
+ matrix([[ 6.76425276e-320, 9.79033856e-307], # random
54
+ [ 7.39337286e-309, 3.22135945e-309]])
55
+ >>> np.matlib.empty((2, 2), dtype=int)
56
+ matrix([[ 6600475, 0], # random
57
+ [ 6586976, 22740995]])
58
+
59
+ """
60
+ return ndarray.__new__(matrix, shape, dtype, order=order)
61
+
62
+ def ones(shape, dtype=None, order='C'):
63
+ """
64
+ Matrix of ones.
65
+
66
+ Return a matrix of given shape and type, filled with ones.
67
+
68
+ Parameters
69
+ ----------
70
+ shape : {sequence of ints, int}
71
+ Shape of the matrix
72
+ dtype : data-type, optional
73
+ The desired data-type for the matrix, default is np.float64.
74
+ order : {'C', 'F'}, optional
75
+ Whether to store matrix in C- or Fortran-contiguous order,
76
+ default is 'C'.
77
+
78
+ Returns
79
+ -------
80
+ out : matrix
81
+ Matrix of ones of given shape, dtype, and order.
82
+
83
+ See Also
84
+ --------
85
+ ones : Array of ones.
86
+ matlib.zeros : Zero matrix.
87
+
88
+ Notes
89
+ -----
90
+ If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
91
+ `out` becomes a single row matrix of shape ``(1,N)``.
92
+
93
+ Examples
94
+ --------
95
+ >>> np.matlib.ones((2,3))
96
+ matrix([[1., 1., 1.],
97
+ [1., 1., 1.]])
98
+
99
+ >>> np.matlib.ones(2)
100
+ matrix([[1., 1.]])
101
+
102
+ """
103
+ a = ndarray.__new__(matrix, shape, dtype, order=order)
104
+ a.fill(1)
105
+ return a
106
+
107
+ def zeros(shape, dtype=None, order='C'):
108
+ """
109
+ Return a matrix of given shape and type, filled with zeros.
110
+
111
+ Parameters
112
+ ----------
113
+ shape : int or sequence of ints
114
+ Shape of the matrix
115
+ dtype : data-type, optional
116
+ The desired data-type for the matrix, default is float.
117
+ order : {'C', 'F'}, optional
118
+ Whether to store the result in C- or Fortran-contiguous order,
119
+ default is 'C'.
120
+
121
+ Returns
122
+ -------
123
+ out : matrix
124
+ Zero matrix of given shape, dtype, and order.
125
+
126
+ See Also
127
+ --------
128
+ numpy.zeros : Equivalent array function.
129
+ matlib.ones : Return a matrix of ones.
130
+
131
+ Notes
132
+ -----
133
+ If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
134
+ `out` becomes a single row matrix of shape ``(1,N)``.
135
+
136
+ Examples
137
+ --------
138
+ >>> import numpy.matlib
139
+ >>> np.matlib.zeros((2, 3))
140
+ matrix([[0., 0., 0.],
141
+ [0., 0., 0.]])
142
+
143
+ >>> np.matlib.zeros(2)
144
+ matrix([[0., 0.]])
145
+
146
+ """
147
+ a = ndarray.__new__(matrix, shape, dtype, order=order)
148
+ a.fill(0)
149
+ return a
150
+
151
+ def identity(n,dtype=None):
152
+ """
153
+ Returns the square identity matrix of given size.
154
+
155
+ Parameters
156
+ ----------
157
+ n : int
158
+ Size of the returned identity matrix.
159
+ dtype : data-type, optional
160
+ Data-type of the output. Defaults to ``float``.
161
+
162
+ Returns
163
+ -------
164
+ out : matrix
165
+ `n` x `n` matrix with its main diagonal set to one,
166
+ and all other elements zero.
167
+
168
+ See Also
169
+ --------
170
+ numpy.identity : Equivalent array function.
171
+ matlib.eye : More general matrix identity function.
172
+
173
+ Examples
174
+ --------
175
+ >>> import numpy.matlib
176
+ >>> np.matlib.identity(3, dtype=int)
177
+ matrix([[1, 0, 0],
178
+ [0, 1, 0],
179
+ [0, 0, 1]])
180
+
181
+ """
182
+ a = array([1]+n*[0], dtype=dtype)
183
+ b = empty((n, n), dtype=dtype)
184
+ b.flat = a
185
+ return b
186
+
187
+ def eye(n,M=None, k=0, dtype=float, order='C'):
188
+ """
189
+ Return a matrix with ones on the diagonal and zeros elsewhere.
190
+
191
+ Parameters
192
+ ----------
193
+ n : int
194
+ Number of rows in the output.
195
+ M : int, optional
196
+ Number of columns in the output, defaults to `n`.
197
+ k : int, optional
198
+ Index of the diagonal: 0 refers to the main diagonal,
199
+ a positive value refers to an upper diagonal,
200
+ and a negative value to a lower diagonal.
201
+ dtype : dtype, optional
202
+ Data-type of the returned matrix.
203
+ order : {'C', 'F'}, optional
204
+ Whether the output should be stored in row-major (C-style) or
205
+ column-major (Fortran-style) order in memory.
206
+
207
+ .. versionadded:: 1.14.0
208
+
209
+ Returns
210
+ -------
211
+ I : matrix
212
+ A `n` x `M` matrix where all elements are equal to zero,
213
+ except for the `k`-th diagonal, whose values are equal to one.
214
+
215
+ See Also
216
+ --------
217
+ numpy.eye : Equivalent array function.
218
+ identity : Square identity matrix.
219
+
220
+ Examples
221
+ --------
222
+ >>> import numpy.matlib
223
+ >>> np.matlib.eye(3, k=1, dtype=float)
224
+ matrix([[0., 1., 0.],
225
+ [0., 0., 1.],
226
+ [0., 0., 0.]])
227
+
228
+ """
229
+ return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order))
230
+
231
+ def rand(*args):
232
+ """
233
+ Return a matrix of random values with given shape.
234
+
235
+ Create a matrix of the given shape and propagate it with
236
+ random samples from a uniform distribution over ``[0, 1)``.
237
+
238
+ Parameters
239
+ ----------
240
+ \\*args : Arguments
241
+ Shape of the output.
242
+ If given as N integers, each integer specifies the size of one
243
+ dimension.
244
+ If given as a tuple, this tuple gives the complete shape.
245
+
246
+ Returns
247
+ -------
248
+ out : ndarray
249
+ The matrix of random values with shape given by `\\*args`.
250
+
251
+ See Also
252
+ --------
253
+ randn, numpy.random.RandomState.rand
254
+
255
+ Examples
256
+ --------
257
+ >>> np.random.seed(123)
258
+ >>> import numpy.matlib
259
+ >>> np.matlib.rand(2, 3)
260
+ matrix([[0.69646919, 0.28613933, 0.22685145],
261
+ [0.55131477, 0.71946897, 0.42310646]])
262
+ >>> np.matlib.rand((2, 3))
263
+ matrix([[0.9807642 , 0.68482974, 0.4809319 ],
264
+ [0.39211752, 0.34317802, 0.72904971]])
265
+
266
+ If the first argument is a tuple, other arguments are ignored:
267
+
268
+ >>> np.matlib.rand((2, 3), 4)
269
+ matrix([[0.43857224, 0.0596779 , 0.39804426],
270
+ [0.73799541, 0.18249173, 0.17545176]])
271
+
272
+ """
273
+ if isinstance(args[0], tuple):
274
+ args = args[0]
275
+ return asmatrix(np.random.rand(*args))
276
+
277
+ def randn(*args):
278
+ """
279
+ Return a random matrix with data from the "standard normal" distribution.
280
+
281
+ `randn` generates a matrix filled with random floats sampled from a
282
+ univariate "normal" (Gaussian) distribution of mean 0 and variance 1.
283
+
284
+ Parameters
285
+ ----------
286
+ \\*args : Arguments
287
+ Shape of the output.
288
+ If given as N integers, each integer specifies the size of one
289
+ dimension. If given as a tuple, this tuple gives the complete shape.
290
+
291
+ Returns
292
+ -------
293
+ Z : matrix of floats
294
+ A matrix of floating-point samples drawn from the standard normal
295
+ distribution.
296
+
297
+ See Also
298
+ --------
299
+ rand, numpy.random.RandomState.randn
300
+
301
+ Notes
302
+ -----
303
+ For random samples from the normal distribution with mean ``mu`` and
304
+ standard deviation ``sigma``, use::
305
+
306
+ sigma * np.matlib.randn(...) + mu
307
+
308
+ Examples
309
+ --------
310
+ >>> np.random.seed(123)
311
+ >>> import numpy.matlib
312
+ >>> np.matlib.randn(1)
313
+ matrix([[-1.0856306]])
314
+ >>> np.matlib.randn(1, 2, 3)
315
+ matrix([[ 0.99734545, 0.2829785 , -1.50629471],
316
+ [-0.57860025, 1.65143654, -2.42667924]])
317
+
318
+ Two-by-four matrix of samples from the normal distribution with
319
+ mean 3 and standard deviation 2.5:
320
+
321
+ >>> 2.5 * np.matlib.randn((2, 4)) + 3
322
+ matrix([[1.92771843, 6.16484065, 0.83314899, 1.30278462],
323
+ [2.76322758, 6.72847407, 1.40274501, 1.8900451 ]])
324
+
325
+ """
326
+ if isinstance(args[0], tuple):
327
+ args = args[0]
328
+ return asmatrix(np.random.randn(*args))
329
+
330
+ def repmat(a, m, n):
331
+ """
332
+ Repeat a 0-D to 2-D array or matrix MxN times.
333
+
334
+ Parameters
335
+ ----------
336
+ a : array_like
337
+ The array or matrix to be repeated.
338
+ m, n : int
339
+ The number of times `a` is repeated along the first and second axes.
340
+
341
+ Returns
342
+ -------
343
+ out : ndarray
344
+ The result of repeating `a`.
345
+
346
+ Examples
347
+ --------
348
+ >>> import numpy.matlib
349
+ >>> a0 = np.array(1)
350
+ >>> np.matlib.repmat(a0, 2, 3)
351
+ array([[1, 1, 1],
352
+ [1, 1, 1]])
353
+
354
+ >>> a1 = np.arange(4)
355
+ >>> np.matlib.repmat(a1, 2, 2)
356
+ array([[0, 1, 2, 3, 0, 1, 2, 3],
357
+ [0, 1, 2, 3, 0, 1, 2, 3]])
358
+
359
+ >>> a2 = np.asmatrix(np.arange(6).reshape(2, 3))
360
+ >>> np.matlib.repmat(a2, 2, 3)
361
+ matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2],
362
+ [3, 4, 5, 3, 4, 5, 3, 4, 5],
363
+ [0, 1, 2, 0, 1, 2, 0, 1, 2],
364
+ [3, 4, 5, 3, 4, 5, 3, 4, 5]])
365
+
366
+ """
367
+ a = asanyarray(a)
368
+ ndim = a.ndim
369
+ if ndim == 0:
370
+ origrows, origcols = (1, 1)
371
+ elif ndim == 1:
372
+ origrows, origcols = (1, a.shape[0])
373
+ else:
374
+ origrows, origcols = a.shape
375
+ rows = origrows * m
376
+ cols = origcols * n
377
+ c = a.reshape(1, a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0)
378
+ return c.reshape(rows, cols)
llmeval-env/lib/python3.10/site-packages/numpy/py.typed ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/psutil/__init__.py ADDED
@@ -0,0 +1,2492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """psutil is a cross-platform library for retrieving information on
8
+ running processes and system utilization (CPU, memory, disks, network,
9
+ sensors) in Python. Supported platforms:
10
+
11
+ - Linux
12
+ - Windows
13
+ - macOS
14
+ - FreeBSD
15
+ - OpenBSD
16
+ - NetBSD
17
+ - Sun Solaris
18
+ - AIX
19
+
20
+ Works with Python versions 2.7 and 3.6+.
21
+ """
22
+
23
+ from __future__ import division
24
+
25
+ import collections
26
+ import contextlib
27
+ import datetime
28
+ import functools
29
+ import os
30
+ import signal
31
+ import subprocess
32
+ import sys
33
+ import threading
34
+ import time
35
+
36
+
37
+ try:
38
+ import pwd
39
+ except ImportError:
40
+ pwd = None
41
+
42
+ from . import _common
43
+ from ._common import AIX
44
+ from ._common import BSD
45
+ from ._common import CONN_CLOSE
46
+ from ._common import CONN_CLOSE_WAIT
47
+ from ._common import CONN_CLOSING
48
+ from ._common import CONN_ESTABLISHED
49
+ from ._common import CONN_FIN_WAIT1
50
+ from ._common import CONN_FIN_WAIT2
51
+ from ._common import CONN_LAST_ACK
52
+ from ._common import CONN_LISTEN
53
+ from ._common import CONN_NONE
54
+ from ._common import CONN_SYN_RECV
55
+ from ._common import CONN_SYN_SENT
56
+ from ._common import CONN_TIME_WAIT
57
+ from ._common import FREEBSD # NOQA
58
+ from ._common import LINUX
59
+ from ._common import MACOS
60
+ from ._common import NETBSD # NOQA
61
+ from ._common import NIC_DUPLEX_FULL
62
+ from ._common import NIC_DUPLEX_HALF
63
+ from ._common import NIC_DUPLEX_UNKNOWN
64
+ from ._common import OPENBSD # NOQA
65
+ from ._common import OSX # deprecated alias
66
+ from ._common import POSIX # NOQA
67
+ from ._common import POWER_TIME_UNKNOWN
68
+ from ._common import POWER_TIME_UNLIMITED
69
+ from ._common import STATUS_DEAD
70
+ from ._common import STATUS_DISK_SLEEP
71
+ from ._common import STATUS_IDLE
72
+ from ._common import STATUS_LOCKED
73
+ from ._common import STATUS_PARKED
74
+ from ._common import STATUS_RUNNING
75
+ from ._common import STATUS_SLEEPING
76
+ from ._common import STATUS_STOPPED
77
+ from ._common import STATUS_TRACING_STOP
78
+ from ._common import STATUS_WAITING
79
+ from ._common import STATUS_WAKING
80
+ from ._common import STATUS_ZOMBIE
81
+ from ._common import SUNOS
82
+ from ._common import WINDOWS
83
+ from ._common import AccessDenied
84
+ from ._common import Error
85
+ from ._common import NoSuchProcess
86
+ from ._common import TimeoutExpired
87
+ from ._common import ZombieProcess
88
+ from ._common import memoize_when_activated
89
+ from ._common import wrap_numbers as _wrap_numbers
90
+ from ._compat import PY3 as _PY3
91
+ from ._compat import PermissionError
92
+ from ._compat import ProcessLookupError
93
+ from ._compat import SubprocessTimeoutExpired as _SubprocessTimeoutExpired
94
+ from ._compat import long
95
+
96
+
97
+ if LINUX:
98
+ # This is public API and it will be retrieved from _pslinux.py
99
+ # via sys.modules.
100
+ PROCFS_PATH = "/proc"
101
+
102
+ from . import _pslinux as _psplatform
103
+ from ._pslinux import IOPRIO_CLASS_BE # NOQA
104
+ from ._pslinux import IOPRIO_CLASS_IDLE # NOQA
105
+ from ._pslinux import IOPRIO_CLASS_NONE # NOQA
106
+ from ._pslinux import IOPRIO_CLASS_RT # NOQA
107
+
108
+ elif WINDOWS:
109
+ from . import _pswindows as _psplatform
110
+ from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # NOQA
111
+ from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # NOQA
112
+ from ._psutil_windows import HIGH_PRIORITY_CLASS # NOQA
113
+ from ._psutil_windows import IDLE_PRIORITY_CLASS # NOQA
114
+ from ._psutil_windows import NORMAL_PRIORITY_CLASS # NOQA
115
+ from ._psutil_windows import REALTIME_PRIORITY_CLASS # NOQA
116
+ from ._pswindows import CONN_DELETE_TCB # NOQA
117
+ from ._pswindows import IOPRIO_HIGH # NOQA
118
+ from ._pswindows import IOPRIO_LOW # NOQA
119
+ from ._pswindows import IOPRIO_NORMAL # NOQA
120
+ from ._pswindows import IOPRIO_VERYLOW # NOQA
121
+
122
+ elif MACOS:
123
+ from . import _psosx as _psplatform
124
+
125
+ elif BSD:
126
+ from . import _psbsd as _psplatform
127
+
128
+ elif SUNOS:
129
+ from . import _pssunos as _psplatform
130
+ from ._pssunos import CONN_BOUND # NOQA
131
+ from ._pssunos import CONN_IDLE # NOQA
132
+
133
+ # This is public writable API which is read from _pslinux.py and
134
+ # _pssunos.py via sys.modules.
135
+ PROCFS_PATH = "/proc"
136
+
137
+ elif AIX:
138
+ from . import _psaix as _psplatform
139
+
140
+ # This is public API and it will be retrieved from _pslinux.py
141
+ # via sys.modules.
142
+ PROCFS_PATH = "/proc"
143
+
144
+ else: # pragma: no cover
145
+ raise NotImplementedError('platform %s is not supported' % sys.platform)
146
+
147
+
148
+ # fmt: off
149
+ __all__ = [
150
+ # exceptions
151
+ "Error", "NoSuchProcess", "ZombieProcess", "AccessDenied",
152
+ "TimeoutExpired",
153
+
154
+ # constants
155
+ "version_info", "__version__",
156
+
157
+ "STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
158
+ "STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
159
+ "STATUS_WAKING", "STATUS_LOCKED", "STATUS_WAITING", "STATUS_LOCKED",
160
+ "STATUS_PARKED",
161
+
162
+ "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
163
+ "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
164
+ "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE",
165
+ # "CONN_IDLE", "CONN_BOUND",
166
+
167
+ "AF_LINK",
168
+
169
+ "NIC_DUPLEX_FULL", "NIC_DUPLEX_HALF", "NIC_DUPLEX_UNKNOWN",
170
+
171
+ "POWER_TIME_UNKNOWN", "POWER_TIME_UNLIMITED",
172
+
173
+ "BSD", "FREEBSD", "LINUX", "NETBSD", "OPENBSD", "MACOS", "OSX", "POSIX",
174
+ "SUNOS", "WINDOWS", "AIX",
175
+
176
+ # "RLIM_INFINITY", "RLIMIT_AS", "RLIMIT_CORE", "RLIMIT_CPU", "RLIMIT_DATA",
177
+ # "RLIMIT_FSIZE", "RLIMIT_LOCKS", "RLIMIT_MEMLOCK", "RLIMIT_NOFILE",
178
+ # "RLIMIT_NPROC", "RLIMIT_RSS", "RLIMIT_STACK", "RLIMIT_MSGQUEUE",
179
+ # "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIMIT_SIGPENDING",
180
+
181
+ # classes
182
+ "Process", "Popen",
183
+
184
+ # functions
185
+ "pid_exists", "pids", "process_iter", "wait_procs", # proc
186
+ "virtual_memory", "swap_memory", # memory
187
+ "cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count", # cpu
188
+ "cpu_stats", # "cpu_freq", "getloadavg"
189
+ "net_io_counters", "net_connections", "net_if_addrs", # network
190
+ "net_if_stats",
191
+ "disk_io_counters", "disk_partitions", "disk_usage", # disk
192
+ # "sensors_temperatures", "sensors_battery", "sensors_fans" # sensors
193
+ "users", "boot_time", # others
194
+ ]
195
+ # fmt: on
196
+
197
+
198
+ __all__.extend(_psplatform.__extra__all__)
199
+
200
+ # Linux, FreeBSD
201
+ if hasattr(_psplatform.Process, "rlimit"):
202
+ # Populate global namespace with RLIM* constants.
203
+ from . import _psutil_posix
204
+
205
+ _globals = globals()
206
+ _name = None
207
+ for _name in dir(_psutil_posix):
208
+ if _name.startswith('RLIM') and _name.isupper():
209
+ _globals[_name] = getattr(_psutil_posix, _name)
210
+ __all__.append(_name)
211
+ del _globals, _name
212
+
213
+ AF_LINK = _psplatform.AF_LINK
214
+
215
+ __author__ = "Giampaolo Rodola'"
216
+ __version__ = "5.9.8"
217
+ version_info = tuple([int(num) for num in __version__.split('.')])
218
+
219
+ _timer = getattr(time, 'monotonic', time.time)
220
+ _TOTAL_PHYMEM = None
221
+ _LOWEST_PID = None
222
+ _SENTINEL = object()
223
+
224
+ # Sanity check in case the user messed up with psutil installation
225
+ # or did something weird with sys.path. In this case we might end
226
+ # up importing a python module using a C extension module which
227
+ # was compiled for a different version of psutil.
228
+ # We want to prevent that by failing sooner rather than later.
229
+ # See: https://github.com/giampaolo/psutil/issues/564
230
+ if int(__version__.replace('.', '')) != getattr(
231
+ _psplatform.cext, 'version', None
232
+ ):
233
+ msg = "version conflict: %r C extension " % _psplatform.cext.__file__
234
+ msg += "module was built for another version of psutil"
235
+ if hasattr(_psplatform.cext, 'version'):
236
+ msg += " (%s instead of %s)" % (
237
+ '.'.join([x for x in str(_psplatform.cext.version)]),
238
+ __version__,
239
+ )
240
+ else:
241
+ msg += " (different than %s)" % __version__
242
+ msg += "; you may try to 'pip uninstall psutil', manually remove %s" % (
243
+ getattr(
244
+ _psplatform.cext,
245
+ "__file__",
246
+ "the existing psutil install directory",
247
+ )
248
+ )
249
+ msg += " or clean the virtual env somehow, then reinstall"
250
+ raise ImportError(msg)
251
+
252
+
253
+ # =====================================================================
254
+ # --- Utils
255
+ # =====================================================================
256
+
257
+
258
+ if hasattr(_psplatform, 'ppid_map'):
259
+ # Faster version (Windows and Linux).
260
+ _ppid_map = _psplatform.ppid_map
261
+ else: # pragma: no cover
262
+
263
+ def _ppid_map():
264
+ """Return a {pid: ppid, ...} dict for all running processes in
265
+ one shot. Used to speed up Process.children().
266
+ """
267
+ ret = {}
268
+ for pid in pids():
269
+ try:
270
+ ret[pid] = _psplatform.Process(pid).ppid()
271
+ except (NoSuchProcess, ZombieProcess):
272
+ pass
273
+ return ret
274
+
275
+
276
+ def _pprint_secs(secs):
277
+ """Format seconds in a human readable form."""
278
+ now = time.time()
279
+ secs_ago = int(now - secs)
280
+ fmt = "%H:%M:%S" if secs_ago < 60 * 60 * 24 else "%Y-%m-%d %H:%M:%S"
281
+ return datetime.datetime.fromtimestamp(secs).strftime(fmt)
282
+
283
+
284
+ # =====================================================================
285
+ # --- Process class
286
+ # =====================================================================
287
+
288
+
289
+ class Process(object): # noqa: UP004
290
+ """Represents an OS process with the given PID.
291
+ If PID is omitted current process PID (os.getpid()) is used.
292
+ Raise NoSuchProcess if PID does not exist.
293
+
294
+ Note that most of the methods of this class do not make sure
295
+ the PID of the process being queried has been reused over time.
296
+ That means you might end up retrieving an information referring
297
+ to another process in case the original one this instance
298
+ refers to is gone in the meantime.
299
+
300
+ The only exceptions for which process identity is pre-emptively
301
+ checked and guaranteed are:
302
+
303
+ - parent()
304
+ - children()
305
+ - nice() (set)
306
+ - ionice() (set)
307
+ - rlimit() (set)
308
+ - cpu_affinity (set)
309
+ - suspend()
310
+ - resume()
311
+ - send_signal()
312
+ - terminate()
313
+ - kill()
314
+
315
+ To prevent this problem for all other methods you can:
316
+ - use is_running() before querying the process
317
+ - if you're continuously iterating over a set of Process
318
+ instances use process_iter() which pre-emptively checks
319
+ process identity for every yielded instance
320
+ """
321
+
322
+ def __init__(self, pid=None):
323
+ self._init(pid)
324
+
325
+ def _init(self, pid, _ignore_nsp=False):
326
+ if pid is None:
327
+ pid = os.getpid()
328
+ else:
329
+ if not _PY3 and not isinstance(pid, (int, long)):
330
+ msg = "pid must be an integer (got %r)" % pid
331
+ raise TypeError(msg)
332
+ if pid < 0:
333
+ msg = "pid must be a positive integer (got %s)" % pid
334
+ raise ValueError(msg)
335
+ try:
336
+ _psplatform.cext.check_pid_range(pid)
337
+ except OverflowError:
338
+ msg = "process PID out of range (got %s)" % pid
339
+ raise NoSuchProcess(pid, msg=msg)
340
+
341
+ self._pid = pid
342
+ self._name = None
343
+ self._exe = None
344
+ self._create_time = None
345
+ self._gone = False
346
+ self._pid_reused = False
347
+ self._hash = None
348
+ self._lock = threading.RLock()
349
+ # used for caching on Windows only (on POSIX ppid may change)
350
+ self._ppid = None
351
+ # platform-specific modules define an _psplatform.Process
352
+ # implementation class
353
+ self._proc = _psplatform.Process(pid)
354
+ self._last_sys_cpu_times = None
355
+ self._last_proc_cpu_times = None
356
+ self._exitcode = _SENTINEL
357
+ # cache creation time for later use in is_running() method
358
+ try:
359
+ self.create_time()
360
+ except AccessDenied:
361
+ # We should never get here as AFAIK we're able to get
362
+ # process creation time on all platforms even as a
363
+ # limited user.
364
+ pass
365
+ except ZombieProcess:
366
+ # Zombies can still be queried by this class (although
367
+ # not always) and pids() return them so just go on.
368
+ pass
369
+ except NoSuchProcess:
370
+ if not _ignore_nsp:
371
+ msg = "process PID not found"
372
+ raise NoSuchProcess(pid, msg=msg)
373
+ else:
374
+ self._gone = True
375
+ # This pair is supposed to identify a Process instance
376
+ # univocally over time (the PID alone is not enough as
377
+ # it might refer to a process whose PID has been reused).
378
+ # This will be used later in __eq__() and is_running().
379
+ self._ident = (self.pid, self._create_time)
380
+
381
+ def __str__(self):
382
+ info = collections.OrderedDict()
383
+ info["pid"] = self.pid
384
+ if self._name:
385
+ info['name'] = self._name
386
+ with self.oneshot():
387
+ try:
388
+ info["name"] = self.name()
389
+ info["status"] = self.status()
390
+ except ZombieProcess:
391
+ info["status"] = "zombie"
392
+ except NoSuchProcess:
393
+ info["status"] = "terminated"
394
+ except AccessDenied:
395
+ pass
396
+ if self._exitcode not in (_SENTINEL, None):
397
+ info["exitcode"] = self._exitcode
398
+ if self._create_time is not None:
399
+ info['started'] = _pprint_secs(self._create_time)
400
+ return "%s.%s(%s)" % (
401
+ self.__class__.__module__,
402
+ self.__class__.__name__,
403
+ ", ".join(["%s=%r" % (k, v) for k, v in info.items()]),
404
+ )
405
+
406
+ __repr__ = __str__
407
+
408
+ def __eq__(self, other):
409
+ # Test for equality with another Process object based
410
+ # on PID and creation time.
411
+ if not isinstance(other, Process):
412
+ return NotImplemented
413
+ if OPENBSD or NETBSD: # pragma: no cover
414
+ # Zombie processes on Open/NetBSD have a creation time of
415
+ # 0.0. This covers the case when a process started normally
416
+ # (so it has a ctime), then it turned into a zombie. It's
417
+ # important to do this because is_running() depends on
418
+ # __eq__.
419
+ pid1, ctime1 = self._ident
420
+ pid2, ctime2 = other._ident
421
+ if pid1 == pid2:
422
+ if ctime1 and not ctime2:
423
+ try:
424
+ return self.status() == STATUS_ZOMBIE
425
+ except Error:
426
+ pass
427
+ return self._ident == other._ident
428
+
429
+ def __ne__(self, other):
430
+ return not self == other
431
+
432
+ def __hash__(self):
433
+ if self._hash is None:
434
+ self._hash = hash(self._ident)
435
+ return self._hash
436
+
437
+ def _raise_if_pid_reused(self):
438
+ """Raises NoSuchProcess in case process PID has been reused."""
439
+ if not self.is_running() and self._pid_reused:
440
+ # We may directly raise NSP in here already if PID is just
441
+ # not running, but I prefer NSP to be raised naturally by
442
+ # the actual Process API call. This way unit tests will tell
443
+ # us if the API is broken (aka don't raise NSP when it
444
+ # should). We also remain consistent with all other "get"
445
+ # APIs which don't use _raise_if_pid_reused().
446
+ msg = "process no longer exists and its PID has been reused"
447
+ raise NoSuchProcess(self.pid, self._name, msg=msg)
448
+
449
+ @property
450
+ def pid(self):
451
+ """The process PID."""
452
+ return self._pid
453
+
454
+ # --- utility methods
455
+
456
+ @contextlib.contextmanager
457
+ def oneshot(self):
458
+ """Utility context manager which considerably speeds up the
459
+ retrieval of multiple process information at the same time.
460
+
461
+ Internally different process info (e.g. name, ppid, uids,
462
+ gids, ...) may be fetched by using the same routine, but
463
+ only one information is returned and the others are discarded.
464
+ When using this context manager the internal routine is
465
+ executed once (in the example below on name()) and the
466
+ other info are cached.
467
+
468
+ The cache is cleared when exiting the context manager block.
469
+ The advice is to use this every time you retrieve more than
470
+ one information about the process. If you're lucky, you'll
471
+ get a hell of a speedup.
472
+
473
+ >>> import psutil
474
+ >>> p = psutil.Process()
475
+ >>> with p.oneshot():
476
+ ... p.name() # collect multiple info
477
+ ... p.cpu_times() # return cached value
478
+ ... p.cpu_percent() # return cached value
479
+ ... p.create_time() # return cached value
480
+ ...
481
+ >>>
482
+ """
483
+ with self._lock:
484
+ if hasattr(self, "_cache"):
485
+ # NOOP: this covers the use case where the user enters the
486
+ # context twice:
487
+ #
488
+ # >>> with p.oneshot():
489
+ # ... with p.oneshot():
490
+ # ...
491
+ #
492
+ # Also, since as_dict() internally uses oneshot()
493
+ # I expect that the code below will be a pretty common
494
+ # "mistake" that the user will make, so let's guard
495
+ # against that:
496
+ #
497
+ # >>> with p.oneshot():
498
+ # ... p.as_dict()
499
+ # ...
500
+ yield
501
+ else:
502
+ try:
503
+ # cached in case cpu_percent() is used
504
+ self.cpu_times.cache_activate(self)
505
+ # cached in case memory_percent() is used
506
+ self.memory_info.cache_activate(self)
507
+ # cached in case parent() is used
508
+ self.ppid.cache_activate(self)
509
+ # cached in case username() is used
510
+ if POSIX:
511
+ self.uids.cache_activate(self)
512
+ # specific implementation cache
513
+ self._proc.oneshot_enter()
514
+ yield
515
+ finally:
516
+ self.cpu_times.cache_deactivate(self)
517
+ self.memory_info.cache_deactivate(self)
518
+ self.ppid.cache_deactivate(self)
519
+ if POSIX:
520
+ self.uids.cache_deactivate(self)
521
+ self._proc.oneshot_exit()
522
+
523
+ def as_dict(self, attrs=None, ad_value=None):
524
+ """Utility method returning process information as a
525
+ hashable dictionary.
526
+ If *attrs* is specified it must be a list of strings
527
+ reflecting available Process class' attribute names
528
+ (e.g. ['cpu_times', 'name']) else all public (read
529
+ only) attributes are assumed.
530
+ *ad_value* is the value which gets assigned in case
531
+ AccessDenied or ZombieProcess exception is raised when
532
+ retrieving that particular process information.
533
+ """
534
+ valid_names = _as_dict_attrnames
535
+ if attrs is not None:
536
+ if not isinstance(attrs, (list, tuple, set, frozenset)):
537
+ msg = "invalid attrs type %s" % type(attrs)
538
+ raise TypeError(msg)
539
+ attrs = set(attrs)
540
+ invalid_names = attrs - valid_names
541
+ if invalid_names:
542
+ msg = "invalid attr name%s %s" % (
543
+ "s" if len(invalid_names) > 1 else "",
544
+ ", ".join(map(repr, invalid_names)),
545
+ )
546
+ raise ValueError(msg)
547
+
548
+ retdict = {}
549
+ ls = attrs or valid_names
550
+ with self.oneshot():
551
+ for name in ls:
552
+ try:
553
+ if name == 'pid':
554
+ ret = self.pid
555
+ else:
556
+ meth = getattr(self, name)
557
+ ret = meth()
558
+ except (AccessDenied, ZombieProcess):
559
+ ret = ad_value
560
+ except NotImplementedError:
561
+ # in case of not implemented functionality (may happen
562
+ # on old or exotic systems) we want to crash only if
563
+ # the user explicitly asked for that particular attr
564
+ if attrs:
565
+ raise
566
+ continue
567
+ retdict[name] = ret
568
+ return retdict
569
+
570
+ def parent(self):
571
+ """Return the parent process as a Process object pre-emptively
572
+ checking whether PID has been reused.
573
+ If no parent is known return None.
574
+ """
575
+ lowest_pid = _LOWEST_PID if _LOWEST_PID is not None else pids()[0]
576
+ if self.pid == lowest_pid:
577
+ return None
578
+ ppid = self.ppid()
579
+ if ppid is not None:
580
+ ctime = self.create_time()
581
+ try:
582
+ parent = Process(ppid)
583
+ if parent.create_time() <= ctime:
584
+ return parent
585
+ # ...else ppid has been reused by another process
586
+ except NoSuchProcess:
587
+ pass
588
+
589
+ def parents(self):
590
+ """Return the parents of this process as a list of Process
591
+ instances. If no parents are known return an empty list.
592
+ """
593
+ parents = []
594
+ proc = self.parent()
595
+ while proc is not None:
596
+ parents.append(proc)
597
+ proc = proc.parent()
598
+ return parents
599
+
600
+ def is_running(self):
601
+ """Return whether this process is running.
602
+ It also checks if PID has been reused by another process in
603
+ which case return False.
604
+ """
605
+ if self._gone or self._pid_reused:
606
+ return False
607
+ try:
608
+ # Checking if PID is alive is not enough as the PID might
609
+ # have been reused by another process: we also want to
610
+ # verify process identity.
611
+ # Process identity / uniqueness over time is guaranteed by
612
+ # (PID + creation time) and that is verified in __eq__.
613
+ self._pid_reused = self != Process(self.pid)
614
+ return not self._pid_reused
615
+ except ZombieProcess:
616
+ # We should never get here as it's already handled in
617
+ # Process.__init__; here just for extra safety.
618
+ return True
619
+ except NoSuchProcess:
620
+ self._gone = True
621
+ return False
622
+
623
+ # --- actual API
624
+
625
+ @memoize_when_activated
626
+ def ppid(self):
627
+ """The process parent PID.
628
+ On Windows the return value is cached after first call.
629
+ """
630
+ # On POSIX we don't want to cache the ppid as it may unexpectedly
631
+ # change to 1 (init) in case this process turns into a zombie:
632
+ # https://github.com/giampaolo/psutil/issues/321
633
+ # http://stackoverflow.com/questions/356722/
634
+
635
+ # XXX should we check creation time here rather than in
636
+ # Process.parent()?
637
+ self._raise_if_pid_reused()
638
+ if POSIX:
639
+ return self._proc.ppid()
640
+ else: # pragma: no cover
641
+ self._ppid = self._ppid or self._proc.ppid()
642
+ return self._ppid
643
+
644
+ def name(self):
645
+ """The process name. The return value is cached after first call."""
646
+ # Process name is only cached on Windows as on POSIX it may
647
+ # change, see:
648
+ # https://github.com/giampaolo/psutil/issues/692
649
+ if WINDOWS and self._name is not None:
650
+ return self._name
651
+ name = self._proc.name()
652
+ if POSIX and len(name) >= 15:
653
+ # On UNIX the name gets truncated to the first 15 characters.
654
+ # If it matches the first part of the cmdline we return that
655
+ # one instead because it's usually more explicative.
656
+ # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
657
+ try:
658
+ cmdline = self.cmdline()
659
+ except (AccessDenied, ZombieProcess):
660
+ # Just pass and return the truncated name: it's better
661
+ # than nothing. Note: there are actual cases where a
662
+ # zombie process can return a name() but not a
663
+ # cmdline(), see:
664
+ # https://github.com/giampaolo/psutil/issues/2239
665
+ pass
666
+ else:
667
+ if cmdline:
668
+ extended_name = os.path.basename(cmdline[0])
669
+ if extended_name.startswith(name):
670
+ name = extended_name
671
+ self._name = name
672
+ self._proc._name = name
673
+ return name
674
+
675
+ def exe(self):
676
+ """The process executable as an absolute path.
677
+ May also be an empty string.
678
+ The return value is cached after first call.
679
+ """
680
+
681
+ def guess_it(fallback):
682
+ # try to guess exe from cmdline[0] in absence of a native
683
+ # exe representation
684
+ cmdline = self.cmdline()
685
+ if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
686
+ exe = cmdline[0] # the possible exe
687
+ # Attempt to guess only in case of an absolute path.
688
+ # It is not safe otherwise as the process might have
689
+ # changed cwd.
690
+ if (
691
+ os.path.isabs(exe)
692
+ and os.path.isfile(exe)
693
+ and os.access(exe, os.X_OK)
694
+ ):
695
+ return exe
696
+ if isinstance(fallback, AccessDenied):
697
+ raise fallback
698
+ return fallback
699
+
700
+ if self._exe is None:
701
+ try:
702
+ exe = self._proc.exe()
703
+ except AccessDenied as err:
704
+ return guess_it(fallback=err)
705
+ else:
706
+ if not exe:
707
+ # underlying implementation can legitimately return an
708
+ # empty string; if that's the case we don't want to
709
+ # raise AD while guessing from the cmdline
710
+ try:
711
+ exe = guess_it(fallback=exe)
712
+ except AccessDenied:
713
+ pass
714
+ self._exe = exe
715
+ return self._exe
716
+
717
+ def cmdline(self):
718
+ """The command line this process has been called with."""
719
+ return self._proc.cmdline()
720
+
721
+ def status(self):
722
+ """The process current status as a STATUS_* constant."""
723
+ try:
724
+ return self._proc.status()
725
+ except ZombieProcess:
726
+ return STATUS_ZOMBIE
727
+
728
+ def username(self):
729
+ """The name of the user that owns the process.
730
+ On UNIX this is calculated by using *real* process uid.
731
+ """
732
+ if POSIX:
733
+ if pwd is None:
734
+ # might happen if python was installed from sources
735
+ msg = "requires pwd module shipped with standard python"
736
+ raise ImportError(msg)
737
+ real_uid = self.uids().real
738
+ try:
739
+ return pwd.getpwuid(real_uid).pw_name
740
+ except KeyError:
741
+ # the uid can't be resolved by the system
742
+ return str(real_uid)
743
+ else:
744
+ return self._proc.username()
745
+
746
+ def create_time(self):
747
+ """The process creation time as a floating point number
748
+ expressed in seconds since the epoch.
749
+ The return value is cached after first call.
750
+ """
751
+ if self._create_time is None:
752
+ self._create_time = self._proc.create_time()
753
+ return self._create_time
754
+
755
+ def cwd(self):
756
+ """Process current working directory as an absolute path."""
757
+ return self._proc.cwd()
758
+
759
+ def nice(self, value=None):
760
+ """Get or set process niceness (priority)."""
761
+ if value is None:
762
+ return self._proc.nice_get()
763
+ else:
764
+ self._raise_if_pid_reused()
765
+ self._proc.nice_set(value)
766
+
767
+ if POSIX:
768
+
769
+ @memoize_when_activated
770
+ def uids(self):
771
+ """Return process UIDs as a (real, effective, saved)
772
+ namedtuple.
773
+ """
774
+ return self._proc.uids()
775
+
776
+ def gids(self):
777
+ """Return process GIDs as a (real, effective, saved)
778
+ namedtuple.
779
+ """
780
+ return self._proc.gids()
781
+
782
+ def terminal(self):
783
+ """The terminal associated with this process, if any,
784
+ else None.
785
+ """
786
+ return self._proc.terminal()
787
+
788
+ def num_fds(self):
789
+ """Return the number of file descriptors opened by this
790
+ process (POSIX only).
791
+ """
792
+ return self._proc.num_fds()
793
+
794
+ # Linux, BSD, AIX and Windows only
795
+ if hasattr(_psplatform.Process, "io_counters"):
796
+
797
+ def io_counters(self):
798
+ """Return process I/O statistics as a
799
+ (read_count, write_count, read_bytes, write_bytes)
800
+ namedtuple.
801
+ Those are the number of read/write calls performed and the
802
+ amount of bytes read and written by the process.
803
+ """
804
+ return self._proc.io_counters()
805
+
806
+ # Linux and Windows
807
+ if hasattr(_psplatform.Process, "ionice_get"):
808
+
809
+ def ionice(self, ioclass=None, value=None):
810
+ """Get or set process I/O niceness (priority).
811
+
812
+ On Linux *ioclass* is one of the IOPRIO_CLASS_* constants.
813
+ *value* is a number which goes from 0 to 7. The higher the
814
+ value, the lower the I/O priority of the process.
815
+
816
+ On Windows only *ioclass* is used and it can be set to 2
817
+ (normal), 1 (low) or 0 (very low).
818
+
819
+ Available on Linux and Windows > Vista only.
820
+ """
821
+ if ioclass is None:
822
+ if value is not None:
823
+ msg = "'ioclass' argument must be specified"
824
+ raise ValueError(msg)
825
+ return self._proc.ionice_get()
826
+ else:
827
+ self._raise_if_pid_reused()
828
+ return self._proc.ionice_set(ioclass, value)
829
+
830
+ # Linux / FreeBSD only
831
+ if hasattr(_psplatform.Process, "rlimit"):
832
+
833
+ def rlimit(self, resource, limits=None):
834
+ """Get or set process resource limits as a (soft, hard)
835
+ tuple.
836
+
837
+ *resource* is one of the RLIMIT_* constants.
838
+ *limits* is supposed to be a (soft, hard) tuple.
839
+
840
+ See "man prlimit" for further info.
841
+ Available on Linux and FreeBSD only.
842
+ """
843
+ if limits is not None:
844
+ self._raise_if_pid_reused()
845
+ return self._proc.rlimit(resource, limits)
846
+
847
+ # Windows, Linux and FreeBSD only
848
+ if hasattr(_psplatform.Process, "cpu_affinity_get"):
849
+
850
+ def cpu_affinity(self, cpus=None):
851
+ """Get or set process CPU affinity.
852
+ If specified, *cpus* must be a list of CPUs for which you
853
+ want to set the affinity (e.g. [0, 1]).
854
+ If an empty list is passed, all egible CPUs are assumed
855
+ (and set).
856
+ (Windows, Linux and BSD only).
857
+ """
858
+ if cpus is None:
859
+ return sorted(set(self._proc.cpu_affinity_get()))
860
+ else:
861
+ self._raise_if_pid_reused()
862
+ if not cpus:
863
+ if hasattr(self._proc, "_get_eligible_cpus"):
864
+ cpus = self._proc._get_eligible_cpus()
865
+ else:
866
+ cpus = tuple(range(len(cpu_times(percpu=True))))
867
+ self._proc.cpu_affinity_set(list(set(cpus)))
868
+
869
+ # Linux, FreeBSD, SunOS
870
+ if hasattr(_psplatform.Process, "cpu_num"):
871
+
872
+ def cpu_num(self):
873
+ """Return what CPU this process is currently running on.
874
+ The returned number should be <= psutil.cpu_count()
875
+ and <= len(psutil.cpu_percent(percpu=True)).
876
+ It may be used in conjunction with
877
+ psutil.cpu_percent(percpu=True) to observe the system
878
+ workload distributed across CPUs.
879
+ """
880
+ return self._proc.cpu_num()
881
+
882
+ # All platforms has it, but maybe not in the future.
883
+ if hasattr(_psplatform.Process, "environ"):
884
+
885
+ def environ(self):
886
+ """The environment variables of the process as a dict. Note: this
887
+ might not reflect changes made after the process started.
888
+ """
889
+ return self._proc.environ()
890
+
891
+ if WINDOWS:
892
+
893
+ def num_handles(self):
894
+ """Return the number of handles opened by this process
895
+ (Windows only).
896
+ """
897
+ return self._proc.num_handles()
898
+
899
+ def num_ctx_switches(self):
900
+ """Return the number of voluntary and involuntary context
901
+ switches performed by this process.
902
+ """
903
+ return self._proc.num_ctx_switches()
904
+
905
+ def num_threads(self):
906
+ """Return the number of threads used by this process."""
907
+ return self._proc.num_threads()
908
+
909
+ if hasattr(_psplatform.Process, "threads"):
910
+
911
+ def threads(self):
912
+ """Return threads opened by process as a list of
913
+ (id, user_time, system_time) namedtuples representing
914
+ thread id and thread CPU times (user/system).
915
+ On OpenBSD this method requires root access.
916
+ """
917
+ return self._proc.threads()
918
+
919
+ def children(self, recursive=False):
920
+ """Return the children of this process as a list of Process
921
+ instances, pre-emptively checking whether PID has been reused.
922
+ If *recursive* is True return all the parent descendants.
923
+
924
+ Example (A == this process):
925
+
926
+ A ─┐
927
+
928
+ ├─ B (child) ─┐
929
+ │ └─ X (grandchild) ─┐
930
+ │ └─ Y (great grandchild)
931
+ ├─ C (child)
932
+ └─ D (child)
933
+
934
+ >>> import psutil
935
+ >>> p = psutil.Process()
936
+ >>> p.children()
937
+ B, C, D
938
+ >>> p.children(recursive=True)
939
+ B, X, Y, C, D
940
+
941
+ Note that in the example above if process X disappears
942
+ process Y won't be listed as the reference to process A
943
+ is lost.
944
+ """
945
+ self._raise_if_pid_reused()
946
+ ppid_map = _ppid_map()
947
+ ret = []
948
+ if not recursive:
949
+ for pid, ppid in ppid_map.items():
950
+ if ppid == self.pid:
951
+ try:
952
+ child = Process(pid)
953
+ # if child happens to be older than its parent
954
+ # (self) it means child's PID has been reused
955
+ if self.create_time() <= child.create_time():
956
+ ret.append(child)
957
+ except (NoSuchProcess, ZombieProcess):
958
+ pass
959
+ else:
960
+ # Construct a {pid: [child pids]} dict
961
+ reverse_ppid_map = collections.defaultdict(list)
962
+ for pid, ppid in ppid_map.items():
963
+ reverse_ppid_map[ppid].append(pid)
964
+ # Recursively traverse that dict, starting from self.pid,
965
+ # such that we only call Process() on actual children
966
+ seen = set()
967
+ stack = [self.pid]
968
+ while stack:
969
+ pid = stack.pop()
970
+ if pid in seen:
971
+ # Since pids can be reused while the ppid_map is
972
+ # constructed, there may be rare instances where
973
+ # there's a cycle in the recorded process "tree".
974
+ continue
975
+ seen.add(pid)
976
+ for child_pid in reverse_ppid_map[pid]:
977
+ try:
978
+ child = Process(child_pid)
979
+ # if child happens to be older than its parent
980
+ # (self) it means child's PID has been reused
981
+ intime = self.create_time() <= child.create_time()
982
+ if intime:
983
+ ret.append(child)
984
+ stack.append(child_pid)
985
+ except (NoSuchProcess, ZombieProcess):
986
+ pass
987
+ return ret
988
+
989
+ def cpu_percent(self, interval=None):
990
+ """Return a float representing the current process CPU
991
+ utilization as a percentage.
992
+
993
+ When *interval* is 0.0 or None (default) compares process times
994
+ to system CPU times elapsed since last call, returning
995
+ immediately (non-blocking). That means that the first time
996
+ this is called it will return a meaningful 0.0 value.
997
+
998
+ When *interval* is > 0.0 compares process times to system CPU
999
+ times elapsed before and after the interval (blocking).
1000
+
1001
+ In this case is recommended for accuracy that this function
1002
+ be called with at least 0.1 seconds between calls.
1003
+
1004
+ A value > 100.0 can be returned in case of processes running
1005
+ multiple threads on different CPU cores.
1006
+
1007
+ The returned value is explicitly NOT split evenly between
1008
+ all available logical CPUs. This means that a busy loop process
1009
+ running on a system with 2 logical CPUs will be reported as
1010
+ having 100% CPU utilization instead of 50%.
1011
+
1012
+ Examples:
1013
+
1014
+ >>> import psutil
1015
+ >>> p = psutil.Process(os.getpid())
1016
+ >>> # blocking
1017
+ >>> p.cpu_percent(interval=1)
1018
+ 2.0
1019
+ >>> # non-blocking (percentage since last call)
1020
+ >>> p.cpu_percent(interval=None)
1021
+ 2.9
1022
+ >>>
1023
+ """
1024
+ blocking = interval is not None and interval > 0.0
1025
+ if interval is not None and interval < 0:
1026
+ msg = "interval is not positive (got %r)" % interval
1027
+ raise ValueError(msg)
1028
+ num_cpus = cpu_count() or 1
1029
+
1030
+ def timer():
1031
+ return _timer() * num_cpus
1032
+
1033
+ if blocking:
1034
+ st1 = timer()
1035
+ pt1 = self._proc.cpu_times()
1036
+ time.sleep(interval)
1037
+ st2 = timer()
1038
+ pt2 = self._proc.cpu_times()
1039
+ else:
1040
+ st1 = self._last_sys_cpu_times
1041
+ pt1 = self._last_proc_cpu_times
1042
+ st2 = timer()
1043
+ pt2 = self._proc.cpu_times()
1044
+ if st1 is None or pt1 is None:
1045
+ self._last_sys_cpu_times = st2
1046
+ self._last_proc_cpu_times = pt2
1047
+ return 0.0
1048
+
1049
+ delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system)
1050
+ delta_time = st2 - st1
1051
+ # reset values for next call in case of interval == None
1052
+ self._last_sys_cpu_times = st2
1053
+ self._last_proc_cpu_times = pt2
1054
+
1055
+ try:
1056
+ # This is the utilization split evenly between all CPUs.
1057
+ # E.g. a busy loop process on a 2-CPU-cores system at this
1058
+ # point is reported as 50% instead of 100%.
1059
+ overall_cpus_percent = (delta_proc / delta_time) * 100
1060
+ except ZeroDivisionError:
1061
+ # interval was too low
1062
+ return 0.0
1063
+ else:
1064
+ # Note 1:
1065
+ # in order to emulate "top" we multiply the value for the num
1066
+ # of CPU cores. This way the busy process will be reported as
1067
+ # having 100% (or more) usage.
1068
+ #
1069
+ # Note 2:
1070
+ # taskmgr.exe on Windows differs in that it will show 50%
1071
+ # instead.
1072
+ #
1073
+ # Note 3:
1074
+ # a percentage > 100 is legitimate as it can result from a
1075
+ # process with multiple threads running on different CPU
1076
+ # cores (top does the same), see:
1077
+ # http://stackoverflow.com/questions/1032357
1078
+ # https://github.com/giampaolo/psutil/issues/474
1079
+ single_cpu_percent = overall_cpus_percent * num_cpus
1080
+ return round(single_cpu_percent, 1)
1081
+
1082
+ @memoize_when_activated
1083
+ def cpu_times(self):
1084
+ """Return a (user, system, children_user, children_system)
1085
+ namedtuple representing the accumulated process time, in
1086
+ seconds.
1087
+ This is similar to os.times() but per-process.
1088
+ On macOS and Windows children_user and children_system are
1089
+ always set to 0.
1090
+ """
1091
+ return self._proc.cpu_times()
1092
+
1093
+ @memoize_when_activated
1094
+ def memory_info(self):
1095
+ """Return a namedtuple with variable fields depending on the
1096
+ platform, representing memory information about the process.
1097
+
1098
+ The "portable" fields available on all platforms are `rss` and `vms`.
1099
+
1100
+ All numbers are expressed in bytes.
1101
+ """
1102
+ return self._proc.memory_info()
1103
+
1104
+ @_common.deprecated_method(replacement="memory_info")
1105
+ def memory_info_ex(self):
1106
+ return self.memory_info()
1107
+
1108
+ def memory_full_info(self):
1109
+ """This method returns the same information as memory_info(),
1110
+ plus, on some platform (Linux, macOS, Windows), also provides
1111
+ additional metrics (USS, PSS and swap).
1112
+ The additional metrics provide a better representation of actual
1113
+ process memory usage.
1114
+
1115
+ Namely USS is the memory which is unique to a process and which
1116
+ would be freed if the process was terminated right now.
1117
+
1118
+ It does so by passing through the whole process address.
1119
+ As such it usually requires higher user privileges than
1120
+ memory_info() and is considerably slower.
1121
+ """
1122
+ return self._proc.memory_full_info()
1123
+
1124
+ def memory_percent(self, memtype="rss"):
1125
+ """Compare process memory to total physical system memory and
1126
+ calculate process memory utilization as a percentage.
1127
+ *memtype* argument is a string that dictates what type of
1128
+ process memory you want to compare against (defaults to "rss").
1129
+ The list of available strings can be obtained like this:
1130
+
1131
+ >>> psutil.Process().memory_info()._fields
1132
+ ('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss')
1133
+ """
1134
+ valid_types = list(_psplatform.pfullmem._fields)
1135
+ if memtype not in valid_types:
1136
+ msg = "invalid memtype %r; valid types are %r" % (
1137
+ memtype,
1138
+ tuple(valid_types),
1139
+ )
1140
+ raise ValueError(msg)
1141
+ fun = (
1142
+ self.memory_info
1143
+ if memtype in _psplatform.pmem._fields
1144
+ else self.memory_full_info
1145
+ )
1146
+ metrics = fun()
1147
+ value = getattr(metrics, memtype)
1148
+
1149
+ # use cached value if available
1150
+ total_phymem = _TOTAL_PHYMEM or virtual_memory().total
1151
+ if not total_phymem > 0:
1152
+ # we should never get here
1153
+ msg = (
1154
+ "can't calculate process memory percent because total physical"
1155
+ " system memory is not positive (%r)" % (total_phymem)
1156
+ )
1157
+ raise ValueError(msg)
1158
+ return (value / float(total_phymem)) * 100
1159
+
1160
+ if hasattr(_psplatform.Process, "memory_maps"):
1161
+
1162
+ def memory_maps(self, grouped=True):
1163
+ """Return process' mapped memory regions as a list of namedtuples
1164
+ whose fields are variable depending on the platform.
1165
+
1166
+ If *grouped* is True the mapped regions with the same 'path'
1167
+ are grouped together and the different memory fields are summed.
1168
+
1169
+ If *grouped* is False every mapped region is shown as a single
1170
+ entity and the namedtuple will also include the mapped region's
1171
+ address space ('addr') and permission set ('perms').
1172
+ """
1173
+ it = self._proc.memory_maps()
1174
+ if grouped:
1175
+ d = {}
1176
+ for tupl in it:
1177
+ path = tupl[2]
1178
+ nums = tupl[3:]
1179
+ try:
1180
+ d[path] = map(lambda x, y: x + y, d[path], nums)
1181
+ except KeyError:
1182
+ d[path] = nums
1183
+ nt = _psplatform.pmmap_grouped
1184
+ return [nt(path, *d[path]) for path in d] # NOQA
1185
+ else:
1186
+ nt = _psplatform.pmmap_ext
1187
+ return [nt(*x) for x in it]
1188
+
1189
+ def open_files(self):
1190
+ """Return files opened by process as a list of
1191
+ (path, fd) namedtuples including the absolute file name
1192
+ and file descriptor number.
1193
+ """
1194
+ return self._proc.open_files()
1195
+
1196
+ def connections(self, kind='inet'):
1197
+ """Return socket connections opened by process as a list of
1198
+ (fd, family, type, laddr, raddr, status) namedtuples.
1199
+ The *kind* parameter filters for connections that match the
1200
+ following criteria:
1201
+
1202
+ +------------+----------------------------------------------------+
1203
+ | Kind Value | Connections using |
1204
+ +------------+----------------------------------------------------+
1205
+ | inet | IPv4 and IPv6 |
1206
+ | inet4 | IPv4 |
1207
+ | inet6 | IPv6 |
1208
+ | tcp | TCP |
1209
+ | tcp4 | TCP over IPv4 |
1210
+ | tcp6 | TCP over IPv6 |
1211
+ | udp | UDP |
1212
+ | udp4 | UDP over IPv4 |
1213
+ | udp6 | UDP over IPv6 |
1214
+ | unix | UNIX socket (both UDP and TCP protocols) |
1215
+ | all | the sum of all the possible families and protocols |
1216
+ +------------+----------------------------------------------------+
1217
+ """
1218
+ return self._proc.connections(kind)
1219
+
1220
+ # --- signals
1221
+
1222
+ if POSIX:
1223
+
1224
+ def _send_signal(self, sig):
1225
+ assert not self.pid < 0, self.pid
1226
+ self._raise_if_pid_reused()
1227
+ if self.pid == 0:
1228
+ # see "man 2 kill"
1229
+ msg = (
1230
+ "preventing sending signal to process with PID 0 as it "
1231
+ "would affect every process in the process group of the "
1232
+ "calling process (os.getpid()) instead of PID 0"
1233
+ )
1234
+ raise ValueError(msg)
1235
+ try:
1236
+ os.kill(self.pid, sig)
1237
+ except ProcessLookupError:
1238
+ if OPENBSD and pid_exists(self.pid):
1239
+ # We do this because os.kill() lies in case of
1240
+ # zombie processes.
1241
+ raise ZombieProcess(self.pid, self._name, self._ppid)
1242
+ else:
1243
+ self._gone = True
1244
+ raise NoSuchProcess(self.pid, self._name)
1245
+ except PermissionError:
1246
+ raise AccessDenied(self.pid, self._name)
1247
+
1248
+ def send_signal(self, sig):
1249
+ """Send a signal *sig* to process pre-emptively checking
1250
+ whether PID has been reused (see signal module constants) .
1251
+ On Windows only SIGTERM is valid and is treated as an alias
1252
+ for kill().
1253
+ """
1254
+ if POSIX:
1255
+ self._send_signal(sig)
1256
+ else: # pragma: no cover
1257
+ self._raise_if_pid_reused()
1258
+ if sig != signal.SIGTERM and not self.is_running():
1259
+ msg = "process no longer exists"
1260
+ raise NoSuchProcess(self.pid, self._name, msg=msg)
1261
+ self._proc.send_signal(sig)
1262
+
1263
+ def suspend(self):
1264
+ """Suspend process execution with SIGSTOP pre-emptively checking
1265
+ whether PID has been reused.
1266
+ On Windows this has the effect of suspending all process threads.
1267
+ """
1268
+ if POSIX:
1269
+ self._send_signal(signal.SIGSTOP)
1270
+ else: # pragma: no cover
1271
+ self._raise_if_pid_reused()
1272
+ self._proc.suspend()
1273
+
1274
+ def resume(self):
1275
+ """Resume process execution with SIGCONT pre-emptively checking
1276
+ whether PID has been reused.
1277
+ On Windows this has the effect of resuming all process threads.
1278
+ """
1279
+ if POSIX:
1280
+ self._send_signal(signal.SIGCONT)
1281
+ else: # pragma: no cover
1282
+ self._raise_if_pid_reused()
1283
+ self._proc.resume()
1284
+
1285
+ def terminate(self):
1286
+ """Terminate the process with SIGTERM pre-emptively checking
1287
+ whether PID has been reused.
1288
+ On Windows this is an alias for kill().
1289
+ """
1290
+ if POSIX:
1291
+ self._send_signal(signal.SIGTERM)
1292
+ else: # pragma: no cover
1293
+ self._raise_if_pid_reused()
1294
+ self._proc.kill()
1295
+
1296
+ def kill(self):
1297
+ """Kill the current process with SIGKILL pre-emptively checking
1298
+ whether PID has been reused.
1299
+ """
1300
+ if POSIX:
1301
+ self._send_signal(signal.SIGKILL)
1302
+ else: # pragma: no cover
1303
+ self._raise_if_pid_reused()
1304
+ self._proc.kill()
1305
+
1306
+ def wait(self, timeout=None):
1307
+ """Wait for process to terminate and, if process is a children
1308
+ of os.getpid(), also return its exit code, else None.
1309
+ On Windows there's no such limitation (exit code is always
1310
+ returned).
1311
+
1312
+ If the process is already terminated immediately return None
1313
+ instead of raising NoSuchProcess.
1314
+
1315
+ If *timeout* (in seconds) is specified and process is still
1316
+ alive raise TimeoutExpired.
1317
+
1318
+ To wait for multiple Process(es) use psutil.wait_procs().
1319
+ """
1320
+ if timeout is not None and not timeout >= 0:
1321
+ msg = "timeout must be a positive integer"
1322
+ raise ValueError(msg)
1323
+ if self._exitcode is not _SENTINEL:
1324
+ return self._exitcode
1325
+ self._exitcode = self._proc.wait(timeout)
1326
+ return self._exitcode
1327
+
1328
+
1329
+ # The valid attr names which can be processed by Process.as_dict().
1330
+ # fmt: off
1331
+ _as_dict_attrnames = set(
1332
+ [x for x in dir(Process) if not x.startswith('_') and x not in
1333
+ {'send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
1334
+ 'is_running', 'as_dict', 'parent', 'parents', 'children', 'rlimit',
1335
+ 'memory_info_ex', 'oneshot'}])
1336
+ # fmt: on
1337
+
1338
+
1339
+ # =====================================================================
1340
+ # --- Popen class
1341
+ # =====================================================================
1342
+
1343
+
1344
+ class Popen(Process):
1345
+ """Same as subprocess.Popen, but in addition it provides all
1346
+ psutil.Process methods in a single class.
1347
+ For the following methods which are common to both classes, psutil
1348
+ implementation takes precedence:
1349
+
1350
+ * send_signal()
1351
+ * terminate()
1352
+ * kill()
1353
+
1354
+ This is done in order to avoid killing another process in case its
1355
+ PID has been reused, fixing BPO-6973.
1356
+
1357
+ >>> import psutil
1358
+ >>> from subprocess import PIPE
1359
+ >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE)
1360
+ >>> p.name()
1361
+ 'python'
1362
+ >>> p.uids()
1363
+ user(real=1000, effective=1000, saved=1000)
1364
+ >>> p.username()
1365
+ 'giampaolo'
1366
+ >>> p.communicate()
1367
+ ('hi', None)
1368
+ >>> p.terminate()
1369
+ >>> p.wait(timeout=2)
1370
+ 0
1371
+ >>>
1372
+ """
1373
+
1374
+ def __init__(self, *args, **kwargs):
1375
+ # Explicitly avoid to raise NoSuchProcess in case the process
1376
+ # spawned by subprocess.Popen terminates too quickly, see:
1377
+ # https://github.com/giampaolo/psutil/issues/193
1378
+ self.__subproc = subprocess.Popen(*args, **kwargs)
1379
+ self._init(self.__subproc.pid, _ignore_nsp=True)
1380
+
1381
+ def __dir__(self):
1382
+ return sorted(set(dir(Popen) + dir(subprocess.Popen)))
1383
+
1384
+ def __enter__(self):
1385
+ if hasattr(self.__subproc, '__enter__'):
1386
+ self.__subproc.__enter__()
1387
+ return self
1388
+
1389
+ def __exit__(self, *args, **kwargs):
1390
+ if hasattr(self.__subproc, '__exit__'):
1391
+ return self.__subproc.__exit__(*args, **kwargs)
1392
+ else:
1393
+ if self.stdout:
1394
+ self.stdout.close()
1395
+ if self.stderr:
1396
+ self.stderr.close()
1397
+ try:
1398
+ # Flushing a BufferedWriter may raise an error.
1399
+ if self.stdin:
1400
+ self.stdin.close()
1401
+ finally:
1402
+ # Wait for the process to terminate, to avoid zombies.
1403
+ self.wait()
1404
+
1405
+ def __getattribute__(self, name):
1406
+ try:
1407
+ return object.__getattribute__(self, name)
1408
+ except AttributeError:
1409
+ try:
1410
+ return object.__getattribute__(self.__subproc, name)
1411
+ except AttributeError:
1412
+ msg = "%s instance has no attribute '%s'" % (
1413
+ self.__class__.__name__,
1414
+ name,
1415
+ )
1416
+ raise AttributeError(msg)
1417
+
1418
+ def wait(self, timeout=None):
1419
+ if self.__subproc.returncode is not None:
1420
+ return self.__subproc.returncode
1421
+ ret = super(Popen, self).wait(timeout) # noqa
1422
+ self.__subproc.returncode = ret
1423
+ return ret
1424
+
1425
+
1426
+ # =====================================================================
1427
+ # --- system processes related functions
1428
+ # =====================================================================
1429
+
1430
+
1431
+ def pids():
1432
+ """Return a list of current running PIDs."""
1433
+ global _LOWEST_PID
1434
+ ret = sorted(_psplatform.pids())
1435
+ _LOWEST_PID = ret[0]
1436
+ return ret
1437
+
1438
+
1439
+ def pid_exists(pid):
1440
+ """Return True if given PID exists in the current process list.
1441
+ This is faster than doing "pid in psutil.pids()" and
1442
+ should be preferred.
1443
+ """
1444
+ if pid < 0:
1445
+ return False
1446
+ elif pid == 0 and POSIX:
1447
+ # On POSIX we use os.kill() to determine PID existence.
1448
+ # According to "man 2 kill" PID 0 has a special meaning
1449
+ # though: it refers to <<every process in the process
1450
+ # group of the calling process>> and that is not we want
1451
+ # to do here.
1452
+ return pid in pids()
1453
+ else:
1454
+ return _psplatform.pid_exists(pid)
1455
+
1456
+
1457
+ _pmap = {}
1458
+
1459
+
1460
+ def process_iter(attrs=None, ad_value=None):
1461
+ """Return a generator yielding a Process instance for all
1462
+ running processes.
1463
+
1464
+ Every new Process instance is only created once and then cached
1465
+ into an internal table which is updated every time this is used.
1466
+
1467
+ Cached Process instances are checked for identity so that you're
1468
+ safe in case a PID has been reused by another process, in which
1469
+ case the cached instance is updated.
1470
+
1471
+ The sorting order in which processes are yielded is based on
1472
+ their PIDs.
1473
+
1474
+ *attrs* and *ad_value* have the same meaning as in
1475
+ Process.as_dict(). If *attrs* is specified as_dict() is called
1476
+ and the resulting dict is stored as a 'info' attribute attached
1477
+ to returned Process instance.
1478
+ If *attrs* is an empty list it will retrieve all process info
1479
+ (slow).
1480
+ """
1481
+ global _pmap
1482
+
1483
+ def add(pid):
1484
+ proc = Process(pid)
1485
+ if attrs is not None:
1486
+ proc.info = proc.as_dict(attrs=attrs, ad_value=ad_value)
1487
+ pmap[proc.pid] = proc
1488
+ return proc
1489
+
1490
+ def remove(pid):
1491
+ pmap.pop(pid, None)
1492
+
1493
+ pmap = _pmap.copy()
1494
+ a = set(pids())
1495
+ b = set(pmap.keys())
1496
+ new_pids = a - b
1497
+ gone_pids = b - a
1498
+ for pid in gone_pids:
1499
+ remove(pid)
1500
+ try:
1501
+ ls = sorted(list(pmap.items()) + list(dict.fromkeys(new_pids).items()))
1502
+ for pid, proc in ls:
1503
+ try:
1504
+ if proc is None: # new process
1505
+ yield add(pid)
1506
+ else:
1507
+ # use is_running() to check whether PID has been
1508
+ # reused by another process in which case yield a
1509
+ # new Process instance
1510
+ if proc.is_running():
1511
+ if attrs is not None:
1512
+ proc.info = proc.as_dict(
1513
+ attrs=attrs, ad_value=ad_value
1514
+ )
1515
+ yield proc
1516
+ else:
1517
+ yield add(pid)
1518
+ except NoSuchProcess:
1519
+ remove(pid)
1520
+ except AccessDenied:
1521
+ # Process creation time can't be determined hence there's
1522
+ # no way to tell whether the pid of the cached process
1523
+ # has been reused. Just return the cached version.
1524
+ if proc is None and pid in pmap:
1525
+ try:
1526
+ yield pmap[pid]
1527
+ except KeyError:
1528
+ # If we get here it is likely that 2 threads were
1529
+ # using process_iter().
1530
+ pass
1531
+ else:
1532
+ raise
1533
+ finally:
1534
+ _pmap = pmap
1535
+
1536
+
1537
+ def wait_procs(procs, timeout=None, callback=None):
1538
+ """Convenience function which waits for a list of processes to
1539
+ terminate.
1540
+
1541
+ Return a (gone, alive) tuple indicating which processes
1542
+ are gone and which ones are still alive.
1543
+
1544
+ The gone ones will have a new *returncode* attribute indicating
1545
+ process exit status (may be None).
1546
+
1547
+ *callback* is a function which gets called every time a process
1548
+ terminates (a Process instance is passed as callback argument).
1549
+
1550
+ Function will return as soon as all processes terminate or when
1551
+ *timeout* occurs.
1552
+ Differently from Process.wait() it will not raise TimeoutExpired if
1553
+ *timeout* occurs.
1554
+
1555
+ Typical use case is:
1556
+
1557
+ - send SIGTERM to a list of processes
1558
+ - give them some time to terminate
1559
+ - send SIGKILL to those ones which are still alive
1560
+
1561
+ Example:
1562
+
1563
+ >>> def on_terminate(proc):
1564
+ ... print("process {} terminated".format(proc))
1565
+ ...
1566
+ >>> for p in procs:
1567
+ ... p.terminate()
1568
+ ...
1569
+ >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
1570
+ >>> for p in alive:
1571
+ ... p.kill()
1572
+ """
1573
+
1574
+ def check_gone(proc, timeout):
1575
+ try:
1576
+ returncode = proc.wait(timeout=timeout)
1577
+ except TimeoutExpired:
1578
+ pass
1579
+ except _SubprocessTimeoutExpired:
1580
+ pass
1581
+ else:
1582
+ if returncode is not None or not proc.is_running():
1583
+ # Set new Process instance attribute.
1584
+ proc.returncode = returncode
1585
+ gone.add(proc)
1586
+ if callback is not None:
1587
+ callback(proc)
1588
+
1589
+ if timeout is not None and not timeout >= 0:
1590
+ msg = "timeout must be a positive integer, got %s" % timeout
1591
+ raise ValueError(msg)
1592
+ gone = set()
1593
+ alive = set(procs)
1594
+ if callback is not None and not callable(callback):
1595
+ msg = "callback %r is not a callable" % callback
1596
+ raise TypeError(msg)
1597
+ if timeout is not None:
1598
+ deadline = _timer() + timeout
1599
+
1600
+ while alive:
1601
+ if timeout is not None and timeout <= 0:
1602
+ break
1603
+ for proc in alive:
1604
+ # Make sure that every complete iteration (all processes)
1605
+ # will last max 1 sec.
1606
+ # We do this because we don't want to wait too long on a
1607
+ # single process: in case it terminates too late other
1608
+ # processes may disappear in the meantime and their PID
1609
+ # reused.
1610
+ max_timeout = 1.0 / len(alive)
1611
+ if timeout is not None:
1612
+ timeout = min((deadline - _timer()), max_timeout)
1613
+ if timeout <= 0:
1614
+ break
1615
+ check_gone(proc, timeout)
1616
+ else:
1617
+ check_gone(proc, max_timeout)
1618
+ alive = alive - gone
1619
+
1620
+ if alive:
1621
+ # Last attempt over processes survived so far.
1622
+ # timeout == 0 won't make this function wait any further.
1623
+ for proc in alive:
1624
+ check_gone(proc, 0)
1625
+ alive = alive - gone
1626
+
1627
+ return (list(gone), list(alive))
1628
+
1629
+
1630
+ # =====================================================================
1631
+ # --- CPU related functions
1632
+ # =====================================================================
1633
+
1634
+
1635
+ def cpu_count(logical=True):
1636
+ """Return the number of logical CPUs in the system (same as
1637
+ os.cpu_count() in Python 3.4).
1638
+
1639
+ If *logical* is False return the number of physical cores only
1640
+ (e.g. hyper thread CPUs are excluded).
1641
+
1642
+ Return None if undetermined.
1643
+
1644
+ The return value is cached after first call.
1645
+ If desired cache can be cleared like this:
1646
+
1647
+ >>> psutil.cpu_count.cache_clear()
1648
+ """
1649
+ if logical:
1650
+ ret = _psplatform.cpu_count_logical()
1651
+ else:
1652
+ ret = _psplatform.cpu_count_cores()
1653
+ if ret is not None and ret < 1:
1654
+ ret = None
1655
+ return ret
1656
+
1657
+
1658
+ def cpu_times(percpu=False):
1659
+ """Return system-wide CPU times as a namedtuple.
1660
+ Every CPU time represents the seconds the CPU has spent in the
1661
+ given mode. The namedtuple's fields availability varies depending on the
1662
+ platform:
1663
+
1664
+ - user
1665
+ - system
1666
+ - idle
1667
+ - nice (UNIX)
1668
+ - iowait (Linux)
1669
+ - irq (Linux, FreeBSD)
1670
+ - softirq (Linux)
1671
+ - steal (Linux >= 2.6.11)
1672
+ - guest (Linux >= 2.6.24)
1673
+ - guest_nice (Linux >= 3.2.0)
1674
+
1675
+ When *percpu* is True return a list of namedtuples for each CPU.
1676
+ First element of the list refers to first CPU, second element
1677
+ to second CPU and so on.
1678
+ The order of the list is consistent across calls.
1679
+ """
1680
+ if not percpu:
1681
+ return _psplatform.cpu_times()
1682
+ else:
1683
+ return _psplatform.per_cpu_times()
1684
+
1685
+
1686
+ try:
1687
+ _last_cpu_times = {threading.current_thread().ident: cpu_times()}
1688
+ except Exception: # noqa: BLE001
1689
+ # Don't want to crash at import time.
1690
+ _last_cpu_times = {}
1691
+
1692
+ try:
1693
+ _last_per_cpu_times = {
1694
+ threading.current_thread().ident: cpu_times(percpu=True)
1695
+ }
1696
+ except Exception: # noqa: BLE001
1697
+ # Don't want to crash at import time.
1698
+ _last_per_cpu_times = {}
1699
+
1700
+
1701
+ def _cpu_tot_time(times):
1702
+ """Given a cpu_time() ntuple calculates the total CPU time
1703
+ (including idle time).
1704
+ """
1705
+ tot = sum(times)
1706
+ if LINUX:
1707
+ # On Linux guest times are already accounted in "user" or
1708
+ # "nice" times, so we subtract them from total.
1709
+ # Htop does the same. References:
1710
+ # https://github.com/giampaolo/psutil/pull/940
1711
+ # http://unix.stackexchange.com/questions/178045
1712
+ # https://github.com/torvalds/linux/blob/
1713
+ # 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
1714
+ # cputime.c#L158
1715
+ tot -= getattr(times, "guest", 0) # Linux 2.6.24+
1716
+ tot -= getattr(times, "guest_nice", 0) # Linux 3.2.0+
1717
+ return tot
1718
+
1719
+
1720
+ def _cpu_busy_time(times):
1721
+ """Given a cpu_time() ntuple calculates the busy CPU time.
1722
+ We do so by subtracting all idle CPU times.
1723
+ """
1724
+ busy = _cpu_tot_time(times)
1725
+ busy -= times.idle
1726
+ # Linux: "iowait" is time during which the CPU does not do anything
1727
+ # (waits for IO to complete). On Linux IO wait is *not* accounted
1728
+ # in "idle" time so we subtract it. Htop does the same.
1729
+ # References:
1730
+ # https://github.com/torvalds/linux/blob/
1731
+ # 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
1732
+ busy -= getattr(times, "iowait", 0)
1733
+ return busy
1734
+
1735
+
1736
+ def _cpu_times_deltas(t1, t2):
1737
+ assert t1._fields == t2._fields, (t1, t2)
1738
+ field_deltas = []
1739
+ for field in _psplatform.scputimes._fields:
1740
+ field_delta = getattr(t2, field) - getattr(t1, field)
1741
+ # CPU times are always supposed to increase over time
1742
+ # or at least remain the same and that's because time
1743
+ # cannot go backwards.
1744
+ # Surprisingly sometimes this might not be the case (at
1745
+ # least on Windows and Linux), see:
1746
+ # https://github.com/giampaolo/psutil/issues/392
1747
+ # https://github.com/giampaolo/psutil/issues/645
1748
+ # https://github.com/giampaolo/psutil/issues/1210
1749
+ # Trim negative deltas to zero to ignore decreasing fields.
1750
+ # top does the same. Reference:
1751
+ # https://gitlab.com/procps-ng/procps/blob/v3.3.12/top/top.c#L5063
1752
+ field_delta = max(0, field_delta)
1753
+ field_deltas.append(field_delta)
1754
+ return _psplatform.scputimes(*field_deltas)
1755
+
1756
+
1757
+ def cpu_percent(interval=None, percpu=False):
1758
+ """Return a float representing the current system-wide CPU
1759
+ utilization as a percentage.
1760
+
1761
+ When *interval* is > 0.0 compares system CPU times elapsed before
1762
+ and after the interval (blocking).
1763
+
1764
+ When *interval* is 0.0 or None compares system CPU times elapsed
1765
+ since last call or module import, returning immediately (non
1766
+ blocking). That means the first time this is called it will
1767
+ return a meaningless 0.0 value which you should ignore.
1768
+ In this case is recommended for accuracy that this function be
1769
+ called with at least 0.1 seconds between calls.
1770
+
1771
+ When *percpu* is True returns a list of floats representing the
1772
+ utilization as a percentage for each CPU.
1773
+ First element of the list refers to first CPU, second element
1774
+ to second CPU and so on.
1775
+ The order of the list is consistent across calls.
1776
+
1777
+ Examples:
1778
+
1779
+ >>> # blocking, system-wide
1780
+ >>> psutil.cpu_percent(interval=1)
1781
+ 2.0
1782
+ >>>
1783
+ >>> # blocking, per-cpu
1784
+ >>> psutil.cpu_percent(interval=1, percpu=True)
1785
+ [2.0, 1.0]
1786
+ >>>
1787
+ >>> # non-blocking (percentage since last call)
1788
+ >>> psutil.cpu_percent(interval=None)
1789
+ 2.9
1790
+ >>>
1791
+ """
1792
+ tid = threading.current_thread().ident
1793
+ blocking = interval is not None and interval > 0.0
1794
+ if interval is not None and interval < 0:
1795
+ msg = "interval is not positive (got %r)" % interval
1796
+ raise ValueError(msg)
1797
+
1798
+ def calculate(t1, t2):
1799
+ times_delta = _cpu_times_deltas(t1, t2)
1800
+ all_delta = _cpu_tot_time(times_delta)
1801
+ busy_delta = _cpu_busy_time(times_delta)
1802
+
1803
+ try:
1804
+ busy_perc = (busy_delta / all_delta) * 100
1805
+ except ZeroDivisionError:
1806
+ return 0.0
1807
+ else:
1808
+ return round(busy_perc, 1)
1809
+
1810
+ # system-wide usage
1811
+ if not percpu:
1812
+ if blocking:
1813
+ t1 = cpu_times()
1814
+ time.sleep(interval)
1815
+ else:
1816
+ t1 = _last_cpu_times.get(tid) or cpu_times()
1817
+ _last_cpu_times[tid] = cpu_times()
1818
+ return calculate(t1, _last_cpu_times[tid])
1819
+ # per-cpu usage
1820
+ else:
1821
+ ret = []
1822
+ if blocking:
1823
+ tot1 = cpu_times(percpu=True)
1824
+ time.sleep(interval)
1825
+ else:
1826
+ tot1 = _last_per_cpu_times.get(tid) or cpu_times(percpu=True)
1827
+ _last_per_cpu_times[tid] = cpu_times(percpu=True)
1828
+ for t1, t2 in zip(tot1, _last_per_cpu_times[tid]):
1829
+ ret.append(calculate(t1, t2))
1830
+ return ret
1831
+
1832
+
1833
+ # Use a separate dict for cpu_times_percent(), so it's independent from
1834
+ # cpu_percent() and they can both be used within the same program.
1835
+ _last_cpu_times_2 = _last_cpu_times.copy()
1836
+ _last_per_cpu_times_2 = _last_per_cpu_times.copy()
1837
+
1838
+
1839
+ def cpu_times_percent(interval=None, percpu=False):
1840
+ """Same as cpu_percent() but provides utilization percentages
1841
+ for each specific CPU time as is returned by cpu_times().
1842
+ For instance, on Linux we'll get:
1843
+
1844
+ >>> cpu_times_percent()
1845
+ cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
1846
+ irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
1847
+ >>>
1848
+
1849
+ *interval* and *percpu* arguments have the same meaning as in
1850
+ cpu_percent().
1851
+ """
1852
+ tid = threading.current_thread().ident
1853
+ blocking = interval is not None and interval > 0.0
1854
+ if interval is not None and interval < 0:
1855
+ msg = "interval is not positive (got %r)" % interval
1856
+ raise ValueError(msg)
1857
+
1858
+ def calculate(t1, t2):
1859
+ nums = []
1860
+ times_delta = _cpu_times_deltas(t1, t2)
1861
+ all_delta = _cpu_tot_time(times_delta)
1862
+ # "scale" is the value to multiply each delta with to get percentages.
1863
+ # We use "max" to avoid division by zero (if all_delta is 0, then all
1864
+ # fields are 0 so percentages will be 0 too. all_delta cannot be a
1865
+ # fraction because cpu times are integers)
1866
+ scale = 100.0 / max(1, all_delta)
1867
+ for field_delta in times_delta:
1868
+ field_perc = field_delta * scale
1869
+ field_perc = round(field_perc, 1)
1870
+ # make sure we don't return negative values or values over 100%
1871
+ field_perc = min(max(0.0, field_perc), 100.0)
1872
+ nums.append(field_perc)
1873
+ return _psplatform.scputimes(*nums)
1874
+
1875
+ # system-wide usage
1876
+ if not percpu:
1877
+ if blocking:
1878
+ t1 = cpu_times()
1879
+ time.sleep(interval)
1880
+ else:
1881
+ t1 = _last_cpu_times_2.get(tid) or cpu_times()
1882
+ _last_cpu_times_2[tid] = cpu_times()
1883
+ return calculate(t1, _last_cpu_times_2[tid])
1884
+ # per-cpu usage
1885
+ else:
1886
+ ret = []
1887
+ if blocking:
1888
+ tot1 = cpu_times(percpu=True)
1889
+ time.sleep(interval)
1890
+ else:
1891
+ tot1 = _last_per_cpu_times_2.get(tid) or cpu_times(percpu=True)
1892
+ _last_per_cpu_times_2[tid] = cpu_times(percpu=True)
1893
+ for t1, t2 in zip(tot1, _last_per_cpu_times_2[tid]):
1894
+ ret.append(calculate(t1, t2))
1895
+ return ret
1896
+
1897
+
1898
+ def cpu_stats():
1899
+ """Return CPU statistics."""
1900
+ return _psplatform.cpu_stats()
1901
+
1902
+
1903
+ if hasattr(_psplatform, "cpu_freq"):
1904
+
1905
+ def cpu_freq(percpu=False):
1906
+ """Return CPU frequency as a namedtuple including current,
1907
+ min and max frequency expressed in Mhz.
1908
+
1909
+ If *percpu* is True and the system supports per-cpu frequency
1910
+ retrieval (Linux only) a list of frequencies is returned for
1911
+ each CPU. If not a list with one element is returned.
1912
+ """
1913
+ ret = _psplatform.cpu_freq()
1914
+ if percpu:
1915
+ return ret
1916
+ else:
1917
+ num_cpus = float(len(ret))
1918
+ if num_cpus == 0:
1919
+ return None
1920
+ elif num_cpus == 1:
1921
+ return ret[0]
1922
+ else:
1923
+ currs, mins, maxs = 0.0, 0.0, 0.0
1924
+ set_none = False
1925
+ for cpu in ret:
1926
+ currs += cpu.current
1927
+ # On Linux if /proc/cpuinfo is used min/max are set
1928
+ # to None.
1929
+ if LINUX and cpu.min is None:
1930
+ set_none = True
1931
+ continue
1932
+ mins += cpu.min
1933
+ maxs += cpu.max
1934
+
1935
+ current = currs / num_cpus
1936
+
1937
+ if set_none:
1938
+ min_ = max_ = None
1939
+ else:
1940
+ min_ = mins / num_cpus
1941
+ max_ = maxs / num_cpus
1942
+
1943
+ return _common.scpufreq(current, min_, max_)
1944
+
1945
+ __all__.append("cpu_freq")
1946
+
1947
+
1948
+ if hasattr(os, "getloadavg") or hasattr(_psplatform, "getloadavg"):
1949
+ # Perform this hasattr check once on import time to either use the
1950
+ # platform based code or proxy straight from the os module.
1951
+ if hasattr(os, "getloadavg"):
1952
+ getloadavg = os.getloadavg
1953
+ else:
1954
+ getloadavg = _psplatform.getloadavg
1955
+
1956
+ __all__.append("getloadavg")
1957
+
1958
+
1959
+ # =====================================================================
1960
+ # --- system memory related functions
1961
+ # =====================================================================
1962
+
1963
+
1964
+ def virtual_memory():
1965
+ """Return statistics about system memory usage as a namedtuple
1966
+ including the following fields, expressed in bytes:
1967
+
1968
+ - total:
1969
+ total physical memory available.
1970
+
1971
+ - available:
1972
+ the memory that can be given instantly to processes without the
1973
+ system going into swap.
1974
+ This is calculated by summing different memory values depending
1975
+ on the platform and it is supposed to be used to monitor actual
1976
+ memory usage in a cross platform fashion.
1977
+
1978
+ - percent:
1979
+ the percentage usage calculated as (total - available) / total * 100
1980
+
1981
+ - used:
1982
+ memory used, calculated differently depending on the platform and
1983
+ designed for informational purposes only:
1984
+ macOS: active + wired
1985
+ BSD: active + wired + cached
1986
+ Linux: total - free
1987
+
1988
+ - free:
1989
+ memory not being used at all (zeroed) that is readily available;
1990
+ note that this doesn't reflect the actual memory available
1991
+ (use 'available' instead)
1992
+
1993
+ Platform-specific fields:
1994
+
1995
+ - active (UNIX):
1996
+ memory currently in use or very recently used, and so it is in RAM.
1997
+
1998
+ - inactive (UNIX):
1999
+ memory that is marked as not used.
2000
+
2001
+ - buffers (BSD, Linux):
2002
+ cache for things like file system metadata.
2003
+
2004
+ - cached (BSD, macOS):
2005
+ cache for various things.
2006
+
2007
+ - wired (macOS, BSD):
2008
+ memory that is marked to always stay in RAM. It is never moved to disk.
2009
+
2010
+ - shared (BSD):
2011
+ memory that may be simultaneously accessed by multiple processes.
2012
+
2013
+ The sum of 'used' and 'available' does not necessarily equal total.
2014
+ On Windows 'available' and 'free' are the same.
2015
+ """
2016
+ global _TOTAL_PHYMEM
2017
+ ret = _psplatform.virtual_memory()
2018
+ # cached for later use in Process.memory_percent()
2019
+ _TOTAL_PHYMEM = ret.total
2020
+ return ret
2021
+
2022
+
2023
+ def swap_memory():
2024
+ """Return system swap memory statistics as a namedtuple including
2025
+ the following fields:
2026
+
2027
+ - total: total swap memory in bytes
2028
+ - used: used swap memory in bytes
2029
+ - free: free swap memory in bytes
2030
+ - percent: the percentage usage
2031
+ - sin: no. of bytes the system has swapped in from disk (cumulative)
2032
+ - sout: no. of bytes the system has swapped out from disk (cumulative)
2033
+
2034
+ 'sin' and 'sout' on Windows are meaningless and always set to 0.
2035
+ """
2036
+ return _psplatform.swap_memory()
2037
+
2038
+
2039
+ # =====================================================================
2040
+ # --- disks/paritions related functions
2041
+ # =====================================================================
2042
+
2043
+
2044
+ def disk_usage(path):
2045
+ """Return disk usage statistics about the given *path* as a
2046
+ namedtuple including total, used and free space expressed in bytes
2047
+ plus the percentage usage.
2048
+ """
2049
+ return _psplatform.disk_usage(path)
2050
+
2051
+
2052
+ def disk_partitions(all=False):
2053
+ """Return mounted partitions as a list of
2054
+ (device, mountpoint, fstype, opts) namedtuple.
2055
+ 'opts' field is a raw string separated by commas indicating mount
2056
+ options which may vary depending on the platform.
2057
+
2058
+ If *all* parameter is False return physical devices only and ignore
2059
+ all others.
2060
+ """
2061
+
2062
+ def pathconf(path, name):
2063
+ try:
2064
+ return os.pathconf(path, name)
2065
+ except (OSError, AttributeError):
2066
+ pass
2067
+
2068
+ ret = _psplatform.disk_partitions(all)
2069
+ if POSIX:
2070
+ new = []
2071
+ for item in ret:
2072
+ nt = item._replace(
2073
+ maxfile=pathconf(item.mountpoint, 'PC_NAME_MAX'),
2074
+ maxpath=pathconf(item.mountpoint, 'PC_PATH_MAX'),
2075
+ )
2076
+ new.append(nt)
2077
+ return new
2078
+ else:
2079
+ return ret
2080
+
2081
+
2082
+ def disk_io_counters(perdisk=False, nowrap=True):
2083
+ """Return system disk I/O statistics as a namedtuple including
2084
+ the following fields:
2085
+
2086
+ - read_count: number of reads
2087
+ - write_count: number of writes
2088
+ - read_bytes: number of bytes read
2089
+ - write_bytes: number of bytes written
2090
+ - read_time: time spent reading from disk (in ms)
2091
+ - write_time: time spent writing to disk (in ms)
2092
+
2093
+ Platform specific:
2094
+
2095
+ - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms)
2096
+ - read_merged_count (Linux): number of merged reads
2097
+ - write_merged_count (Linux): number of merged writes
2098
+
2099
+ If *perdisk* is True return the same information for every
2100
+ physical disk installed on the system as a dictionary
2101
+ with partition names as the keys and the namedtuple
2102
+ described above as the values.
2103
+
2104
+ If *nowrap* is True it detects and adjust the numbers which overflow
2105
+ and wrap (restart from 0) and add "old value" to "new value" so that
2106
+ the returned numbers will always be increasing or remain the same,
2107
+ but never decrease.
2108
+ "disk_io_counters.cache_clear()" can be used to invalidate the
2109
+ cache.
2110
+
2111
+ On recent Windows versions 'diskperf -y' command may need to be
2112
+ executed first otherwise this function won't find any disk.
2113
+ """
2114
+ kwargs = dict(perdisk=perdisk) if LINUX else {}
2115
+ rawdict = _psplatform.disk_io_counters(**kwargs)
2116
+ if not rawdict:
2117
+ return {} if perdisk else None
2118
+ if nowrap:
2119
+ rawdict = _wrap_numbers(rawdict, 'psutil.disk_io_counters')
2120
+ nt = getattr(_psplatform, "sdiskio", _common.sdiskio)
2121
+ if perdisk:
2122
+ for disk, fields in rawdict.items():
2123
+ rawdict[disk] = nt(*fields)
2124
+ return rawdict
2125
+ else:
2126
+ return nt(*(sum(x) for x in zip(*rawdict.values())))
2127
+
2128
+
2129
+ disk_io_counters.cache_clear = functools.partial(
2130
+ _wrap_numbers.cache_clear, 'psutil.disk_io_counters'
2131
+ )
2132
+ disk_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
2133
+
2134
+
2135
+ # =====================================================================
2136
+ # --- network related functions
2137
+ # =====================================================================
2138
+
2139
+
2140
+ def net_io_counters(pernic=False, nowrap=True):
2141
+ """Return network I/O statistics as a namedtuple including
2142
+ the following fields:
2143
+
2144
+ - bytes_sent: number of bytes sent
2145
+ - bytes_recv: number of bytes received
2146
+ - packets_sent: number of packets sent
2147
+ - packets_recv: number of packets received
2148
+ - errin: total number of errors while receiving
2149
+ - errout: total number of errors while sending
2150
+ - dropin: total number of incoming packets which were dropped
2151
+ - dropout: total number of outgoing packets which were dropped
2152
+ (always 0 on macOS and BSD)
2153
+
2154
+ If *pernic* is True return the same information for every
2155
+ network interface installed on the system as a dictionary
2156
+ with network interface names as the keys and the namedtuple
2157
+ described above as the values.
2158
+
2159
+ If *nowrap* is True it detects and adjust the numbers which overflow
2160
+ and wrap (restart from 0) and add "old value" to "new value" so that
2161
+ the returned numbers will always be increasing or remain the same,
2162
+ but never decrease.
2163
+ "net_io_counters.cache_clear()" can be used to invalidate the
2164
+ cache.
2165
+ """
2166
+ rawdict = _psplatform.net_io_counters()
2167
+ if not rawdict:
2168
+ return {} if pernic else None
2169
+ if nowrap:
2170
+ rawdict = _wrap_numbers(rawdict, 'psutil.net_io_counters')
2171
+ if pernic:
2172
+ for nic, fields in rawdict.items():
2173
+ rawdict[nic] = _common.snetio(*fields)
2174
+ return rawdict
2175
+ else:
2176
+ return _common.snetio(*[sum(x) for x in zip(*rawdict.values())])
2177
+
2178
+
2179
+ net_io_counters.cache_clear = functools.partial(
2180
+ _wrap_numbers.cache_clear, 'psutil.net_io_counters'
2181
+ )
2182
+ net_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
2183
+
2184
+
2185
+ def net_connections(kind='inet'):
2186
+ """Return system-wide socket connections as a list of
2187
+ (fd, family, type, laddr, raddr, status, pid) namedtuples.
2188
+ In case of limited privileges 'fd' and 'pid' may be set to -1
2189
+ and None respectively.
2190
+ The *kind* parameter filters for connections that fit the
2191
+ following criteria:
2192
+
2193
+ +------------+----------------------------------------------------+
2194
+ | Kind Value | Connections using |
2195
+ +------------+----------------------------------------------------+
2196
+ | inet | IPv4 and IPv6 |
2197
+ | inet4 | IPv4 |
2198
+ | inet6 | IPv6 |
2199
+ | tcp | TCP |
2200
+ | tcp4 | TCP over IPv4 |
2201
+ | tcp6 | TCP over IPv6 |
2202
+ | udp | UDP |
2203
+ | udp4 | UDP over IPv4 |
2204
+ | udp6 | UDP over IPv6 |
2205
+ | unix | UNIX socket (both UDP and TCP protocols) |
2206
+ | all | the sum of all the possible families and protocols |
2207
+ +------------+----------------------------------------------------+
2208
+
2209
+ On macOS this function requires root privileges.
2210
+ """
2211
+ return _psplatform.net_connections(kind)
2212
+
2213
+
2214
+ def net_if_addrs():
2215
+ """Return the addresses associated to each NIC (network interface
2216
+ card) installed on the system as a dictionary whose keys are the
2217
+ NIC names and value is a list of namedtuples for each address
2218
+ assigned to the NIC. Each namedtuple includes 5 fields:
2219
+
2220
+ - family: can be either socket.AF_INET, socket.AF_INET6 or
2221
+ psutil.AF_LINK, which refers to a MAC address.
2222
+ - address: is the primary address and it is always set.
2223
+ - netmask: and 'broadcast' and 'ptp' may be None.
2224
+ - ptp: stands for "point to point" and references the
2225
+ destination address on a point to point interface
2226
+ (typically a VPN).
2227
+ - broadcast: and *ptp* are mutually exclusive.
2228
+
2229
+ Note: you can have more than one address of the same family
2230
+ associated with each interface.
2231
+ """
2232
+ has_enums = _PY3
2233
+ if has_enums:
2234
+ import socket
2235
+ rawlist = _psplatform.net_if_addrs()
2236
+ rawlist.sort(key=lambda x: x[1]) # sort by family
2237
+ ret = collections.defaultdict(list)
2238
+ for name, fam, addr, mask, broadcast, ptp in rawlist:
2239
+ if has_enums:
2240
+ try:
2241
+ fam = socket.AddressFamily(fam)
2242
+ except ValueError:
2243
+ if WINDOWS and fam == -1:
2244
+ fam = _psplatform.AF_LINK
2245
+ elif (
2246
+ hasattr(_psplatform, "AF_LINK")
2247
+ and fam == _psplatform.AF_LINK
2248
+ ):
2249
+ # Linux defines AF_LINK as an alias for AF_PACKET.
2250
+ # We re-set the family here so that repr(family)
2251
+ # will show AF_LINK rather than AF_PACKET
2252
+ fam = _psplatform.AF_LINK
2253
+ if fam == _psplatform.AF_LINK:
2254
+ # The underlying C function may return an incomplete MAC
2255
+ # address in which case we fill it with null bytes, see:
2256
+ # https://github.com/giampaolo/psutil/issues/786
2257
+ separator = ":" if POSIX else "-"
2258
+ while addr.count(separator) < 5:
2259
+ addr += "%s00" % separator
2260
+ ret[name].append(_common.snicaddr(fam, addr, mask, broadcast, ptp))
2261
+ return dict(ret)
2262
+
2263
+
2264
+ def net_if_stats():
2265
+ """Return information about each NIC (network interface card)
2266
+ installed on the system as a dictionary whose keys are the
2267
+ NIC names and value is a namedtuple with the following fields:
2268
+
2269
+ - isup: whether the interface is up (bool)
2270
+ - duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or
2271
+ NIC_DUPLEX_UNKNOWN
2272
+ - speed: the NIC speed expressed in mega bits (MB); if it can't
2273
+ be determined (e.g. 'localhost') it will be set to 0.
2274
+ - mtu: the maximum transmission unit expressed in bytes.
2275
+ """
2276
+ return _psplatform.net_if_stats()
2277
+
2278
+
2279
+ # =====================================================================
2280
+ # --- sensors
2281
+ # =====================================================================
2282
+
2283
+
2284
+ # Linux, macOS
2285
+ if hasattr(_psplatform, "sensors_temperatures"):
2286
+
2287
+ def sensors_temperatures(fahrenheit=False):
2288
+ """Return hardware temperatures. Each entry is a namedtuple
2289
+ representing a certain hardware sensor (it may be a CPU, an
2290
+ hard disk or something else, depending on the OS and its
2291
+ configuration).
2292
+ All temperatures are expressed in celsius unless *fahrenheit*
2293
+ is set to True.
2294
+ """
2295
+
2296
+ def convert(n):
2297
+ if n is not None:
2298
+ return (float(n) * 9 / 5) + 32 if fahrenheit else n
2299
+
2300
+ ret = collections.defaultdict(list)
2301
+ rawdict = _psplatform.sensors_temperatures()
2302
+
2303
+ for name, values in rawdict.items():
2304
+ while values:
2305
+ label, current, high, critical = values.pop(0)
2306
+ current = convert(current)
2307
+ high = convert(high)
2308
+ critical = convert(critical)
2309
+
2310
+ if high and not critical:
2311
+ critical = high
2312
+ elif critical and not high:
2313
+ high = critical
2314
+
2315
+ ret[name].append(
2316
+ _common.shwtemp(label, current, high, critical)
2317
+ )
2318
+
2319
+ return dict(ret)
2320
+
2321
+ __all__.append("sensors_temperatures")
2322
+
2323
+
2324
+ # Linux
2325
+ if hasattr(_psplatform, "sensors_fans"):
2326
+
2327
+ def sensors_fans():
2328
+ """Return fans speed. Each entry is a namedtuple
2329
+ representing a certain hardware sensor.
2330
+ All speed are expressed in RPM (rounds per minute).
2331
+ """
2332
+ return _psplatform.sensors_fans()
2333
+
2334
+ __all__.append("sensors_fans")
2335
+
2336
+
2337
+ # Linux, Windows, FreeBSD, macOS
2338
+ if hasattr(_psplatform, "sensors_battery"):
2339
+
2340
+ def sensors_battery():
2341
+ """Return battery information. If no battery is installed
2342
+ returns None.
2343
+
2344
+ - percent: battery power left as a percentage.
2345
+ - secsleft: a rough approximation of how many seconds are left
2346
+ before the battery runs out of power. May be
2347
+ POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED.
2348
+ - power_plugged: True if the AC power cable is connected.
2349
+ """
2350
+ return _psplatform.sensors_battery()
2351
+
2352
+ __all__.append("sensors_battery")
2353
+
2354
+
2355
+ # =====================================================================
2356
+ # --- other system related functions
2357
+ # =====================================================================
2358
+
2359
+
2360
+ def boot_time():
2361
+ """Return the system boot time expressed in seconds since the epoch."""
2362
+ # Note: we are not caching this because it is subject to
2363
+ # system clock updates.
2364
+ return _psplatform.boot_time()
2365
+
2366
+
2367
+ def users():
2368
+ """Return users currently connected on the system as a list of
2369
+ namedtuples including the following fields.
2370
+
2371
+ - user: the name of the user
2372
+ - terminal: the tty or pseudo-tty associated with the user, if any.
2373
+ - host: the host name associated with the entry, if any.
2374
+ - started: the creation time as a floating point number expressed in
2375
+ seconds since the epoch.
2376
+ """
2377
+ return _psplatform.users()
2378
+
2379
+
2380
+ # =====================================================================
2381
+ # --- Windows services
2382
+ # =====================================================================
2383
+
2384
+
2385
+ if WINDOWS:
2386
+
2387
+ def win_service_iter():
2388
+ """Return a generator yielding a WindowsService instance for all
2389
+ Windows services installed.
2390
+ """
2391
+ return _psplatform.win_service_iter()
2392
+
2393
+ def win_service_get(name):
2394
+ """Get a Windows service by *name*.
2395
+ Raise NoSuchProcess if no service with such name exists.
2396
+ """
2397
+ return _psplatform.win_service_get(name)
2398
+
2399
+
2400
+ # =====================================================================
2401
+
2402
+
2403
+ def _set_debug(value):
2404
+ """Enable or disable PSUTIL_DEBUG option, which prints debugging
2405
+ messages to stderr.
2406
+ """
2407
+ import psutil._common
2408
+
2409
+ psutil._common.PSUTIL_DEBUG = bool(value)
2410
+ _psplatform.cext.set_debug(bool(value))
2411
+
2412
+
2413
+ def test(): # pragma: no cover
2414
+ from ._common import bytes2human
2415
+ from ._compat import get_terminal_size
2416
+
2417
+ today_day = datetime.date.today()
2418
+ # fmt: off
2419
+ templ = "%-10s %5s %5s %7s %7s %5s %6s %6s %6s %s"
2420
+ attrs = ['pid', 'memory_percent', 'name', 'cmdline', 'cpu_times',
2421
+ 'create_time', 'memory_info', 'status', 'nice', 'username']
2422
+ print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "NICE", # NOQA
2423
+ "STATUS", "START", "TIME", "CMDLINE"))
2424
+ # fmt: on
2425
+ for p in process_iter(attrs, ad_value=None):
2426
+ if p.info['create_time']:
2427
+ ctime = datetime.datetime.fromtimestamp(p.info['create_time'])
2428
+ if ctime.date() == today_day:
2429
+ ctime = ctime.strftime("%H:%M")
2430
+ else:
2431
+ ctime = ctime.strftime("%b%d")
2432
+ else:
2433
+ ctime = ''
2434
+ if p.info['cpu_times']:
2435
+ cputime = time.strftime(
2436
+ "%M:%S", time.localtime(sum(p.info['cpu_times']))
2437
+ )
2438
+ else:
2439
+ cputime = ''
2440
+
2441
+ user = p.info['username'] or ''
2442
+ if not user and POSIX:
2443
+ try:
2444
+ user = p.uids()[0]
2445
+ except Error:
2446
+ pass
2447
+ if user and WINDOWS and '\\' in user:
2448
+ user = user.split('\\')[1]
2449
+ user = user[:9]
2450
+ vms = (
2451
+ bytes2human(p.info['memory_info'].vms)
2452
+ if p.info['memory_info'] is not None
2453
+ else ''
2454
+ )
2455
+ rss = (
2456
+ bytes2human(p.info['memory_info'].rss)
2457
+ if p.info['memory_info'] is not None
2458
+ else ''
2459
+ )
2460
+ memp = (
2461
+ round(p.info['memory_percent'], 1)
2462
+ if p.info['memory_percent'] is not None
2463
+ else ''
2464
+ )
2465
+ nice = int(p.info['nice']) if p.info['nice'] else ''
2466
+ if p.info['cmdline']:
2467
+ cmdline = ' '.join(p.info['cmdline'])
2468
+ else:
2469
+ cmdline = p.info['name']
2470
+ status = p.info['status'][:5] if p.info['status'] else ''
2471
+
2472
+ line = templ % (
2473
+ user[:10],
2474
+ p.info['pid'],
2475
+ memp,
2476
+ vms,
2477
+ rss,
2478
+ nice,
2479
+ status,
2480
+ ctime,
2481
+ cputime,
2482
+ cmdline,
2483
+ )
2484
+ print(line[: get_terminal_size()[0]]) # NOQA
2485
+
2486
+
2487
+ del memoize_when_activated, division
2488
+ if sys.version_info[0] < 3:
2489
+ del num, x # noqa
2490
+
2491
+ if __name__ == "__main__":
2492
+ test()
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (64 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_common.cpython-310.pyc ADDED
Binary file (22.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_compat.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_psaix.cpython-310.pyc ADDED
Binary file (15.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_psbsd.cpython-310.pyc ADDED
Binary file (20.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_pslinux.cpython-310.pyc ADDED
Binary file (53.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_psosx.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_psposix.cpython-310.pyc ADDED
Binary file (4.64 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_pssunos.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/__pycache__/_pswindows.cpython-310.pyc ADDED
Binary file (29 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/_common.py ADDED
@@ -0,0 +1,983 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """Common objects shared by __init__.py and _ps*.py modules."""
6
+
7
+ # Note: this module is imported by setup.py so it should not import
8
+ # psutil or third-party modules.
9
+
10
+ from __future__ import division
11
+ from __future__ import print_function
12
+
13
+ import collections
14
+ import contextlib
15
+ import errno
16
+ import functools
17
+ import os
18
+ import socket
19
+ import stat
20
+ import sys
21
+ import threading
22
+ import warnings
23
+ from collections import namedtuple
24
+ from socket import AF_INET
25
+ from socket import SOCK_DGRAM
26
+ from socket import SOCK_STREAM
27
+
28
+
29
+ try:
30
+ from socket import AF_INET6
31
+ except ImportError:
32
+ AF_INET6 = None
33
+ try:
34
+ from socket import AF_UNIX
35
+ except ImportError:
36
+ AF_UNIX = None
37
+
38
+
39
+ # can't take it from _common.py as this script is imported by setup.py
40
+ PY3 = sys.version_info[0] >= 3
41
+ if PY3:
42
+ import enum
43
+ else:
44
+ enum = None
45
+
46
+
47
+ PSUTIL_DEBUG = bool(os.getenv('PSUTIL_DEBUG'))
48
+ _DEFAULT = object()
49
+
50
+ # fmt: off
51
+ __all__ = [
52
+ # OS constants
53
+ 'FREEBSD', 'BSD', 'LINUX', 'NETBSD', 'OPENBSD', 'MACOS', 'OSX', 'POSIX',
54
+ 'SUNOS', 'WINDOWS',
55
+ # connection constants
56
+ 'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED',
57
+ 'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN',
58
+ 'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT',
59
+ # net constants
60
+ 'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN',
61
+ # process status constants
62
+ 'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED',
63
+ 'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_SUSPENDED',
64
+ 'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKE_KILL',
65
+ 'STATUS_WAKING', 'STATUS_ZOMBIE', 'STATUS_PARKED',
66
+ # other constants
67
+ 'ENCODING', 'ENCODING_ERRS', 'AF_INET6',
68
+ # named tuples
69
+ 'pconn', 'pcputimes', 'pctxsw', 'pgids', 'pio', 'pionice', 'popenfile',
70
+ 'pthread', 'puids', 'sconn', 'scpustats', 'sdiskio', 'sdiskpart',
71
+ 'sdiskusage', 'snetio', 'snicaddr', 'snicstats', 'sswap', 'suser',
72
+ # utility functions
73
+ 'conn_tmap', 'deprecated_method', 'isfile_strict', 'memoize',
74
+ 'parse_environ_block', 'path_exists_strict', 'usage_percent',
75
+ 'supports_ipv6', 'sockfam_to_enum', 'socktype_to_enum', "wrap_numbers",
76
+ 'open_text', 'open_binary', 'cat', 'bcat',
77
+ 'bytes2human', 'conn_to_ntuple', 'debug',
78
+ # shell utils
79
+ 'hilite', 'term_supports_colors', 'print_color',
80
+ ]
81
+ # fmt: on
82
+
83
+
84
+ # ===================================================================
85
+ # --- OS constants
86
+ # ===================================================================
87
+
88
+
89
+ POSIX = os.name == "posix"
90
+ WINDOWS = os.name == "nt"
91
+ LINUX = sys.platform.startswith("linux")
92
+ MACOS = sys.platform.startswith("darwin")
93
+ OSX = MACOS # deprecated alias
94
+ FREEBSD = sys.platform.startswith(("freebsd", "midnightbsd"))
95
+ OPENBSD = sys.platform.startswith("openbsd")
96
+ NETBSD = sys.platform.startswith("netbsd")
97
+ BSD = FREEBSD or OPENBSD or NETBSD
98
+ SUNOS = sys.platform.startswith(("sunos", "solaris"))
99
+ AIX = sys.platform.startswith("aix")
100
+
101
+
102
+ # ===================================================================
103
+ # --- API constants
104
+ # ===================================================================
105
+
106
+
107
+ # Process.status()
108
+ STATUS_RUNNING = "running"
109
+ STATUS_SLEEPING = "sleeping"
110
+ STATUS_DISK_SLEEP = "disk-sleep"
111
+ STATUS_STOPPED = "stopped"
112
+ STATUS_TRACING_STOP = "tracing-stop"
113
+ STATUS_ZOMBIE = "zombie"
114
+ STATUS_DEAD = "dead"
115
+ STATUS_WAKE_KILL = "wake-kill"
116
+ STATUS_WAKING = "waking"
117
+ STATUS_IDLE = "idle" # Linux, macOS, FreeBSD
118
+ STATUS_LOCKED = "locked" # FreeBSD
119
+ STATUS_WAITING = "waiting" # FreeBSD
120
+ STATUS_SUSPENDED = "suspended" # NetBSD
121
+ STATUS_PARKED = "parked" # Linux
122
+
123
+ # Process.connections() and psutil.net_connections()
124
+ CONN_ESTABLISHED = "ESTABLISHED"
125
+ CONN_SYN_SENT = "SYN_SENT"
126
+ CONN_SYN_RECV = "SYN_RECV"
127
+ CONN_FIN_WAIT1 = "FIN_WAIT1"
128
+ CONN_FIN_WAIT2 = "FIN_WAIT2"
129
+ CONN_TIME_WAIT = "TIME_WAIT"
130
+ CONN_CLOSE = "CLOSE"
131
+ CONN_CLOSE_WAIT = "CLOSE_WAIT"
132
+ CONN_LAST_ACK = "LAST_ACK"
133
+ CONN_LISTEN = "LISTEN"
134
+ CONN_CLOSING = "CLOSING"
135
+ CONN_NONE = "NONE"
136
+
137
+ # net_if_stats()
138
+ if enum is None:
139
+ NIC_DUPLEX_FULL = 2
140
+ NIC_DUPLEX_HALF = 1
141
+ NIC_DUPLEX_UNKNOWN = 0
142
+ else:
143
+
144
+ class NicDuplex(enum.IntEnum):
145
+ NIC_DUPLEX_FULL = 2
146
+ NIC_DUPLEX_HALF = 1
147
+ NIC_DUPLEX_UNKNOWN = 0
148
+
149
+ globals().update(NicDuplex.__members__)
150
+
151
+ # sensors_battery()
152
+ if enum is None:
153
+ POWER_TIME_UNKNOWN = -1
154
+ POWER_TIME_UNLIMITED = -2
155
+ else:
156
+
157
+ class BatteryTime(enum.IntEnum):
158
+ POWER_TIME_UNKNOWN = -1
159
+ POWER_TIME_UNLIMITED = -2
160
+
161
+ globals().update(BatteryTime.__members__)
162
+
163
+ # --- others
164
+
165
+ ENCODING = sys.getfilesystemencoding()
166
+ if not PY3:
167
+ ENCODING_ERRS = "replace"
168
+ else:
169
+ try:
170
+ ENCODING_ERRS = sys.getfilesystemencodeerrors() # py 3.6
171
+ except AttributeError:
172
+ ENCODING_ERRS = "surrogateescape" if POSIX else "replace"
173
+
174
+
175
+ # ===================================================================
176
+ # --- namedtuples
177
+ # ===================================================================
178
+
179
+ # --- for system functions
180
+
181
+ # fmt: off
182
+ # psutil.swap_memory()
183
+ sswap = namedtuple('sswap', ['total', 'used', 'free', 'percent', 'sin',
184
+ 'sout'])
185
+ # psutil.disk_usage()
186
+ sdiskusage = namedtuple('sdiskusage', ['total', 'used', 'free', 'percent'])
187
+ # psutil.disk_io_counters()
188
+ sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
189
+ 'read_bytes', 'write_bytes',
190
+ 'read_time', 'write_time'])
191
+ # psutil.disk_partitions()
192
+ sdiskpart = namedtuple('sdiskpart', ['device', 'mountpoint', 'fstype', 'opts',
193
+ 'maxfile', 'maxpath'])
194
+ # psutil.net_io_counters()
195
+ snetio = namedtuple('snetio', ['bytes_sent', 'bytes_recv',
196
+ 'packets_sent', 'packets_recv',
197
+ 'errin', 'errout',
198
+ 'dropin', 'dropout'])
199
+ # psutil.users()
200
+ suser = namedtuple('suser', ['name', 'terminal', 'host', 'started', 'pid'])
201
+ # psutil.net_connections()
202
+ sconn = namedtuple('sconn', ['fd', 'family', 'type', 'laddr', 'raddr',
203
+ 'status', 'pid'])
204
+ # psutil.net_if_addrs()
205
+ snicaddr = namedtuple('snicaddr',
206
+ ['family', 'address', 'netmask', 'broadcast', 'ptp'])
207
+ # psutil.net_if_stats()
208
+ snicstats = namedtuple('snicstats',
209
+ ['isup', 'duplex', 'speed', 'mtu', 'flags'])
210
+ # psutil.cpu_stats()
211
+ scpustats = namedtuple(
212
+ 'scpustats', ['ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls'])
213
+ # psutil.cpu_freq()
214
+ scpufreq = namedtuple('scpufreq', ['current', 'min', 'max'])
215
+ # psutil.sensors_temperatures()
216
+ shwtemp = namedtuple(
217
+ 'shwtemp', ['label', 'current', 'high', 'critical'])
218
+ # psutil.sensors_battery()
219
+ sbattery = namedtuple('sbattery', ['percent', 'secsleft', 'power_plugged'])
220
+ # psutil.sensors_fans()
221
+ sfan = namedtuple('sfan', ['label', 'current'])
222
+ # fmt: on
223
+
224
+ # --- for Process methods
225
+
226
+ # psutil.Process.cpu_times()
227
+ pcputimes = namedtuple(
228
+ 'pcputimes', ['user', 'system', 'children_user', 'children_system']
229
+ )
230
+ # psutil.Process.open_files()
231
+ popenfile = namedtuple('popenfile', ['path', 'fd'])
232
+ # psutil.Process.threads()
233
+ pthread = namedtuple('pthread', ['id', 'user_time', 'system_time'])
234
+ # psutil.Process.uids()
235
+ puids = namedtuple('puids', ['real', 'effective', 'saved'])
236
+ # psutil.Process.gids()
237
+ pgids = namedtuple('pgids', ['real', 'effective', 'saved'])
238
+ # psutil.Process.io_counters()
239
+ pio = namedtuple(
240
+ 'pio', ['read_count', 'write_count', 'read_bytes', 'write_bytes']
241
+ )
242
+ # psutil.Process.ionice()
243
+ pionice = namedtuple('pionice', ['ioclass', 'value'])
244
+ # psutil.Process.ctx_switches()
245
+ pctxsw = namedtuple('pctxsw', ['voluntary', 'involuntary'])
246
+ # psutil.Process.connections()
247
+ pconn = namedtuple(
248
+ 'pconn', ['fd', 'family', 'type', 'laddr', 'raddr', 'status']
249
+ )
250
+
251
+ # psutil.connections() and psutil.Process.connections()
252
+ addr = namedtuple('addr', ['ip', 'port'])
253
+
254
+
255
+ # ===================================================================
256
+ # --- Process.connections() 'kind' parameter mapping
257
+ # ===================================================================
258
+
259
+
260
+ conn_tmap = {
261
+ "all": ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
262
+ "tcp": ([AF_INET, AF_INET6], [SOCK_STREAM]),
263
+ "tcp4": ([AF_INET], [SOCK_STREAM]),
264
+ "udp": ([AF_INET, AF_INET6], [SOCK_DGRAM]),
265
+ "udp4": ([AF_INET], [SOCK_DGRAM]),
266
+ "inet": ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
267
+ "inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]),
268
+ "inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
269
+ }
270
+
271
+ if AF_INET6 is not None:
272
+ conn_tmap.update({
273
+ "tcp6": ([AF_INET6], [SOCK_STREAM]),
274
+ "udp6": ([AF_INET6], [SOCK_DGRAM]),
275
+ })
276
+
277
+ if AF_UNIX is not None:
278
+ conn_tmap.update({"unix": ([AF_UNIX], [SOCK_STREAM, SOCK_DGRAM])})
279
+
280
+
281
+ # =====================================================================
282
+ # --- Exceptions
283
+ # =====================================================================
284
+
285
+
286
+ class Error(Exception):
287
+ """Base exception class. All other psutil exceptions inherit
288
+ from this one.
289
+ """
290
+
291
+ __module__ = 'psutil'
292
+
293
+ def _infodict(self, attrs):
294
+ info = collections.OrderedDict()
295
+ for name in attrs:
296
+ value = getattr(self, name, None)
297
+ if value: # noqa
298
+ info[name] = value
299
+ elif name == "pid" and value == 0:
300
+ info[name] = value
301
+ return info
302
+
303
+ def __str__(self):
304
+ # invoked on `raise Error`
305
+ info = self._infodict(("pid", "ppid", "name"))
306
+ if info:
307
+ details = "(%s)" % ", ".join(
308
+ ["%s=%r" % (k, v) for k, v in info.items()]
309
+ )
310
+ else:
311
+ details = None
312
+ return " ".join([x for x in (getattr(self, "msg", ""), details) if x])
313
+
314
+ def __repr__(self):
315
+ # invoked on `repr(Error)`
316
+ info = self._infodict(("pid", "ppid", "name", "seconds", "msg"))
317
+ details = ", ".join(["%s=%r" % (k, v) for k, v in info.items()])
318
+ return "psutil.%s(%s)" % (self.__class__.__name__, details)
319
+
320
+
321
+ class NoSuchProcess(Error):
322
+ """Exception raised when a process with a certain PID doesn't
323
+ or no longer exists.
324
+ """
325
+
326
+ __module__ = 'psutil'
327
+
328
+ def __init__(self, pid, name=None, msg=None):
329
+ Error.__init__(self)
330
+ self.pid = pid
331
+ self.name = name
332
+ self.msg = msg or "process no longer exists"
333
+
334
+
335
+ class ZombieProcess(NoSuchProcess):
336
+ """Exception raised when querying a zombie process. This is
337
+ raised on macOS, BSD and Solaris only, and not always: depending
338
+ on the query the OS may be able to succeed anyway.
339
+ On Linux all zombie processes are querable (hence this is never
340
+ raised). Windows doesn't have zombie processes.
341
+ """
342
+
343
+ __module__ = 'psutil'
344
+
345
+ def __init__(self, pid, name=None, ppid=None, msg=None):
346
+ NoSuchProcess.__init__(self, pid, name, msg)
347
+ self.ppid = ppid
348
+ self.msg = msg or "PID still exists but it's a zombie"
349
+
350
+
351
+ class AccessDenied(Error):
352
+ """Exception raised when permission to perform an action is denied."""
353
+
354
+ __module__ = 'psutil'
355
+
356
+ def __init__(self, pid=None, name=None, msg=None):
357
+ Error.__init__(self)
358
+ self.pid = pid
359
+ self.name = name
360
+ self.msg = msg or ""
361
+
362
+
363
+ class TimeoutExpired(Error):
364
+ """Raised on Process.wait(timeout) if timeout expires and process
365
+ is still alive.
366
+ """
367
+
368
+ __module__ = 'psutil'
369
+
370
+ def __init__(self, seconds, pid=None, name=None):
371
+ Error.__init__(self)
372
+ self.seconds = seconds
373
+ self.pid = pid
374
+ self.name = name
375
+ self.msg = "timeout after %s seconds" % seconds
376
+
377
+
378
+ # ===================================================================
379
+ # --- utils
380
+ # ===================================================================
381
+
382
+
383
+ # This should be in _compat.py rather than here, but does not work well
384
+ # with setup.py importing this module via a sys.path trick.
385
+ if PY3:
386
+ if isinstance(__builtins__, dict): # cpython
387
+ exec_ = __builtins__["exec"]
388
+ else: # pypy
389
+ exec_ = getattr(__builtins__, "exec") # noqa
390
+
391
+ exec_("""def raise_from(value, from_value):
392
+ try:
393
+ raise value from from_value
394
+ finally:
395
+ value = None
396
+ """)
397
+ else:
398
+
399
+ def raise_from(value, from_value):
400
+ raise value
401
+
402
+
403
+ def usage_percent(used, total, round_=None):
404
+ """Calculate percentage usage of 'used' against 'total'."""
405
+ try:
406
+ ret = (float(used) / total) * 100
407
+ except ZeroDivisionError:
408
+ return 0.0
409
+ else:
410
+ if round_ is not None:
411
+ ret = round(ret, round_)
412
+ return ret
413
+
414
+
415
+ def memoize(fun):
416
+ """A simple memoize decorator for functions supporting (hashable)
417
+ positional arguments.
418
+ It also provides a cache_clear() function for clearing the cache:
419
+
420
+ >>> @memoize
421
+ ... def foo()
422
+ ... return 1
423
+ ...
424
+ >>> foo()
425
+ 1
426
+ >>> foo.cache_clear()
427
+ >>>
428
+
429
+ It supports:
430
+ - functions
431
+ - classes (acts as a @singleton)
432
+ - staticmethods
433
+ - classmethods
434
+
435
+ It does NOT support:
436
+ - methods
437
+ """
438
+
439
+ @functools.wraps(fun)
440
+ def wrapper(*args, **kwargs):
441
+ key = (args, frozenset(sorted(kwargs.items())))
442
+ try:
443
+ return cache[key]
444
+ except KeyError:
445
+ try:
446
+ ret = cache[key] = fun(*args, **kwargs)
447
+ except Exception as err: # noqa: BLE001
448
+ raise raise_from(err, None)
449
+ return ret
450
+
451
+ def cache_clear():
452
+ """Clear cache."""
453
+ cache.clear()
454
+
455
+ cache = {}
456
+ wrapper.cache_clear = cache_clear
457
+ return wrapper
458
+
459
+
460
+ def memoize_when_activated(fun):
461
+ """A memoize decorator which is disabled by default. It can be
462
+ activated and deactivated on request.
463
+ For efficiency reasons it can be used only against class methods
464
+ accepting no arguments.
465
+
466
+ >>> class Foo:
467
+ ... @memoize
468
+ ... def foo()
469
+ ... print(1)
470
+ ...
471
+ >>> f = Foo()
472
+ >>> # deactivated (default)
473
+ >>> foo()
474
+ 1
475
+ >>> foo()
476
+ 1
477
+ >>>
478
+ >>> # activated
479
+ >>> foo.cache_activate(self)
480
+ >>> foo()
481
+ 1
482
+ >>> foo()
483
+ >>> foo()
484
+ >>>
485
+ """
486
+
487
+ @functools.wraps(fun)
488
+ def wrapper(self):
489
+ try:
490
+ # case 1: we previously entered oneshot() ctx
491
+ ret = self._cache[fun]
492
+ except AttributeError:
493
+ # case 2: we never entered oneshot() ctx
494
+ try:
495
+ return fun(self)
496
+ except Exception as err: # noqa: BLE001
497
+ raise raise_from(err, None)
498
+ except KeyError:
499
+ # case 3: we entered oneshot() ctx but there's no cache
500
+ # for this entry yet
501
+ try:
502
+ ret = fun(self)
503
+ except Exception as err: # noqa: BLE001
504
+ raise raise_from(err, None)
505
+ try:
506
+ self._cache[fun] = ret
507
+ except AttributeError:
508
+ # multi-threading race condition, see:
509
+ # https://github.com/giampaolo/psutil/issues/1948
510
+ pass
511
+ return ret
512
+
513
+ def cache_activate(proc):
514
+ """Activate cache. Expects a Process instance. Cache will be
515
+ stored as a "_cache" instance attribute.
516
+ """
517
+ proc._cache = {}
518
+
519
+ def cache_deactivate(proc):
520
+ """Deactivate and clear cache."""
521
+ try:
522
+ del proc._cache
523
+ except AttributeError:
524
+ pass
525
+
526
+ wrapper.cache_activate = cache_activate
527
+ wrapper.cache_deactivate = cache_deactivate
528
+ return wrapper
529
+
530
+
531
+ def isfile_strict(path):
532
+ """Same as os.path.isfile() but does not swallow EACCES / EPERM
533
+ exceptions, see:
534
+ http://mail.python.org/pipermail/python-dev/2012-June/120787.html.
535
+ """
536
+ try:
537
+ st = os.stat(path)
538
+ except OSError as err:
539
+ if err.errno in (errno.EPERM, errno.EACCES):
540
+ raise
541
+ return False
542
+ else:
543
+ return stat.S_ISREG(st.st_mode)
544
+
545
+
546
+ def path_exists_strict(path):
547
+ """Same as os.path.exists() but does not swallow EACCES / EPERM
548
+ exceptions. See:
549
+ http://mail.python.org/pipermail/python-dev/2012-June/120787.html.
550
+ """
551
+ try:
552
+ os.stat(path)
553
+ except OSError as err:
554
+ if err.errno in (errno.EPERM, errno.EACCES):
555
+ raise
556
+ return False
557
+ else:
558
+ return True
559
+
560
+
561
+ @memoize
562
+ def supports_ipv6():
563
+ """Return True if IPv6 is supported on this platform."""
564
+ if not socket.has_ipv6 or AF_INET6 is None:
565
+ return False
566
+ try:
567
+ sock = socket.socket(AF_INET6, socket.SOCK_STREAM)
568
+ with contextlib.closing(sock):
569
+ sock.bind(("::1", 0))
570
+ return True
571
+ except socket.error:
572
+ return False
573
+
574
+
575
+ def parse_environ_block(data):
576
+ """Parse a C environ block of environment variables into a dictionary."""
577
+ # The block is usually raw data from the target process. It might contain
578
+ # trailing garbage and lines that do not look like assignments.
579
+ ret = {}
580
+ pos = 0
581
+
582
+ # localize global variable to speed up access.
583
+ WINDOWS_ = WINDOWS
584
+ while True:
585
+ next_pos = data.find("\0", pos)
586
+ # nul byte at the beginning or double nul byte means finish
587
+ if next_pos <= pos:
588
+ break
589
+ # there might not be an equals sign
590
+ equal_pos = data.find("=", pos, next_pos)
591
+ if equal_pos > pos:
592
+ key = data[pos:equal_pos]
593
+ value = data[equal_pos + 1 : next_pos]
594
+ # Windows expects environment variables to be uppercase only
595
+ if WINDOWS_:
596
+ key = key.upper()
597
+ ret[key] = value
598
+ pos = next_pos + 1
599
+
600
+ return ret
601
+
602
+
603
+ def sockfam_to_enum(num):
604
+ """Convert a numeric socket family value to an IntEnum member.
605
+ If it's not a known member, return the numeric value itself.
606
+ """
607
+ if enum is None:
608
+ return num
609
+ else: # pragma: no cover
610
+ try:
611
+ return socket.AddressFamily(num)
612
+ except ValueError:
613
+ return num
614
+
615
+
616
+ def socktype_to_enum(num):
617
+ """Convert a numeric socket type value to an IntEnum member.
618
+ If it's not a known member, return the numeric value itself.
619
+ """
620
+ if enum is None:
621
+ return num
622
+ else: # pragma: no cover
623
+ try:
624
+ return socket.SocketKind(num)
625
+ except ValueError:
626
+ return num
627
+
628
+
629
+ def conn_to_ntuple(fd, fam, type_, laddr, raddr, status, status_map, pid=None):
630
+ """Convert a raw connection tuple to a proper ntuple."""
631
+ if fam in (socket.AF_INET, AF_INET6):
632
+ if laddr:
633
+ laddr = addr(*laddr)
634
+ if raddr:
635
+ raddr = addr(*raddr)
636
+ if type_ == socket.SOCK_STREAM and fam in (AF_INET, AF_INET6):
637
+ status = status_map.get(status, CONN_NONE)
638
+ else:
639
+ status = CONN_NONE # ignore whatever C returned to us
640
+ fam = sockfam_to_enum(fam)
641
+ type_ = socktype_to_enum(type_)
642
+ if pid is None:
643
+ return pconn(fd, fam, type_, laddr, raddr, status)
644
+ else:
645
+ return sconn(fd, fam, type_, laddr, raddr, status, pid)
646
+
647
+
648
+ def deprecated_method(replacement):
649
+ """A decorator which can be used to mark a method as deprecated
650
+ 'replcement' is the method name which will be called instead.
651
+ """
652
+
653
+ def outer(fun):
654
+ msg = "%s() is deprecated and will be removed; use %s() instead" % (
655
+ fun.__name__,
656
+ replacement,
657
+ )
658
+ if fun.__doc__ is None:
659
+ fun.__doc__ = msg
660
+
661
+ @functools.wraps(fun)
662
+ def inner(self, *args, **kwargs):
663
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
664
+ return getattr(self, replacement)(*args, **kwargs)
665
+
666
+ return inner
667
+
668
+ return outer
669
+
670
+
671
+ class _WrapNumbers:
672
+ """Watches numbers so that they don't overflow and wrap
673
+ (reset to zero).
674
+ """
675
+
676
+ def __init__(self):
677
+ self.lock = threading.Lock()
678
+ self.cache = {}
679
+ self.reminders = {}
680
+ self.reminder_keys = {}
681
+
682
+ def _add_dict(self, input_dict, name):
683
+ assert name not in self.cache
684
+ assert name not in self.reminders
685
+ assert name not in self.reminder_keys
686
+ self.cache[name] = input_dict
687
+ self.reminders[name] = collections.defaultdict(int)
688
+ self.reminder_keys[name] = collections.defaultdict(set)
689
+
690
+ def _remove_dead_reminders(self, input_dict, name):
691
+ """In case the number of keys changed between calls (e.g. a
692
+ disk disappears) this removes the entry from self.reminders.
693
+ """
694
+ old_dict = self.cache[name]
695
+ gone_keys = set(old_dict.keys()) - set(input_dict.keys())
696
+ for gone_key in gone_keys:
697
+ for remkey in self.reminder_keys[name][gone_key]:
698
+ del self.reminders[name][remkey]
699
+ del self.reminder_keys[name][gone_key]
700
+
701
+ def run(self, input_dict, name):
702
+ """Cache dict and sum numbers which overflow and wrap.
703
+ Return an updated copy of `input_dict`.
704
+ """
705
+ if name not in self.cache:
706
+ # This was the first call.
707
+ self._add_dict(input_dict, name)
708
+ return input_dict
709
+
710
+ self._remove_dead_reminders(input_dict, name)
711
+
712
+ old_dict = self.cache[name]
713
+ new_dict = {}
714
+ for key in input_dict:
715
+ input_tuple = input_dict[key]
716
+ try:
717
+ old_tuple = old_dict[key]
718
+ except KeyError:
719
+ # The input dict has a new key (e.g. a new disk or NIC)
720
+ # which didn't exist in the previous call.
721
+ new_dict[key] = input_tuple
722
+ continue
723
+
724
+ bits = []
725
+ for i in range(len(input_tuple)):
726
+ input_value = input_tuple[i]
727
+ old_value = old_tuple[i]
728
+ remkey = (key, i)
729
+ if input_value < old_value:
730
+ # it wrapped!
731
+ self.reminders[name][remkey] += old_value
732
+ self.reminder_keys[name][key].add(remkey)
733
+ bits.append(input_value + self.reminders[name][remkey])
734
+
735
+ new_dict[key] = tuple(bits)
736
+
737
+ self.cache[name] = input_dict
738
+ return new_dict
739
+
740
+ def cache_clear(self, name=None):
741
+ """Clear the internal cache, optionally only for function 'name'."""
742
+ with self.lock:
743
+ if name is None:
744
+ self.cache.clear()
745
+ self.reminders.clear()
746
+ self.reminder_keys.clear()
747
+ else:
748
+ self.cache.pop(name, None)
749
+ self.reminders.pop(name, None)
750
+ self.reminder_keys.pop(name, None)
751
+
752
+ def cache_info(self):
753
+ """Return internal cache dicts as a tuple of 3 elements."""
754
+ with self.lock:
755
+ return (self.cache, self.reminders, self.reminder_keys)
756
+
757
+
758
+ def wrap_numbers(input_dict, name):
759
+ """Given an `input_dict` and a function `name`, adjust the numbers
760
+ which "wrap" (restart from zero) across different calls by adding
761
+ "old value" to "new value" and return an updated dict.
762
+ """
763
+ with _wn.lock:
764
+ return _wn.run(input_dict, name)
765
+
766
+
767
+ _wn = _WrapNumbers()
768
+ wrap_numbers.cache_clear = _wn.cache_clear
769
+ wrap_numbers.cache_info = _wn.cache_info
770
+
771
+
772
+ # The read buffer size for open() builtin. This (also) dictates how
773
+ # much data we read(2) when iterating over file lines as in:
774
+ # >>> with open(file) as f:
775
+ # ... for line in f:
776
+ # ... ...
777
+ # Default per-line buffer size for binary files is 1K. For text files
778
+ # is 8K. We use a bigger buffer (32K) in order to have more consistent
779
+ # results when reading /proc pseudo files on Linux, see:
780
+ # https://github.com/giampaolo/psutil/issues/2050
781
+ # On Python 2 this also speeds up the reading of big files:
782
+ # (namely /proc/{pid}/smaps and /proc/net/*):
783
+ # https://github.com/giampaolo/psutil/issues/708
784
+ FILE_READ_BUFFER_SIZE = 32 * 1024
785
+
786
+
787
+ def open_binary(fname):
788
+ return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE)
789
+
790
+
791
+ def open_text(fname):
792
+ """On Python 3 opens a file in text mode by using fs encoding and
793
+ a proper en/decoding errors handler.
794
+ On Python 2 this is just an alias for open(name, 'rt').
795
+ """
796
+ if not PY3:
797
+ return open(fname, buffering=FILE_READ_BUFFER_SIZE)
798
+
799
+ # See:
800
+ # https://github.com/giampaolo/psutil/issues/675
801
+ # https://github.com/giampaolo/psutil/pull/733
802
+ fobj = open(
803
+ fname,
804
+ buffering=FILE_READ_BUFFER_SIZE,
805
+ encoding=ENCODING,
806
+ errors=ENCODING_ERRS,
807
+ )
808
+ try:
809
+ # Dictates per-line read(2) buffer size. Defaults is 8k. See:
810
+ # https://github.com/giampaolo/psutil/issues/2050#issuecomment-1013387546
811
+ fobj._CHUNK_SIZE = FILE_READ_BUFFER_SIZE
812
+ except AttributeError:
813
+ pass
814
+ except Exception:
815
+ fobj.close()
816
+ raise
817
+
818
+ return fobj
819
+
820
+
821
+ def cat(fname, fallback=_DEFAULT, _open=open_text):
822
+ """Read entire file content and return it as a string. File is
823
+ opened in text mode. If specified, `fallback` is the value
824
+ returned in case of error, either if the file does not exist or
825
+ it can't be read().
826
+ """
827
+ if fallback is _DEFAULT:
828
+ with _open(fname) as f:
829
+ return f.read()
830
+ else:
831
+ try:
832
+ with _open(fname) as f:
833
+ return f.read()
834
+ except (IOError, OSError):
835
+ return fallback
836
+
837
+
838
+ def bcat(fname, fallback=_DEFAULT):
839
+ """Same as above but opens file in binary mode."""
840
+ return cat(fname, fallback=fallback, _open=open_binary)
841
+
842
+
843
+ def bytes2human(n, format="%(value).1f%(symbol)s"):
844
+ """Used by various scripts. See: http://goo.gl/zeJZl.
845
+
846
+ >>> bytes2human(10000)
847
+ '9.8K'
848
+ >>> bytes2human(100001221)
849
+ '95.4M'
850
+ """
851
+ symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
852
+ prefix = {}
853
+ for i, s in enumerate(symbols[1:]):
854
+ prefix[s] = 1 << (i + 1) * 10
855
+ for symbol in reversed(symbols[1:]):
856
+ if abs(n) >= prefix[symbol]:
857
+ value = float(n) / prefix[symbol]
858
+ return format % locals()
859
+ return format % dict(symbol=symbols[0], value=n)
860
+
861
+
862
+ def get_procfs_path():
863
+ """Return updated psutil.PROCFS_PATH constant."""
864
+ return sys.modules['psutil'].PROCFS_PATH
865
+
866
+
867
+ if PY3:
868
+
869
+ def decode(s):
870
+ return s.decode(encoding=ENCODING, errors=ENCODING_ERRS)
871
+
872
+ else:
873
+
874
+ def decode(s):
875
+ return s
876
+
877
+
878
+ # =====================================================================
879
+ # --- shell utils
880
+ # =====================================================================
881
+
882
+
883
+ @memoize
884
+ def term_supports_colors(file=sys.stdout): # pragma: no cover
885
+ if os.name == 'nt':
886
+ return True
887
+ try:
888
+ import curses
889
+
890
+ assert file.isatty()
891
+ curses.setupterm()
892
+ assert curses.tigetnum("colors") > 0
893
+ except Exception: # noqa: BLE001
894
+ return False
895
+ else:
896
+ return True
897
+
898
+
899
+ def hilite(s, color=None, bold=False): # pragma: no cover
900
+ """Return an highlighted version of 'string'."""
901
+ if not term_supports_colors():
902
+ return s
903
+ attr = []
904
+ colors = dict(
905
+ blue='34',
906
+ brown='33',
907
+ darkgrey='30',
908
+ green='32',
909
+ grey='37',
910
+ lightblue='36',
911
+ red='91',
912
+ violet='35',
913
+ yellow='93',
914
+ )
915
+ colors[None] = '29'
916
+ try:
917
+ color = colors[color]
918
+ except KeyError:
919
+ raise ValueError(
920
+ "invalid color %r; choose between %s" % (list(colors.keys()))
921
+ )
922
+ attr.append(color)
923
+ if bold:
924
+ attr.append('1')
925
+ return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), s)
926
+
927
+
928
+ def print_color(
929
+ s, color=None, bold=False, file=sys.stdout
930
+ ): # pragma: no cover
931
+ """Print a colorized version of string."""
932
+ if not term_supports_colors():
933
+ print(s, file=file) # NOQA
934
+ elif POSIX:
935
+ print(hilite(s, color, bold), file=file) # NOQA
936
+ else:
937
+ import ctypes
938
+
939
+ DEFAULT_COLOR = 7
940
+ GetStdHandle = ctypes.windll.Kernel32.GetStdHandle
941
+ SetConsoleTextAttribute = (
942
+ ctypes.windll.Kernel32.SetConsoleTextAttribute
943
+ )
944
+
945
+ colors = dict(green=2, red=4, brown=6, yellow=6)
946
+ colors[None] = DEFAULT_COLOR
947
+ try:
948
+ color = colors[color]
949
+ except KeyError:
950
+ raise ValueError(
951
+ "invalid color %r; choose between %r"
952
+ % (color, list(colors.keys()))
953
+ )
954
+ if bold and color <= 7:
955
+ color += 8
956
+
957
+ handle_id = -12 if file is sys.stderr else -11
958
+ GetStdHandle.restype = ctypes.c_ulong
959
+ handle = GetStdHandle(handle_id)
960
+ SetConsoleTextAttribute(handle, color)
961
+ try:
962
+ print(s, file=file) # NOQA
963
+ finally:
964
+ SetConsoleTextAttribute(handle, DEFAULT_COLOR)
965
+
966
+
967
+ def debug(msg):
968
+ """If PSUTIL_DEBUG env var is set, print a debug message to stderr."""
969
+ if PSUTIL_DEBUG:
970
+ import inspect
971
+
972
+ fname, lineno, _, lines, index = inspect.getframeinfo(
973
+ inspect.currentframe().f_back
974
+ )
975
+ if isinstance(msg, Exception):
976
+ if isinstance(msg, (OSError, IOError, EnvironmentError)):
977
+ # ...because str(exc) may contain info about the file name
978
+ msg = "ignoring %s" % msg
979
+ else:
980
+ msg = "ignoring %r" % msg
981
+ print( # noqa
982
+ "psutil-debug [%s:%s]> %s" % (fname, lineno, msg), file=sys.stderr
983
+ )
llmeval-env/lib/python3.10/site-packages/psutil/_compat.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """Module which provides compatibility with older Python versions.
6
+ This is more future-compatible rather than the opposite (prefer latest
7
+ Python 3 way of doing things).
8
+ """
9
+
10
+ import collections
11
+ import contextlib
12
+ import errno
13
+ import functools
14
+ import os
15
+ import sys
16
+ import types
17
+
18
+
19
+ # fmt: off
20
+ __all__ = [
21
+ # constants
22
+ "PY3",
23
+ # builtins
24
+ "long", "range", "super", "unicode", "basestring",
25
+ # literals
26
+ "u", "b",
27
+ # collections module
28
+ "lru_cache",
29
+ # shutil module
30
+ "which", "get_terminal_size",
31
+ # contextlib module
32
+ "redirect_stderr",
33
+ # python 3 exceptions
34
+ "FileNotFoundError", "PermissionError", "ProcessLookupError",
35
+ "InterruptedError", "ChildProcessError", "FileExistsError",
36
+ ]
37
+ # fmt: on
38
+
39
+
40
+ PY3 = sys.version_info[0] >= 3
41
+ _SENTINEL = object()
42
+
43
+ if PY3:
44
+ long = int
45
+ xrange = range
46
+ unicode = str
47
+ basestring = str
48
+ range = range
49
+
50
+ def u(s):
51
+ return s
52
+
53
+ def b(s):
54
+ return s.encode("latin-1")
55
+
56
+ else:
57
+ long = long
58
+ range = xrange
59
+ unicode = unicode
60
+ basestring = basestring
61
+
62
+ def u(s):
63
+ return unicode(s, "unicode_escape")
64
+
65
+ def b(s):
66
+ return s
67
+
68
+
69
+ # --- builtins
70
+
71
+
72
+ # Python 3 super().
73
+ # Taken from "future" package.
74
+ # Credit: Ryan Kelly
75
+ if PY3:
76
+ super = super
77
+ else:
78
+ _builtin_super = super
79
+
80
+ def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
81
+ """Like Python 3 builtin super(). If called without any arguments
82
+ it attempts to infer them at runtime.
83
+ """
84
+ if type_ is _SENTINEL:
85
+ f = sys._getframe(framedepth)
86
+ try:
87
+ # Get the function's first positional argument.
88
+ type_or_obj = f.f_locals[f.f_code.co_varnames[0]]
89
+ except (IndexError, KeyError):
90
+ msg = 'super() used in a function with no args'
91
+ raise RuntimeError(msg)
92
+ try:
93
+ # Get the MRO so we can crawl it.
94
+ mro = type_or_obj.__mro__
95
+ except (AttributeError, RuntimeError):
96
+ try:
97
+ mro = type_or_obj.__class__.__mro__
98
+ except AttributeError:
99
+ msg = 'super() used in a non-newstyle class'
100
+ raise RuntimeError(msg)
101
+ for type_ in mro:
102
+ # Find the class that owns the currently-executing method.
103
+ for meth in type_.__dict__.values():
104
+ # Drill down through any wrappers to the underlying func.
105
+ # This handles e.g. classmethod() and staticmethod().
106
+ try:
107
+ while not isinstance(meth, types.FunctionType):
108
+ if isinstance(meth, property):
109
+ # Calling __get__ on the property will invoke
110
+ # user code which might throw exceptions or
111
+ # have side effects
112
+ meth = meth.fget
113
+ else:
114
+ try:
115
+ meth = meth.__func__
116
+ except AttributeError:
117
+ meth = meth.__get__(type_or_obj, type_)
118
+ except (AttributeError, TypeError):
119
+ continue
120
+ if meth.func_code is f.f_code:
121
+ break # found
122
+ else:
123
+ # Not found. Move onto the next class in MRO.
124
+ continue
125
+ break # found
126
+ else:
127
+ msg = 'super() called outside a method'
128
+ raise RuntimeError(msg)
129
+
130
+ # Dispatch to builtin super().
131
+ if type_or_obj is not _SENTINEL:
132
+ return _builtin_super(type_, type_or_obj)
133
+ return _builtin_super(type_)
134
+
135
+
136
+ # --- exceptions
137
+
138
+
139
+ if PY3:
140
+ FileNotFoundError = FileNotFoundError # NOQA
141
+ PermissionError = PermissionError # NOQA
142
+ ProcessLookupError = ProcessLookupError # NOQA
143
+ InterruptedError = InterruptedError # NOQA
144
+ ChildProcessError = ChildProcessError # NOQA
145
+ FileExistsError = FileExistsError # NOQA
146
+ else:
147
+ # https://github.com/PythonCharmers/python-future/blob/exceptions/
148
+ # src/future/types/exceptions/pep3151.py
149
+ import platform
150
+
151
+ def _instance_checking_exception(base_exception=Exception):
152
+ def wrapped(instance_checker):
153
+ class TemporaryClass(base_exception):
154
+ def __init__(self, *args, **kwargs):
155
+ if len(args) == 1 and isinstance(args[0], TemporaryClass):
156
+ unwrap_me = args[0]
157
+ for attr in dir(unwrap_me):
158
+ if not attr.startswith('__'):
159
+ setattr(self, attr, getattr(unwrap_me, attr))
160
+ else:
161
+ super(TemporaryClass, self).__init__( # noqa
162
+ *args, **kwargs
163
+ )
164
+
165
+ class __metaclass__(type):
166
+ def __instancecheck__(cls, inst):
167
+ return instance_checker(inst)
168
+
169
+ def __subclasscheck__(cls, classinfo):
170
+ value = sys.exc_info()[1]
171
+ return isinstance(value, cls)
172
+
173
+ TemporaryClass.__name__ = instance_checker.__name__
174
+ TemporaryClass.__doc__ = instance_checker.__doc__
175
+ return TemporaryClass
176
+
177
+ return wrapped
178
+
179
+ @_instance_checking_exception(EnvironmentError)
180
+ def FileNotFoundError(inst):
181
+ return getattr(inst, 'errno', _SENTINEL) == errno.ENOENT
182
+
183
+ @_instance_checking_exception(EnvironmentError)
184
+ def ProcessLookupError(inst):
185
+ return getattr(inst, 'errno', _SENTINEL) == errno.ESRCH
186
+
187
+ @_instance_checking_exception(EnvironmentError)
188
+ def PermissionError(inst):
189
+ return getattr(inst, 'errno', _SENTINEL) in (errno.EACCES, errno.EPERM)
190
+
191
+ @_instance_checking_exception(EnvironmentError)
192
+ def InterruptedError(inst):
193
+ return getattr(inst, 'errno', _SENTINEL) == errno.EINTR
194
+
195
+ @_instance_checking_exception(EnvironmentError)
196
+ def ChildProcessError(inst):
197
+ return getattr(inst, 'errno', _SENTINEL) == errno.ECHILD
198
+
199
+ @_instance_checking_exception(EnvironmentError)
200
+ def FileExistsError(inst):
201
+ return getattr(inst, 'errno', _SENTINEL) == errno.EEXIST
202
+
203
+ if platform.python_implementation() != "CPython":
204
+ try:
205
+ raise OSError(errno.EEXIST, "perm")
206
+ except FileExistsError:
207
+ pass
208
+ except OSError:
209
+ msg = (
210
+ "broken or incompatible Python implementation, see: "
211
+ "https://github.com/giampaolo/psutil/issues/1659"
212
+ )
213
+ raise RuntimeError(msg)
214
+
215
+
216
+ # --- stdlib additions
217
+
218
+
219
+ # py 3.2 functools.lru_cache
220
+ # Taken from: http://code.activestate.com/recipes/578078
221
+ # Credit: Raymond Hettinger
222
+ try:
223
+ from functools import lru_cache
224
+ except ImportError:
225
+ try:
226
+ from threading import RLock
227
+ except ImportError:
228
+ from dummy_threading import RLock
229
+
230
+ _CacheInfo = collections.namedtuple(
231
+ "CacheInfo", ["hits", "misses", "maxsize", "currsize"]
232
+ )
233
+
234
+ class _HashedSeq(list):
235
+ __slots__ = ('hashvalue',)
236
+
237
+ def __init__(self, tup, hash=hash):
238
+ self[:] = tup
239
+ self.hashvalue = hash(tup)
240
+
241
+ def __hash__(self):
242
+ return self.hashvalue
243
+
244
+ def _make_key(
245
+ args,
246
+ kwds,
247
+ typed,
248
+ kwd_mark=(_SENTINEL,),
249
+ fasttypes=set((int, str, frozenset, type(None))), # noqa
250
+ sorted=sorted,
251
+ tuple=tuple,
252
+ type=type,
253
+ len=len,
254
+ ):
255
+ key = args
256
+ if kwds:
257
+ sorted_items = sorted(kwds.items())
258
+ key += kwd_mark
259
+ for item in sorted_items:
260
+ key += item
261
+ if typed:
262
+ key += tuple(type(v) for v in args)
263
+ if kwds:
264
+ key += tuple(type(v) for k, v in sorted_items)
265
+ elif len(key) == 1 and type(key[0]) in fasttypes:
266
+ return key[0]
267
+ return _HashedSeq(key)
268
+
269
+ def lru_cache(maxsize=100, typed=False):
270
+ """Least-recently-used cache decorator, see:
271
+ http://docs.python.org/3/library/functools.html#functools.lru_cache.
272
+ """
273
+
274
+ def decorating_function(user_function):
275
+ cache = {}
276
+ stats = [0, 0]
277
+ HITS, MISSES = 0, 1
278
+ make_key = _make_key
279
+ cache_get = cache.get
280
+ _len = len
281
+ lock = RLock()
282
+ root = []
283
+ root[:] = [root, root, None, None]
284
+ nonlocal_root = [root]
285
+ PREV, NEXT, KEY, RESULT = 0, 1, 2, 3
286
+ if maxsize == 0:
287
+
288
+ def wrapper(*args, **kwds):
289
+ result = user_function(*args, **kwds)
290
+ stats[MISSES] += 1
291
+ return result
292
+
293
+ elif maxsize is None:
294
+
295
+ def wrapper(*args, **kwds):
296
+ key = make_key(args, kwds, typed)
297
+ result = cache_get(key, root)
298
+ if result is not root:
299
+ stats[HITS] += 1
300
+ return result
301
+ result = user_function(*args, **kwds)
302
+ cache[key] = result
303
+ stats[MISSES] += 1
304
+ return result
305
+
306
+ else:
307
+
308
+ def wrapper(*args, **kwds):
309
+ if kwds or typed:
310
+ key = make_key(args, kwds, typed)
311
+ else:
312
+ key = args
313
+ lock.acquire()
314
+ try:
315
+ link = cache_get(key)
316
+ if link is not None:
317
+ (root,) = nonlocal_root
318
+ link_prev, link_next, key, result = link
319
+ link_prev[NEXT] = link_next
320
+ link_next[PREV] = link_prev
321
+ last = root[PREV]
322
+ last[NEXT] = root[PREV] = link
323
+ link[PREV] = last
324
+ link[NEXT] = root
325
+ stats[HITS] += 1
326
+ return result
327
+ finally:
328
+ lock.release()
329
+ result = user_function(*args, **kwds)
330
+ lock.acquire()
331
+ try:
332
+ (root,) = nonlocal_root
333
+ if key in cache:
334
+ pass
335
+ elif _len(cache) >= maxsize:
336
+ oldroot = root
337
+ oldroot[KEY] = key
338
+ oldroot[RESULT] = result
339
+ root = nonlocal_root[0] = oldroot[NEXT]
340
+ oldkey = root[KEY]
341
+ root[KEY] = root[RESULT] = None
342
+ del cache[oldkey]
343
+ cache[key] = oldroot
344
+ else:
345
+ last = root[PREV]
346
+ link = [last, root, key, result]
347
+ last[NEXT] = root[PREV] = cache[key] = link
348
+ stats[MISSES] += 1
349
+ finally:
350
+ lock.release()
351
+ return result
352
+
353
+ def cache_info():
354
+ """Report cache statistics."""
355
+ lock.acquire()
356
+ try:
357
+ return _CacheInfo(
358
+ stats[HITS], stats[MISSES], maxsize, len(cache)
359
+ )
360
+ finally:
361
+ lock.release()
362
+
363
+ def cache_clear():
364
+ """Clear the cache and cache statistics."""
365
+ lock.acquire()
366
+ try:
367
+ cache.clear()
368
+ root = nonlocal_root[0]
369
+ root[:] = [root, root, None, None]
370
+ stats[:] = [0, 0]
371
+ finally:
372
+ lock.release()
373
+
374
+ wrapper.__wrapped__ = user_function
375
+ wrapper.cache_info = cache_info
376
+ wrapper.cache_clear = cache_clear
377
+ return functools.update_wrapper(wrapper, user_function)
378
+
379
+ return decorating_function
380
+
381
+
382
+ # python 3.3
383
+ try:
384
+ from shutil import which
385
+ except ImportError:
386
+
387
+ def which(cmd, mode=os.F_OK | os.X_OK, path=None):
388
+ """Given a command, mode, and a PATH string, return the path which
389
+ conforms to the given mode on the PATH, or None if there is no such
390
+ file.
391
+
392
+ `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
393
+ of os.environ.get("PATH"), or can be overridden with a custom search
394
+ path.
395
+ """
396
+
397
+ def _access_check(fn, mode):
398
+ return (
399
+ os.path.exists(fn)
400
+ and os.access(fn, mode)
401
+ and not os.path.isdir(fn)
402
+ )
403
+
404
+ if os.path.dirname(cmd):
405
+ if _access_check(cmd, mode):
406
+ return cmd
407
+ return None
408
+
409
+ if path is None:
410
+ path = os.environ.get("PATH", os.defpath)
411
+ if not path:
412
+ return None
413
+ path = path.split(os.pathsep)
414
+
415
+ if sys.platform == "win32":
416
+ if os.curdir not in path:
417
+ path.insert(0, os.curdir)
418
+
419
+ pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
420
+ if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
421
+ files = [cmd]
422
+ else:
423
+ files = [cmd + ext for ext in pathext]
424
+ else:
425
+ files = [cmd]
426
+
427
+ seen = set()
428
+ for dir in path:
429
+ normdir = os.path.normcase(dir)
430
+ if normdir not in seen:
431
+ seen.add(normdir)
432
+ for thefile in files:
433
+ name = os.path.join(dir, thefile)
434
+ if _access_check(name, mode):
435
+ return name
436
+ return None
437
+
438
+
439
+ # python 3.3
440
+ try:
441
+ from shutil import get_terminal_size
442
+ except ImportError:
443
+
444
+ def get_terminal_size(fallback=(80, 24)):
445
+ try:
446
+ import fcntl
447
+ import struct
448
+ import termios
449
+ except ImportError:
450
+ return fallback
451
+ else:
452
+ try:
453
+ # This should work on Linux.
454
+ res = struct.unpack(
455
+ 'hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234')
456
+ )
457
+ return (res[1], res[0])
458
+ except Exception: # noqa: BLE001
459
+ return fallback
460
+
461
+
462
+ # python 3.3
463
+ try:
464
+ from subprocess import TimeoutExpired as SubprocessTimeoutExpired
465
+ except ImportError:
466
+
467
+ class SubprocessTimeoutExpired(Exception):
468
+ pass
469
+
470
+
471
+ # python 3.5
472
+ try:
473
+ from contextlib import redirect_stderr
474
+ except ImportError:
475
+
476
+ @contextlib.contextmanager
477
+ def redirect_stderr(new_target):
478
+ original = sys.stderr
479
+ try:
480
+ sys.stderr = new_target
481
+ yield new_target
482
+ finally:
483
+ sys.stderr = original
llmeval-env/lib/python3.10/site-packages/psutil/_psaix.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'
2
+ # Copyright (c) 2017, Arnon Yaari
3
+ # All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """AIX platform implementation."""
8
+
9
+ import functools
10
+ import glob
11
+ import os
12
+ import re
13
+ import subprocess
14
+ import sys
15
+ from collections import namedtuple
16
+
17
+ from . import _common
18
+ from . import _psposix
19
+ from . import _psutil_aix as cext
20
+ from . import _psutil_posix as cext_posix
21
+ from ._common import NIC_DUPLEX_FULL
22
+ from ._common import NIC_DUPLEX_HALF
23
+ from ._common import NIC_DUPLEX_UNKNOWN
24
+ from ._common import AccessDenied
25
+ from ._common import NoSuchProcess
26
+ from ._common import ZombieProcess
27
+ from ._common import conn_to_ntuple
28
+ from ._common import get_procfs_path
29
+ from ._common import memoize_when_activated
30
+ from ._common import usage_percent
31
+ from ._compat import PY3
32
+ from ._compat import FileNotFoundError
33
+ from ._compat import PermissionError
34
+ from ._compat import ProcessLookupError
35
+
36
+
37
+ __extra__all__ = ["PROCFS_PATH"]
38
+
39
+
40
+ # =====================================================================
41
+ # --- globals
42
+ # =====================================================================
43
+
44
+
45
+ HAS_THREADS = hasattr(cext, "proc_threads")
46
+ HAS_NET_IO_COUNTERS = hasattr(cext, "net_io_counters")
47
+ HAS_PROC_IO_COUNTERS = hasattr(cext, "proc_io_counters")
48
+
49
+ PAGE_SIZE = cext_posix.getpagesize()
50
+ AF_LINK = cext_posix.AF_LINK
51
+
52
+ PROC_STATUSES = {
53
+ cext.SIDL: _common.STATUS_IDLE,
54
+ cext.SZOMB: _common.STATUS_ZOMBIE,
55
+ cext.SACTIVE: _common.STATUS_RUNNING,
56
+ cext.SSWAP: _common.STATUS_RUNNING, # TODO what status is this?
57
+ cext.SSTOP: _common.STATUS_STOPPED,
58
+ }
59
+
60
+ TCP_STATUSES = {
61
+ cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
62
+ cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
63
+ cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
64
+ cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
65
+ cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
66
+ cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
67
+ cext.TCPS_CLOSED: _common.CONN_CLOSE,
68
+ cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
69
+ cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
70
+ cext.TCPS_LISTEN: _common.CONN_LISTEN,
71
+ cext.TCPS_CLOSING: _common.CONN_CLOSING,
72
+ cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
73
+ }
74
+
75
+ proc_info_map = dict(
76
+ ppid=0,
77
+ rss=1,
78
+ vms=2,
79
+ create_time=3,
80
+ nice=4,
81
+ num_threads=5,
82
+ status=6,
83
+ ttynr=7,
84
+ )
85
+
86
+
87
+ # =====================================================================
88
+ # --- named tuples
89
+ # =====================================================================
90
+
91
+
92
+ # psutil.Process.memory_info()
93
+ pmem = namedtuple('pmem', ['rss', 'vms'])
94
+ # psutil.Process.memory_full_info()
95
+ pfullmem = pmem
96
+ # psutil.Process.cpu_times()
97
+ scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
98
+ # psutil.virtual_memory()
99
+ svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
100
+
101
+
102
+ # =====================================================================
103
+ # --- memory
104
+ # =====================================================================
105
+
106
+
107
+ def virtual_memory():
108
+ total, avail, free, pinned, inuse = cext.virtual_mem()
109
+ percent = usage_percent((total - avail), total, round_=1)
110
+ return svmem(total, avail, percent, inuse, free)
111
+
112
+
113
+ def swap_memory():
114
+ """Swap system memory as a (total, used, free, sin, sout) tuple."""
115
+ total, free, sin, sout = cext.swap_mem()
116
+ used = total - free
117
+ percent = usage_percent(used, total, round_=1)
118
+ return _common.sswap(total, used, free, percent, sin, sout)
119
+
120
+
121
+ # =====================================================================
122
+ # --- CPU
123
+ # =====================================================================
124
+
125
+
126
+ def cpu_times():
127
+ """Return system-wide CPU times as a named tuple."""
128
+ ret = cext.per_cpu_times()
129
+ return scputimes(*[sum(x) for x in zip(*ret)])
130
+
131
+
132
+ def per_cpu_times():
133
+ """Return system per-CPU times as a list of named tuples."""
134
+ ret = cext.per_cpu_times()
135
+ return [scputimes(*x) for x in ret]
136
+
137
+
138
+ def cpu_count_logical():
139
+ """Return the number of logical CPUs in the system."""
140
+ try:
141
+ return os.sysconf("SC_NPROCESSORS_ONLN")
142
+ except ValueError:
143
+ # mimic os.cpu_count() behavior
144
+ return None
145
+
146
+
147
+ def cpu_count_cores():
148
+ cmd = ["lsdev", "-Cc", "processor"]
149
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
150
+ stdout, stderr = p.communicate()
151
+ if PY3:
152
+ stdout, stderr = (
153
+ x.decode(sys.stdout.encoding) for x in (stdout, stderr)
154
+ )
155
+ if p.returncode != 0:
156
+ raise RuntimeError("%r command error\n%s" % (cmd, stderr))
157
+ processors = stdout.strip().splitlines()
158
+ return len(processors) or None
159
+
160
+
161
+ def cpu_stats():
162
+ """Return various CPU stats as a named tuple."""
163
+ ctx_switches, interrupts, soft_interrupts, syscalls = cext.cpu_stats()
164
+ return _common.scpustats(
165
+ ctx_switches, interrupts, soft_interrupts, syscalls
166
+ )
167
+
168
+
169
+ # =====================================================================
170
+ # --- disks
171
+ # =====================================================================
172
+
173
+
174
+ disk_io_counters = cext.disk_io_counters
175
+ disk_usage = _psposix.disk_usage
176
+
177
+
178
+ def disk_partitions(all=False):
179
+ """Return system disk partitions."""
180
+ # TODO - the filtering logic should be better checked so that
181
+ # it tries to reflect 'df' as much as possible
182
+ retlist = []
183
+ partitions = cext.disk_partitions()
184
+ for partition in partitions:
185
+ device, mountpoint, fstype, opts = partition
186
+ if device == 'none':
187
+ device = ''
188
+ if not all:
189
+ # Differently from, say, Linux, we don't have a list of
190
+ # common fs types so the best we can do, AFAIK, is to
191
+ # filter by filesystem having a total size > 0.
192
+ if not disk_usage(mountpoint).total:
193
+ continue
194
+ maxfile = maxpath = None # set later
195
+ ntuple = _common.sdiskpart(
196
+ device, mountpoint, fstype, opts, maxfile, maxpath
197
+ )
198
+ retlist.append(ntuple)
199
+ return retlist
200
+
201
+
202
+ # =====================================================================
203
+ # --- network
204
+ # =====================================================================
205
+
206
+
207
+ net_if_addrs = cext_posix.net_if_addrs
208
+
209
+ if HAS_NET_IO_COUNTERS:
210
+ net_io_counters = cext.net_io_counters
211
+
212
+
213
+ def net_connections(kind, _pid=-1):
214
+ """Return socket connections. If pid == -1 return system-wide
215
+ connections (as opposed to connections opened by one process only).
216
+ """
217
+ cmap = _common.conn_tmap
218
+ if kind not in cmap:
219
+ raise ValueError(
220
+ "invalid %r kind argument; choose between %s"
221
+ % (kind, ', '.join([repr(x) for x in cmap]))
222
+ )
223
+ families, types = _common.conn_tmap[kind]
224
+ rawlist = cext.net_connections(_pid)
225
+ ret = []
226
+ for item in rawlist:
227
+ fd, fam, type_, laddr, raddr, status, pid = item
228
+ if fam not in families:
229
+ continue
230
+ if type_ not in types:
231
+ continue
232
+ nt = conn_to_ntuple(
233
+ fd,
234
+ fam,
235
+ type_,
236
+ laddr,
237
+ raddr,
238
+ status,
239
+ TCP_STATUSES,
240
+ pid=pid if _pid == -1 else None,
241
+ )
242
+ ret.append(nt)
243
+ return ret
244
+
245
+
246
+ def net_if_stats():
247
+ """Get NIC stats (isup, duplex, speed, mtu)."""
248
+ duplex_map = {"Full": NIC_DUPLEX_FULL, "Half": NIC_DUPLEX_HALF}
249
+ names = set([x[0] for x in net_if_addrs()])
250
+ ret = {}
251
+ for name in names:
252
+ mtu = cext_posix.net_if_mtu(name)
253
+ flags = cext_posix.net_if_flags(name)
254
+
255
+ # try to get speed and duplex
256
+ # TODO: rewrite this in C (entstat forks, so use truss -f to follow.
257
+ # looks like it is using an undocumented ioctl?)
258
+ duplex = ""
259
+ speed = 0
260
+ p = subprocess.Popen(
261
+ ["/usr/bin/entstat", "-d", name],
262
+ stdout=subprocess.PIPE,
263
+ stderr=subprocess.PIPE,
264
+ )
265
+ stdout, stderr = p.communicate()
266
+ if PY3:
267
+ stdout, stderr = (
268
+ x.decode(sys.stdout.encoding) for x in (stdout, stderr)
269
+ )
270
+ if p.returncode == 0:
271
+ re_result = re.search(
272
+ r"Running: (\d+) Mbps.*?(\w+) Duplex", stdout
273
+ )
274
+ if re_result is not None:
275
+ speed = int(re_result.group(1))
276
+ duplex = re_result.group(2)
277
+
278
+ output_flags = ','.join(flags)
279
+ isup = 'running' in flags
280
+ duplex = duplex_map.get(duplex, NIC_DUPLEX_UNKNOWN)
281
+ ret[name] = _common.snicstats(isup, duplex, speed, mtu, output_flags)
282
+ return ret
283
+
284
+
285
+ # =====================================================================
286
+ # --- other system functions
287
+ # =====================================================================
288
+
289
+
290
+ def boot_time():
291
+ """The system boot time expressed in seconds since the epoch."""
292
+ return cext.boot_time()
293
+
294
+
295
+ def users():
296
+ """Return currently connected users as a list of namedtuples."""
297
+ retlist = []
298
+ rawlist = cext.users()
299
+ localhost = (':0.0', ':0')
300
+ for item in rawlist:
301
+ user, tty, hostname, tstamp, user_process, pid = item
302
+ # note: the underlying C function includes entries about
303
+ # system boot, run level and others. We might want
304
+ # to use them in the future.
305
+ if not user_process:
306
+ continue
307
+ if hostname in localhost:
308
+ hostname = 'localhost'
309
+ nt = _common.suser(user, tty, hostname, tstamp, pid)
310
+ retlist.append(nt)
311
+ return retlist
312
+
313
+
314
+ # =====================================================================
315
+ # --- processes
316
+ # =====================================================================
317
+
318
+
319
+ def pids():
320
+ """Returns a list of PIDs currently running on the system."""
321
+ return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()]
322
+
323
+
324
+ def pid_exists(pid):
325
+ """Check for the existence of a unix pid."""
326
+ return os.path.exists(os.path.join(get_procfs_path(), str(pid), "psinfo"))
327
+
328
+
329
+ def wrap_exceptions(fun):
330
+ """Call callable into a try/except clause and translate ENOENT,
331
+ EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
332
+ """
333
+
334
+ @functools.wraps(fun)
335
+ def wrapper(self, *args, **kwargs):
336
+ try:
337
+ return fun(self, *args, **kwargs)
338
+ except (FileNotFoundError, ProcessLookupError):
339
+ # ENOENT (no such file or directory) gets raised on open().
340
+ # ESRCH (no such process) can get raised on read() if
341
+ # process is gone in meantime.
342
+ if not pid_exists(self.pid):
343
+ raise NoSuchProcess(self.pid, self._name)
344
+ else:
345
+ raise ZombieProcess(self.pid, self._name, self._ppid)
346
+ except PermissionError:
347
+ raise AccessDenied(self.pid, self._name)
348
+
349
+ return wrapper
350
+
351
+
352
+ class Process:
353
+ """Wrapper class around underlying C implementation."""
354
+
355
+ __slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
356
+
357
+ def __init__(self, pid):
358
+ self.pid = pid
359
+ self._name = None
360
+ self._ppid = None
361
+ self._procfs_path = get_procfs_path()
362
+
363
+ def oneshot_enter(self):
364
+ self._proc_basic_info.cache_activate(self)
365
+ self._proc_cred.cache_activate(self)
366
+
367
+ def oneshot_exit(self):
368
+ self._proc_basic_info.cache_deactivate(self)
369
+ self._proc_cred.cache_deactivate(self)
370
+
371
+ @wrap_exceptions
372
+ @memoize_when_activated
373
+ def _proc_basic_info(self):
374
+ return cext.proc_basic_info(self.pid, self._procfs_path)
375
+
376
+ @wrap_exceptions
377
+ @memoize_when_activated
378
+ def _proc_cred(self):
379
+ return cext.proc_cred(self.pid, self._procfs_path)
380
+
381
+ @wrap_exceptions
382
+ def name(self):
383
+ if self.pid == 0:
384
+ return "swapper"
385
+ # note: max 16 characters
386
+ return cext.proc_name(self.pid, self._procfs_path).rstrip("\x00")
387
+
388
+ @wrap_exceptions
389
+ def exe(self):
390
+ # there is no way to get executable path in AIX other than to guess,
391
+ # and guessing is more complex than what's in the wrapping class
392
+ cmdline = self.cmdline()
393
+ if not cmdline:
394
+ return ''
395
+ exe = cmdline[0]
396
+ if os.path.sep in exe:
397
+ # relative or absolute path
398
+ if not os.path.isabs(exe):
399
+ # if cwd has changed, we're out of luck - this may be wrong!
400
+ exe = os.path.abspath(os.path.join(self.cwd(), exe))
401
+ if (
402
+ os.path.isabs(exe)
403
+ and os.path.isfile(exe)
404
+ and os.access(exe, os.X_OK)
405
+ ):
406
+ return exe
407
+ # not found, move to search in PATH using basename only
408
+ exe = os.path.basename(exe)
409
+ # search for exe name PATH
410
+ for path in os.environ["PATH"].split(":"):
411
+ possible_exe = os.path.abspath(os.path.join(path, exe))
412
+ if os.path.isfile(possible_exe) and os.access(
413
+ possible_exe, os.X_OK
414
+ ):
415
+ return possible_exe
416
+ return ''
417
+
418
+ @wrap_exceptions
419
+ def cmdline(self):
420
+ return cext.proc_args(self.pid)
421
+
422
+ @wrap_exceptions
423
+ def environ(self):
424
+ return cext.proc_environ(self.pid)
425
+
426
+ @wrap_exceptions
427
+ def create_time(self):
428
+ return self._proc_basic_info()[proc_info_map['create_time']]
429
+
430
+ @wrap_exceptions
431
+ def num_threads(self):
432
+ return self._proc_basic_info()[proc_info_map['num_threads']]
433
+
434
+ if HAS_THREADS:
435
+
436
+ @wrap_exceptions
437
+ def threads(self):
438
+ rawlist = cext.proc_threads(self.pid)
439
+ retlist = []
440
+ for thread_id, utime, stime in rawlist:
441
+ ntuple = _common.pthread(thread_id, utime, stime)
442
+ retlist.append(ntuple)
443
+ # The underlying C implementation retrieves all OS threads
444
+ # and filters them by PID. At this point we can't tell whether
445
+ # an empty list means there were no connections for process or
446
+ # process is no longer active so we force NSP in case the PID
447
+ # is no longer there.
448
+ if not retlist:
449
+ # will raise NSP if process is gone
450
+ os.stat('%s/%s' % (self._procfs_path, self.pid))
451
+ return retlist
452
+
453
+ @wrap_exceptions
454
+ def connections(self, kind='inet'):
455
+ ret = net_connections(kind, _pid=self.pid)
456
+ # The underlying C implementation retrieves all OS connections
457
+ # and filters them by PID. At this point we can't tell whether
458
+ # an empty list means there were no connections for process or
459
+ # process is no longer active so we force NSP in case the PID
460
+ # is no longer there.
461
+ if not ret:
462
+ # will raise NSP if process is gone
463
+ os.stat('%s/%s' % (self._procfs_path, self.pid))
464
+ return ret
465
+
466
+ @wrap_exceptions
467
+ def nice_get(self):
468
+ return cext_posix.getpriority(self.pid)
469
+
470
+ @wrap_exceptions
471
+ def nice_set(self, value):
472
+ return cext_posix.setpriority(self.pid, value)
473
+
474
+ @wrap_exceptions
475
+ def ppid(self):
476
+ self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
477
+ return self._ppid
478
+
479
+ @wrap_exceptions
480
+ def uids(self):
481
+ real, effective, saved, _, _, _ = self._proc_cred()
482
+ return _common.puids(real, effective, saved)
483
+
484
+ @wrap_exceptions
485
+ def gids(self):
486
+ _, _, _, real, effective, saved = self._proc_cred()
487
+ return _common.puids(real, effective, saved)
488
+
489
+ @wrap_exceptions
490
+ def cpu_times(self):
491
+ t = cext.proc_cpu_times(self.pid, self._procfs_path)
492
+ return _common.pcputimes(*t)
493
+
494
+ @wrap_exceptions
495
+ def terminal(self):
496
+ ttydev = self._proc_basic_info()[proc_info_map['ttynr']]
497
+ # convert from 64-bit dev_t to 32-bit dev_t and then map the device
498
+ ttydev = ((ttydev & 0x0000FFFF00000000) >> 16) | (ttydev & 0xFFFF)
499
+ # try to match rdev of /dev/pts/* files ttydev
500
+ for dev in glob.glob("/dev/**/*"):
501
+ if os.stat(dev).st_rdev == ttydev:
502
+ return dev
503
+ return None
504
+
505
+ @wrap_exceptions
506
+ def cwd(self):
507
+ procfs_path = self._procfs_path
508
+ try:
509
+ result = os.readlink("%s/%s/cwd" % (procfs_path, self.pid))
510
+ return result.rstrip('/')
511
+ except FileNotFoundError:
512
+ os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
513
+ return ""
514
+
515
+ @wrap_exceptions
516
+ def memory_info(self):
517
+ ret = self._proc_basic_info()
518
+ rss = ret[proc_info_map['rss']] * 1024
519
+ vms = ret[proc_info_map['vms']] * 1024
520
+ return pmem(rss, vms)
521
+
522
+ memory_full_info = memory_info
523
+
524
+ @wrap_exceptions
525
+ def status(self):
526
+ code = self._proc_basic_info()[proc_info_map['status']]
527
+ # XXX is '?' legit? (we're not supposed to return it anyway)
528
+ return PROC_STATUSES.get(code, '?')
529
+
530
+ def open_files(self):
531
+ # TODO rewrite without using procfiles (stat /proc/pid/fd/* and then
532
+ # find matching name of the inode)
533
+ p = subprocess.Popen(
534
+ ["/usr/bin/procfiles", "-n", str(self.pid)],
535
+ stdout=subprocess.PIPE,
536
+ stderr=subprocess.PIPE,
537
+ )
538
+ stdout, stderr = p.communicate()
539
+ if PY3:
540
+ stdout, stderr = (
541
+ x.decode(sys.stdout.encoding) for x in (stdout, stderr)
542
+ )
543
+ if "no such process" in stderr.lower():
544
+ raise NoSuchProcess(self.pid, self._name)
545
+ procfiles = re.findall(r"(\d+): S_IFREG.*\s*.*name:(.*)\n", stdout)
546
+ retlist = []
547
+ for fd, path in procfiles:
548
+ path = path.strip()
549
+ if path.startswith("//"):
550
+ path = path[1:]
551
+ if path.lower() == "cannot be retrieved":
552
+ continue
553
+ retlist.append(_common.popenfile(path, int(fd)))
554
+ return retlist
555
+
556
+ @wrap_exceptions
557
+ def num_fds(self):
558
+ if self.pid == 0: # no /proc/0/fd
559
+ return 0
560
+ return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
561
+
562
+ @wrap_exceptions
563
+ def num_ctx_switches(self):
564
+ return _common.pctxsw(*cext.proc_num_ctx_switches(self.pid))
565
+
566
+ @wrap_exceptions
567
+ def wait(self, timeout=None):
568
+ return _psposix.wait_pid(self.pid, timeout, self._name)
569
+
570
+ if HAS_PROC_IO_COUNTERS:
571
+
572
+ @wrap_exceptions
573
+ def io_counters(self):
574
+ try:
575
+ rc, wc, rb, wb = cext.proc_io_counters(self.pid)
576
+ except OSError:
577
+ # if process is terminated, proc_io_counters returns OSError
578
+ # instead of NSP
579
+ if not pid_exists(self.pid):
580
+ raise NoSuchProcess(self.pid, self._name)
581
+ raise
582
+ return _common.pio(rc, wc, rb, wb)
llmeval-env/lib/python3.10/site-packages/psutil/_pslinux.py ADDED
@@ -0,0 +1,2366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """Linux platform implementation."""
6
+
7
+ from __future__ import division
8
+
9
+ import base64
10
+ import collections
11
+ import errno
12
+ import functools
13
+ import glob
14
+ import os
15
+ import re
16
+ import socket
17
+ import struct
18
+ import sys
19
+ import warnings
20
+ from collections import defaultdict
21
+ from collections import namedtuple
22
+
23
+ from . import _common
24
+ from . import _psposix
25
+ from . import _psutil_linux as cext
26
+ from . import _psutil_posix as cext_posix
27
+ from ._common import NIC_DUPLEX_FULL
28
+ from ._common import NIC_DUPLEX_HALF
29
+ from ._common import NIC_DUPLEX_UNKNOWN
30
+ from ._common import AccessDenied
31
+ from ._common import NoSuchProcess
32
+ from ._common import ZombieProcess
33
+ from ._common import bcat
34
+ from ._common import cat
35
+ from ._common import debug
36
+ from ._common import decode
37
+ from ._common import get_procfs_path
38
+ from ._common import isfile_strict
39
+ from ._common import memoize
40
+ from ._common import memoize_when_activated
41
+ from ._common import open_binary
42
+ from ._common import open_text
43
+ from ._common import parse_environ_block
44
+ from ._common import path_exists_strict
45
+ from ._common import supports_ipv6
46
+ from ._common import usage_percent
47
+ from ._compat import PY3
48
+ from ._compat import FileNotFoundError
49
+ from ._compat import PermissionError
50
+ from ._compat import ProcessLookupError
51
+ from ._compat import b
52
+ from ._compat import basestring
53
+
54
+
55
+ if PY3:
56
+ import enum
57
+ else:
58
+ enum = None
59
+
60
+
61
+ # fmt: off
62
+ __extra__all__ = [
63
+ #
64
+ 'PROCFS_PATH',
65
+ # io prio constants
66
+ "IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
67
+ "IOPRIO_CLASS_IDLE",
68
+ # connection status constants
69
+ "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
70
+ "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
71
+ "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING",
72
+ ]
73
+ # fmt: on
74
+
75
+
76
+ # =====================================================================
77
+ # --- globals
78
+ # =====================================================================
79
+
80
+
81
+ POWER_SUPPLY_PATH = "/sys/class/power_supply"
82
+ HAS_PROC_SMAPS = os.path.exists('/proc/%s/smaps' % os.getpid())
83
+ HAS_PROC_SMAPS_ROLLUP = os.path.exists('/proc/%s/smaps_rollup' % os.getpid())
84
+ HAS_PROC_IO_PRIORITY = hasattr(cext, "proc_ioprio_get")
85
+ HAS_CPU_AFFINITY = hasattr(cext, "proc_cpu_affinity_get")
86
+
87
+ # Number of clock ticks per second
88
+ CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
89
+ PAGESIZE = cext_posix.getpagesize()
90
+ BOOT_TIME = None # set later
91
+ LITTLE_ENDIAN = sys.byteorder == 'little'
92
+
93
+ # "man iostat" states that sectors are equivalent with blocks and have
94
+ # a size of 512 bytes. Despite this value can be queried at runtime
95
+ # via /sys/block/{DISK}/queue/hw_sector_size and results may vary
96
+ # between 1k, 2k, or 4k... 512 appears to be a magic constant used
97
+ # throughout Linux source code:
98
+ # * https://stackoverflow.com/a/38136179/376587
99
+ # * https://lists.gt.net/linux/kernel/2241060
100
+ # * https://github.com/giampaolo/psutil/issues/1305
101
+ # * https://github.com/torvalds/linux/blob/
102
+ # 4f671fe2f9523a1ea206f63fe60a7c7b3a56d5c7/include/linux/bio.h#L99
103
+ # * https://lkml.org/lkml/2015/8/17/234
104
+ DISK_SECTOR_SIZE = 512
105
+
106
+ if enum is None:
107
+ AF_LINK = socket.AF_PACKET
108
+ else:
109
+ AddressFamily = enum.IntEnum(
110
+ 'AddressFamily', {'AF_LINK': int(socket.AF_PACKET)}
111
+ )
112
+ AF_LINK = AddressFamily.AF_LINK
113
+
114
+ # ioprio_* constants http://linux.die.net/man/2/ioprio_get
115
+ if enum is None:
116
+ IOPRIO_CLASS_NONE = 0
117
+ IOPRIO_CLASS_RT = 1
118
+ IOPRIO_CLASS_BE = 2
119
+ IOPRIO_CLASS_IDLE = 3
120
+ else:
121
+
122
+ class IOPriority(enum.IntEnum):
123
+ IOPRIO_CLASS_NONE = 0
124
+ IOPRIO_CLASS_RT = 1
125
+ IOPRIO_CLASS_BE = 2
126
+ IOPRIO_CLASS_IDLE = 3
127
+
128
+ globals().update(IOPriority.__members__)
129
+
130
+ # See:
131
+ # https://github.com/torvalds/linux/blame/master/fs/proc/array.c
132
+ # ...and (TASK_* constants):
133
+ # https://github.com/torvalds/linux/blob/master/include/linux/sched.h
134
+ PROC_STATUSES = {
135
+ "R": _common.STATUS_RUNNING,
136
+ "S": _common.STATUS_SLEEPING,
137
+ "D": _common.STATUS_DISK_SLEEP,
138
+ "T": _common.STATUS_STOPPED,
139
+ "t": _common.STATUS_TRACING_STOP,
140
+ "Z": _common.STATUS_ZOMBIE,
141
+ "X": _common.STATUS_DEAD,
142
+ "x": _common.STATUS_DEAD,
143
+ "K": _common.STATUS_WAKE_KILL,
144
+ "W": _common.STATUS_WAKING,
145
+ "I": _common.STATUS_IDLE,
146
+ "P": _common.STATUS_PARKED,
147
+ }
148
+
149
+ # https://github.com/torvalds/linux/blob/master/include/net/tcp_states.h
150
+ TCP_STATUSES = {
151
+ "01": _common.CONN_ESTABLISHED,
152
+ "02": _common.CONN_SYN_SENT,
153
+ "03": _common.CONN_SYN_RECV,
154
+ "04": _common.CONN_FIN_WAIT1,
155
+ "05": _common.CONN_FIN_WAIT2,
156
+ "06": _common.CONN_TIME_WAIT,
157
+ "07": _common.CONN_CLOSE,
158
+ "08": _common.CONN_CLOSE_WAIT,
159
+ "09": _common.CONN_LAST_ACK,
160
+ "0A": _common.CONN_LISTEN,
161
+ "0B": _common.CONN_CLOSING,
162
+ }
163
+
164
+
165
+ # =====================================================================
166
+ # --- named tuples
167
+ # =====================================================================
168
+
169
+
170
+ # fmt: off
171
+ # psutil.virtual_memory()
172
+ svmem = namedtuple(
173
+ 'svmem', ['total', 'available', 'percent', 'used', 'free',
174
+ 'active', 'inactive', 'buffers', 'cached', 'shared', 'slab'])
175
+ # psutil.disk_io_counters()
176
+ sdiskio = namedtuple(
177
+ 'sdiskio', ['read_count', 'write_count',
178
+ 'read_bytes', 'write_bytes',
179
+ 'read_time', 'write_time',
180
+ 'read_merged_count', 'write_merged_count',
181
+ 'busy_time'])
182
+ # psutil.Process().open_files()
183
+ popenfile = namedtuple(
184
+ 'popenfile', ['path', 'fd', 'position', 'mode', 'flags'])
185
+ # psutil.Process().memory_info()
186
+ pmem = namedtuple('pmem', 'rss vms shared text lib data dirty')
187
+ # psutil.Process().memory_full_info()
188
+ pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', 'pss', 'swap'))
189
+ # psutil.Process().memory_maps(grouped=True)
190
+ pmmap_grouped = namedtuple(
191
+ 'pmmap_grouped',
192
+ ['path', 'rss', 'size', 'pss', 'shared_clean', 'shared_dirty',
193
+ 'private_clean', 'private_dirty', 'referenced', 'anonymous', 'swap'])
194
+ # psutil.Process().memory_maps(grouped=False)
195
+ pmmap_ext = namedtuple(
196
+ 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
197
+ # psutil.Process.io_counters()
198
+ pio = namedtuple('pio', ['read_count', 'write_count',
199
+ 'read_bytes', 'write_bytes',
200
+ 'read_chars', 'write_chars'])
201
+ # psutil.Process.cpu_times()
202
+ pcputimes = namedtuple('pcputimes',
203
+ ['user', 'system', 'children_user', 'children_system',
204
+ 'iowait'])
205
+ # fmt: on
206
+
207
+
208
+ # =====================================================================
209
+ # --- utils
210
+ # =====================================================================
211
+
212
+
213
+ def readlink(path):
214
+ """Wrapper around os.readlink()."""
215
+ assert isinstance(path, basestring), path
216
+ path = os.readlink(path)
217
+ # readlink() might return paths containing null bytes ('\x00')
218
+ # resulting in "TypeError: must be encoded string without NULL
219
+ # bytes, not str" errors when the string is passed to other
220
+ # fs-related functions (os.*, open(), ...).
221
+ # Apparently everything after '\x00' is garbage (we can have
222
+ # ' (deleted)', 'new' and possibly others), see:
223
+ # https://github.com/giampaolo/psutil/issues/717
224
+ path = path.split('\x00')[0]
225
+ # Certain paths have ' (deleted)' appended. Usually this is
226
+ # bogus as the file actually exists. Even if it doesn't we
227
+ # don't care.
228
+ if path.endswith(' (deleted)') and not path_exists_strict(path):
229
+ path = path[:-10]
230
+ return path
231
+
232
+
233
+ def file_flags_to_mode(flags):
234
+ """Convert file's open() flags into a readable string.
235
+ Used by Process.open_files().
236
+ """
237
+ modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
238
+ mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
239
+ if flags & os.O_APPEND:
240
+ mode = mode.replace('w', 'a', 1)
241
+ mode = mode.replace('w+', 'r+')
242
+ # possible values: r, w, a, r+, a+
243
+ return mode
244
+
245
+
246
+ def is_storage_device(name):
247
+ """Return True if the given name refers to a root device (e.g.
248
+ "sda", "nvme0n1") as opposed to a logical partition (e.g. "sda1",
249
+ "nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram")
250
+ return True.
251
+ """
252
+ # Re-adapted from iostat source code, see:
253
+ # https://github.com/sysstat/sysstat/blob/
254
+ # 97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208
255
+ # Some devices may have a slash in their name (e.g. cciss/c0d0...).
256
+ name = name.replace('/', '!')
257
+ including_virtual = True
258
+ if including_virtual:
259
+ path = "/sys/block/%s" % name
260
+ else:
261
+ path = "/sys/block/%s/device" % name
262
+ return os.access(path, os.F_OK)
263
+
264
+
265
+ @memoize
266
+ def set_scputimes_ntuple(procfs_path):
267
+ """Set a namedtuple of variable fields depending on the CPU times
268
+ available on this Linux kernel version which may be:
269
+ (user, nice, system, idle, iowait, irq, softirq, [steal, [guest,
270
+ [guest_nice]]])
271
+ Used by cpu_times() function.
272
+ """
273
+ global scputimes
274
+ with open_binary('%s/stat' % procfs_path) as f:
275
+ values = f.readline().split()[1:]
276
+ fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
277
+ vlen = len(values)
278
+ if vlen >= 8:
279
+ # Linux >= 2.6.11
280
+ fields.append('steal')
281
+ if vlen >= 9:
282
+ # Linux >= 2.6.24
283
+ fields.append('guest')
284
+ if vlen >= 10:
285
+ # Linux >= 3.2.0
286
+ fields.append('guest_nice')
287
+ scputimes = namedtuple('scputimes', fields)
288
+
289
+
290
+ try:
291
+ set_scputimes_ntuple("/proc")
292
+ except Exception as err: # noqa: BLE001
293
+ # Don't want to crash at import time.
294
+ debug("ignoring exception on import: %r" % err)
295
+ scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0)
296
+
297
+
298
+ # =====================================================================
299
+ # --- prlimit
300
+ # =====================================================================
301
+
302
+ # Backport of resource.prlimit() for Python 2. Originally this was done
303
+ # in C, but CentOS-6 which we use to create manylinux wheels is too old
304
+ # and does not support prlimit() syscall. As such the resulting wheel
305
+ # would not include prlimit(), even when installed on newer systems.
306
+ # This is the only part of psutil using ctypes.
307
+
308
+ prlimit = None
309
+ try:
310
+ from resource import prlimit # python >= 3.4
311
+ except ImportError:
312
+ import ctypes
313
+
314
+ libc = ctypes.CDLL(None, use_errno=True)
315
+
316
+ if hasattr(libc, "prlimit"):
317
+
318
+ def prlimit(pid, resource_, limits=None):
319
+ class StructRlimit(ctypes.Structure):
320
+ _fields_ = [
321
+ ('rlim_cur', ctypes.c_longlong),
322
+ ('rlim_max', ctypes.c_longlong),
323
+ ]
324
+
325
+ current = StructRlimit()
326
+ if limits is None:
327
+ # get
328
+ ret = libc.prlimit(pid, resource_, None, ctypes.byref(current))
329
+ else:
330
+ # set
331
+ new = StructRlimit()
332
+ new.rlim_cur = limits[0]
333
+ new.rlim_max = limits[1]
334
+ ret = libc.prlimit(
335
+ pid, resource_, ctypes.byref(new), ctypes.byref(current)
336
+ )
337
+
338
+ if ret != 0:
339
+ errno_ = ctypes.get_errno()
340
+ raise OSError(errno_, os.strerror(errno_))
341
+ return (current.rlim_cur, current.rlim_max)
342
+
343
+
344
+ if prlimit is not None:
345
+ __extra__all__.extend(
346
+ [x for x in dir(cext) if x.startswith('RLIM') and x.isupper()]
347
+ )
348
+
349
+
350
+ # =====================================================================
351
+ # --- system memory
352
+ # =====================================================================
353
+
354
+
355
+ def calculate_avail_vmem(mems):
356
+ """Fallback for kernels < 3.14 where /proc/meminfo does not provide
357
+ "MemAvailable", see:
358
+ https://blog.famzah.net/2014/09/24/.
359
+
360
+ This code reimplements the algorithm outlined here:
361
+ https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
362
+ commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
363
+
364
+ We use this function also when "MemAvailable" returns 0 (possibly a
365
+ kernel bug, see: https://github.com/giampaolo/psutil/issues/1915).
366
+ In that case this routine matches "free" CLI tool result ("available"
367
+ column).
368
+
369
+ XXX: on recent kernels this calculation may differ by ~1.5% compared
370
+ to "MemAvailable:", as it's calculated slightly differently.
371
+ It is still way more realistic than doing (free + cached) though.
372
+ See:
373
+ * https://gitlab.com/procps-ng/procps/issues/42
374
+ * https://github.com/famzah/linux-memavailable-procfs/issues/2
375
+ """
376
+ # Note about "fallback" value. According to:
377
+ # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
378
+ # commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
379
+ # ...long ago "available" memory was calculated as (free + cached),
380
+ # We use fallback when one of these is missing from /proc/meminfo:
381
+ # "Active(file)": introduced in 2.6.28 / Dec 2008
382
+ # "Inactive(file)": introduced in 2.6.28 / Dec 2008
383
+ # "SReclaimable": introduced in 2.6.19 / Nov 2006
384
+ # /proc/zoneinfo: introduced in 2.6.13 / Aug 2005
385
+ free = mems[b'MemFree:']
386
+ fallback = free + mems.get(b"Cached:", 0)
387
+ try:
388
+ lru_active_file = mems[b'Active(file):']
389
+ lru_inactive_file = mems[b'Inactive(file):']
390
+ slab_reclaimable = mems[b'SReclaimable:']
391
+ except KeyError as err:
392
+ debug(
393
+ "%s is missing from /proc/meminfo; using an approximation for "
394
+ "calculating available memory"
395
+ % err.args[0]
396
+ )
397
+ return fallback
398
+ try:
399
+ f = open_binary('%s/zoneinfo' % get_procfs_path())
400
+ except IOError:
401
+ return fallback # kernel 2.6.13
402
+
403
+ watermark_low = 0
404
+ with f:
405
+ for line in f:
406
+ line = line.strip()
407
+ if line.startswith(b'low'):
408
+ watermark_low += int(line.split()[1])
409
+ watermark_low *= PAGESIZE
410
+
411
+ avail = free - watermark_low
412
+ pagecache = lru_active_file + lru_inactive_file
413
+ pagecache -= min(pagecache / 2, watermark_low)
414
+ avail += pagecache
415
+ avail += slab_reclaimable - min(slab_reclaimable / 2.0, watermark_low)
416
+ return int(avail)
417
+
418
+
419
+ def virtual_memory():
420
+ """Report virtual memory stats.
421
+ This implementation mimicks procps-ng-3.3.12, aka "free" CLI tool:
422
+ https://gitlab.com/procps-ng/procps/blob/
423
+ 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L778-791
424
+ The returned values are supposed to match both "free" and "vmstat -s"
425
+ CLI tools.
426
+ """
427
+ missing_fields = []
428
+ mems = {}
429
+ with open_binary('%s/meminfo' % get_procfs_path()) as f:
430
+ for line in f:
431
+ fields = line.split()
432
+ mems[fields[0]] = int(fields[1]) * 1024
433
+
434
+ # /proc doc states that the available fields in /proc/meminfo vary
435
+ # by architecture and compile options, but these 3 values are also
436
+ # returned by sysinfo(2); as such we assume they are always there.
437
+ total = mems[b'MemTotal:']
438
+ free = mems[b'MemFree:']
439
+ try:
440
+ buffers = mems[b'Buffers:']
441
+ except KeyError:
442
+ # https://github.com/giampaolo/psutil/issues/1010
443
+ buffers = 0
444
+ missing_fields.append('buffers')
445
+ try:
446
+ cached = mems[b"Cached:"]
447
+ except KeyError:
448
+ cached = 0
449
+ missing_fields.append('cached')
450
+ else:
451
+ # "free" cmdline utility sums reclaimable to cached.
452
+ # Older versions of procps used to add slab memory instead.
453
+ # This got changed in:
454
+ # https://gitlab.com/procps-ng/procps/commit/
455
+ # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
456
+ cached += mems.get(b"SReclaimable:", 0) # since kernel 2.6.19
457
+
458
+ try:
459
+ shared = mems[b'Shmem:'] # since kernel 2.6.32
460
+ except KeyError:
461
+ try:
462
+ shared = mems[b'MemShared:'] # kernels 2.4
463
+ except KeyError:
464
+ shared = 0
465
+ missing_fields.append('shared')
466
+
467
+ try:
468
+ active = mems[b"Active:"]
469
+ except KeyError:
470
+ active = 0
471
+ missing_fields.append('active')
472
+
473
+ try:
474
+ inactive = mems[b"Inactive:"]
475
+ except KeyError:
476
+ try:
477
+ inactive = (
478
+ mems[b"Inact_dirty:"]
479
+ + mems[b"Inact_clean:"]
480
+ + mems[b"Inact_laundry:"]
481
+ )
482
+ except KeyError:
483
+ inactive = 0
484
+ missing_fields.append('inactive')
485
+
486
+ try:
487
+ slab = mems[b"Slab:"]
488
+ except KeyError:
489
+ slab = 0
490
+
491
+ used = total - free - cached - buffers
492
+ if used < 0:
493
+ # May be symptomatic of running within a LCX container where such
494
+ # values will be dramatically distorted over those of the host.
495
+ used = total - free
496
+
497
+ # - starting from 4.4.0 we match free's "available" column.
498
+ # Before 4.4.0 we calculated it as (free + buffers + cached)
499
+ # which matched htop.
500
+ # - free and htop available memory differs as per:
501
+ # http://askubuntu.com/a/369589
502
+ # http://unix.stackexchange.com/a/65852/168884
503
+ # - MemAvailable has been introduced in kernel 3.14
504
+ try:
505
+ avail = mems[b'MemAvailable:']
506
+ except KeyError:
507
+ avail = calculate_avail_vmem(mems)
508
+ else:
509
+ if avail == 0:
510
+ # Yes, it can happen (probably a kernel bug):
511
+ # https://github.com/giampaolo/psutil/issues/1915
512
+ # In this case "free" CLI tool makes an estimate. We do the same,
513
+ # and it matches "free" CLI tool.
514
+ avail = calculate_avail_vmem(mems)
515
+
516
+ if avail < 0:
517
+ avail = 0
518
+ missing_fields.append('available')
519
+ elif avail > total:
520
+ # If avail is greater than total or our calculation overflows,
521
+ # that's symptomatic of running within a LCX container where such
522
+ # values will be dramatically distorted over those of the host.
523
+ # https://gitlab.com/procps-ng/procps/blob/
524
+ # 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764
525
+ avail = free
526
+
527
+ percent = usage_percent((total - avail), total, round_=1)
528
+
529
+ # Warn about missing metrics which are set to 0.
530
+ if missing_fields:
531
+ msg = "%s memory stats couldn't be determined and %s set to 0" % (
532
+ ", ".join(missing_fields),
533
+ "was" if len(missing_fields) == 1 else "were",
534
+ )
535
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
536
+
537
+ return svmem(
538
+ total,
539
+ avail,
540
+ percent,
541
+ used,
542
+ free,
543
+ active,
544
+ inactive,
545
+ buffers,
546
+ cached,
547
+ shared,
548
+ slab,
549
+ )
550
+
551
+
552
+ def swap_memory():
553
+ """Return swap memory metrics."""
554
+ mems = {}
555
+ with open_binary('%s/meminfo' % get_procfs_path()) as f:
556
+ for line in f:
557
+ fields = line.split()
558
+ mems[fields[0]] = int(fields[1]) * 1024
559
+ # We prefer /proc/meminfo over sysinfo() syscall so that
560
+ # psutil.PROCFS_PATH can be used in order to allow retrieval
561
+ # for linux containers, see:
562
+ # https://github.com/giampaolo/psutil/issues/1015
563
+ try:
564
+ total = mems[b'SwapTotal:']
565
+ free = mems[b'SwapFree:']
566
+ except KeyError:
567
+ _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
568
+ total *= unit_multiplier
569
+ free *= unit_multiplier
570
+
571
+ used = total - free
572
+ percent = usage_percent(used, total, round_=1)
573
+ # get pgin/pgouts
574
+ try:
575
+ f = open_binary("%s/vmstat" % get_procfs_path())
576
+ except IOError as err:
577
+ # see https://github.com/giampaolo/psutil/issues/722
578
+ msg = (
579
+ "'sin' and 'sout' swap memory stats couldn't "
580
+ + "be determined and were set to 0 (%s)" % str(err)
581
+ )
582
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
583
+ sin = sout = 0
584
+ else:
585
+ with f:
586
+ sin = sout = None
587
+ for line in f:
588
+ # values are expressed in 4 kilo bytes, we want
589
+ # bytes instead
590
+ if line.startswith(b'pswpin'):
591
+ sin = int(line.split(b' ')[1]) * 4 * 1024
592
+ elif line.startswith(b'pswpout'):
593
+ sout = int(line.split(b' ')[1]) * 4 * 1024
594
+ if sin is not None and sout is not None:
595
+ break
596
+ else:
597
+ # we might get here when dealing with exotic Linux
598
+ # flavors, see:
599
+ # https://github.com/giampaolo/psutil/issues/313
600
+ msg = "'sin' and 'sout' swap memory stats couldn't "
601
+ msg += "be determined and were set to 0"
602
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
603
+ sin = sout = 0
604
+ return _common.sswap(total, used, free, percent, sin, sout)
605
+
606
+
607
+ # =====================================================================
608
+ # --- CPU
609
+ # =====================================================================
610
+
611
+
612
+ def cpu_times():
613
+ """Return a named tuple representing the following system-wide
614
+ CPU times:
615
+ (user, nice, system, idle, iowait, irq, softirq [steal, [guest,
616
+ [guest_nice]]])
617
+ Last 3 fields may not be available on all Linux kernel versions.
618
+ """
619
+ procfs_path = get_procfs_path()
620
+ set_scputimes_ntuple(procfs_path)
621
+ with open_binary('%s/stat' % procfs_path) as f:
622
+ values = f.readline().split()
623
+ fields = values[1 : len(scputimes._fields) + 1]
624
+ fields = [float(x) / CLOCK_TICKS for x in fields]
625
+ return scputimes(*fields)
626
+
627
+
628
+ def per_cpu_times():
629
+ """Return a list of namedtuple representing the CPU times
630
+ for every CPU available on the system.
631
+ """
632
+ procfs_path = get_procfs_path()
633
+ set_scputimes_ntuple(procfs_path)
634
+ cpus = []
635
+ with open_binary('%s/stat' % procfs_path) as f:
636
+ # get rid of the first line which refers to system wide CPU stats
637
+ f.readline()
638
+ for line in f:
639
+ if line.startswith(b'cpu'):
640
+ values = line.split()
641
+ fields = values[1 : len(scputimes._fields) + 1]
642
+ fields = [float(x) / CLOCK_TICKS for x in fields]
643
+ entry = scputimes(*fields)
644
+ cpus.append(entry)
645
+ return cpus
646
+
647
+
648
+ def cpu_count_logical():
649
+ """Return the number of logical CPUs in the system."""
650
+ try:
651
+ return os.sysconf("SC_NPROCESSORS_ONLN")
652
+ except ValueError:
653
+ # as a second fallback we try to parse /proc/cpuinfo
654
+ num = 0
655
+ with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
656
+ for line in f:
657
+ if line.lower().startswith(b'processor'):
658
+ num += 1
659
+
660
+ # unknown format (e.g. amrel/sparc architectures), see:
661
+ # https://github.com/giampaolo/psutil/issues/200
662
+ # try to parse /proc/stat as a last resort
663
+ if num == 0:
664
+ search = re.compile(r'cpu\d')
665
+ with open_text('%s/stat' % get_procfs_path()) as f:
666
+ for line in f:
667
+ line = line.split(' ')[0]
668
+ if search.match(line):
669
+ num += 1
670
+
671
+ if num == 0:
672
+ # mimic os.cpu_count()
673
+ return None
674
+ return num
675
+
676
+
677
+ def cpu_count_cores():
678
+ """Return the number of CPU cores in the system."""
679
+ # Method #1
680
+ ls = set()
681
+ # These 2 files are the same but */core_cpus_list is newer while
682
+ # */thread_siblings_list is deprecated and may disappear in the future.
683
+ # https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst
684
+ # https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964
685
+ # https://lkml.org/lkml/2019/2/26/41
686
+ p1 = "/sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_list"
687
+ p2 = "/sys/devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list"
688
+ for path in glob.glob(p1) or glob.glob(p2):
689
+ with open_binary(path) as f:
690
+ ls.add(f.read().strip())
691
+ result = len(ls)
692
+ if result != 0:
693
+ return result
694
+
695
+ # Method #2
696
+ mapping = {}
697
+ current_info = {}
698
+ with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
699
+ for line in f:
700
+ line = line.strip().lower()
701
+ if not line:
702
+ # new section
703
+ try:
704
+ mapping[current_info[b'physical id']] = current_info[
705
+ b'cpu cores'
706
+ ]
707
+ except KeyError:
708
+ pass
709
+ current_info = {}
710
+ else:
711
+ # ongoing section
712
+ if line.startswith((b'physical id', b'cpu cores')):
713
+ key, value = line.split(b'\t:', 1)
714
+ current_info[key] = int(value)
715
+
716
+ result = sum(mapping.values())
717
+ return result or None # mimic os.cpu_count()
718
+
719
+
720
+ def cpu_stats():
721
+ """Return various CPU stats as a named tuple."""
722
+ with open_binary('%s/stat' % get_procfs_path()) as f:
723
+ ctx_switches = None
724
+ interrupts = None
725
+ soft_interrupts = None
726
+ for line in f:
727
+ if line.startswith(b'ctxt'):
728
+ ctx_switches = int(line.split()[1])
729
+ elif line.startswith(b'intr'):
730
+ interrupts = int(line.split()[1])
731
+ elif line.startswith(b'softirq'):
732
+ soft_interrupts = int(line.split()[1])
733
+ if (
734
+ ctx_switches is not None
735
+ and soft_interrupts is not None
736
+ and interrupts is not None
737
+ ):
738
+ break
739
+ syscalls = 0
740
+ return _common.scpustats(
741
+ ctx_switches, interrupts, soft_interrupts, syscalls
742
+ )
743
+
744
+
745
+ def _cpu_get_cpuinfo_freq():
746
+ """Return current CPU frequency from cpuinfo if available."""
747
+ ret = []
748
+ with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
749
+ for line in f:
750
+ if line.lower().startswith(b'cpu mhz'):
751
+ ret.append(float(line.split(b':', 1)[1]))
752
+ return ret
753
+
754
+
755
+ if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or os.path.exists(
756
+ "/sys/devices/system/cpu/cpu0/cpufreq"
757
+ ):
758
+
759
+ def cpu_freq():
760
+ """Return frequency metrics for all CPUs.
761
+ Contrarily to other OSes, Linux updates these values in
762
+ real-time.
763
+ """
764
+ cpuinfo_freqs = _cpu_get_cpuinfo_freq()
765
+ paths = glob.glob(
766
+ "/sys/devices/system/cpu/cpufreq/policy[0-9]*"
767
+ ) or glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq")
768
+ paths.sort(key=lambda x: int(re.search(r"[0-9]+", x).group()))
769
+ ret = []
770
+ pjoin = os.path.join
771
+ for i, path in enumerate(paths):
772
+ if len(paths) == len(cpuinfo_freqs):
773
+ # take cached value from cpuinfo if available, see:
774
+ # https://github.com/giampaolo/psutil/issues/1851
775
+ curr = cpuinfo_freqs[i] * 1000
776
+ else:
777
+ curr = bcat(pjoin(path, "scaling_cur_freq"), fallback=None)
778
+ if curr is None:
779
+ # Likely an old RedHat, see:
780
+ # https://github.com/giampaolo/psutil/issues/1071
781
+ curr = bcat(pjoin(path, "cpuinfo_cur_freq"), fallback=None)
782
+ if curr is None:
783
+ msg = "can't find current frequency file"
784
+ raise NotImplementedError(msg)
785
+ curr = int(curr) / 1000
786
+ max_ = int(bcat(pjoin(path, "scaling_max_freq"))) / 1000
787
+ min_ = int(bcat(pjoin(path, "scaling_min_freq"))) / 1000
788
+ ret.append(_common.scpufreq(curr, min_, max_))
789
+ return ret
790
+
791
+ else:
792
+
793
+ def cpu_freq():
794
+ """Alternate implementation using /proc/cpuinfo.
795
+ min and max frequencies are not available and are set to None.
796
+ """
797
+ return [_common.scpufreq(x, 0.0, 0.0) for x in _cpu_get_cpuinfo_freq()]
798
+
799
+
800
+ # =====================================================================
801
+ # --- network
802
+ # =====================================================================
803
+
804
+
805
+ net_if_addrs = cext_posix.net_if_addrs
806
+
807
+
808
+ class _Ipv6UnsupportedError(Exception):
809
+ pass
810
+
811
+
812
+ class Connections:
813
+ """A wrapper on top of /proc/net/* files, retrieving per-process
814
+ and system-wide open connections (TCP, UDP, UNIX) similarly to
815
+ "netstat -an".
816
+
817
+ Note: in case of UNIX sockets we're only able to determine the
818
+ local endpoint/path, not the one it's connected to.
819
+ According to [1] it would be possible but not easily.
820
+
821
+ [1] http://serverfault.com/a/417946
822
+ """
823
+
824
+ def __init__(self):
825
+ # The string represents the basename of the corresponding
826
+ # /proc/net/{proto_name} file.
827
+ tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
828
+ tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
829
+ udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
830
+ udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
831
+ unix = ("unix", socket.AF_UNIX, None)
832
+ self.tmap = {
833
+ "all": (tcp4, tcp6, udp4, udp6, unix),
834
+ "tcp": (tcp4, tcp6),
835
+ "tcp4": (tcp4,),
836
+ "tcp6": (tcp6,),
837
+ "udp": (udp4, udp6),
838
+ "udp4": (udp4,),
839
+ "udp6": (udp6,),
840
+ "unix": (unix,),
841
+ "inet": (tcp4, tcp6, udp4, udp6),
842
+ "inet4": (tcp4, udp4),
843
+ "inet6": (tcp6, udp6),
844
+ }
845
+ self._procfs_path = None
846
+
847
+ def get_proc_inodes(self, pid):
848
+ inodes = defaultdict(list)
849
+ for fd in os.listdir("%s/%s/fd" % (self._procfs_path, pid)):
850
+ try:
851
+ inode = readlink("%s/%s/fd/%s" % (self._procfs_path, pid, fd))
852
+ except (FileNotFoundError, ProcessLookupError):
853
+ # ENOENT == file which is gone in the meantime;
854
+ # os.stat('/proc/%s' % self.pid) will be done later
855
+ # to force NSP (if it's the case)
856
+ continue
857
+ except OSError as err:
858
+ if err.errno == errno.EINVAL:
859
+ # not a link
860
+ continue
861
+ if err.errno == errno.ENAMETOOLONG:
862
+ # file name too long
863
+ debug(err)
864
+ continue
865
+ raise
866
+ else:
867
+ if inode.startswith('socket:['):
868
+ # the process is using a socket
869
+ inode = inode[8:][:-1]
870
+ inodes[inode].append((pid, int(fd)))
871
+ return inodes
872
+
873
+ def get_all_inodes(self):
874
+ inodes = {}
875
+ for pid in pids():
876
+ try:
877
+ inodes.update(self.get_proc_inodes(pid))
878
+ except (FileNotFoundError, ProcessLookupError, PermissionError):
879
+ # os.listdir() is gonna raise a lot of access denied
880
+ # exceptions in case of unprivileged user; that's fine
881
+ # as we'll just end up returning a connection with PID
882
+ # and fd set to None anyway.
883
+ # Both netstat -an and lsof does the same so it's
884
+ # unlikely we can do any better.
885
+ # ENOENT just means a PID disappeared on us.
886
+ continue
887
+ return inodes
888
+
889
+ @staticmethod
890
+ def decode_address(addr, family):
891
+ """Accept an "ip:port" address as displayed in /proc/net/*
892
+ and convert it into a human readable form, like:
893
+
894
+ "0500000A:0016" -> ("10.0.0.5", 22)
895
+ "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)
896
+
897
+ The IP address portion is a little or big endian four-byte
898
+ hexadecimal number; that is, the least significant byte is listed
899
+ first, so we need to reverse the order of the bytes to convert it
900
+ to an IP address.
901
+ The port is represented as a two-byte hexadecimal number.
902
+
903
+ Reference:
904
+ http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
905
+ """
906
+ ip, port = addr.split(':')
907
+ port = int(port, 16)
908
+ # this usually refers to a local socket in listen mode with
909
+ # no end-points connected
910
+ if not port:
911
+ return ()
912
+ if PY3:
913
+ ip = ip.encode('ascii')
914
+ if family == socket.AF_INET:
915
+ # see: https://github.com/giampaolo/psutil/issues/201
916
+ if LITTLE_ENDIAN:
917
+ ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
918
+ else:
919
+ ip = socket.inet_ntop(family, base64.b16decode(ip))
920
+ else: # IPv6
921
+ ip = base64.b16decode(ip)
922
+ try:
923
+ # see: https://github.com/giampaolo/psutil/issues/201
924
+ if LITTLE_ENDIAN:
925
+ ip = socket.inet_ntop(
926
+ socket.AF_INET6,
927
+ struct.pack('>4I', *struct.unpack('<4I', ip)),
928
+ )
929
+ else:
930
+ ip = socket.inet_ntop(
931
+ socket.AF_INET6,
932
+ struct.pack('<4I', *struct.unpack('<4I', ip)),
933
+ )
934
+ except ValueError:
935
+ # see: https://github.com/giampaolo/psutil/issues/623
936
+ if not supports_ipv6():
937
+ raise _Ipv6UnsupportedError
938
+ else:
939
+ raise
940
+ return _common.addr(ip, port)
941
+
942
+ @staticmethod
943
+ def process_inet(file, family, type_, inodes, filter_pid=None):
944
+ """Parse /proc/net/tcp* and /proc/net/udp* files."""
945
+ if file.endswith('6') and not os.path.exists(file):
946
+ # IPv6 not supported
947
+ return
948
+ with open_text(file) as f:
949
+ f.readline() # skip the first line
950
+ for lineno, line in enumerate(f, 1):
951
+ try:
952
+ _, laddr, raddr, status, _, _, _, _, _, inode = (
953
+ line.split()[:10]
954
+ )
955
+ except ValueError:
956
+ raise RuntimeError(
957
+ "error while parsing %s; malformed line %s %r"
958
+ % (file, lineno, line)
959
+ )
960
+ if inode in inodes:
961
+ # # We assume inet sockets are unique, so we error
962
+ # # out if there are multiple references to the
963
+ # # same inode. We won't do this for UNIX sockets.
964
+ # if len(inodes[inode]) > 1 and family != socket.AF_UNIX:
965
+ # raise ValueError("ambiguous inode with multiple "
966
+ # "PIDs references")
967
+ pid, fd = inodes[inode][0]
968
+ else:
969
+ pid, fd = None, -1
970
+ if filter_pid is not None and filter_pid != pid:
971
+ continue
972
+ else:
973
+ if type_ == socket.SOCK_STREAM:
974
+ status = TCP_STATUSES[status]
975
+ else:
976
+ status = _common.CONN_NONE
977
+ try:
978
+ laddr = Connections.decode_address(laddr, family)
979
+ raddr = Connections.decode_address(raddr, family)
980
+ except _Ipv6UnsupportedError:
981
+ continue
982
+ yield (fd, family, type_, laddr, raddr, status, pid)
983
+
984
+ @staticmethod
985
+ def process_unix(file, family, inodes, filter_pid=None):
986
+ """Parse /proc/net/unix files."""
987
+ with open_text(file) as f:
988
+ f.readline() # skip the first line
989
+ for line in f:
990
+ tokens = line.split()
991
+ try:
992
+ _, _, _, _, type_, _, inode = tokens[0:7]
993
+ except ValueError:
994
+ if ' ' not in line:
995
+ # see: https://github.com/giampaolo/psutil/issues/766
996
+ continue
997
+ raise RuntimeError(
998
+ "error while parsing %s; malformed line %r"
999
+ % (file, line)
1000
+ )
1001
+ if inode in inodes: # noqa
1002
+ # With UNIX sockets we can have a single inode
1003
+ # referencing many file descriptors.
1004
+ pairs = inodes[inode]
1005
+ else:
1006
+ pairs = [(None, -1)]
1007
+ for pid, fd in pairs:
1008
+ if filter_pid is not None and filter_pid != pid:
1009
+ continue
1010
+ else:
1011
+ path = tokens[-1] if len(tokens) == 8 else ''
1012
+ type_ = _common.socktype_to_enum(int(type_))
1013
+ # XXX: determining the remote endpoint of a
1014
+ # UNIX socket on Linux is not possible, see:
1015
+ # https://serverfault.com/questions/252723/
1016
+ raddr = ""
1017
+ status = _common.CONN_NONE
1018
+ yield (fd, family, type_, path, raddr, status, pid)
1019
+
1020
+ def retrieve(self, kind, pid=None):
1021
+ if kind not in self.tmap:
1022
+ raise ValueError(
1023
+ "invalid %r kind argument; choose between %s"
1024
+ % (kind, ', '.join([repr(x) for x in self.tmap]))
1025
+ )
1026
+ self._procfs_path = get_procfs_path()
1027
+ if pid is not None:
1028
+ inodes = self.get_proc_inodes(pid)
1029
+ if not inodes:
1030
+ # no connections for this process
1031
+ return []
1032
+ else:
1033
+ inodes = self.get_all_inodes()
1034
+ ret = set()
1035
+ for proto_name, family, type_ in self.tmap[kind]:
1036
+ path = "%s/net/%s" % (self._procfs_path, proto_name)
1037
+ if family in (socket.AF_INET, socket.AF_INET6):
1038
+ ls = self.process_inet(
1039
+ path, family, type_, inodes, filter_pid=pid
1040
+ )
1041
+ else:
1042
+ ls = self.process_unix(path, family, inodes, filter_pid=pid)
1043
+ for fd, family, type_, laddr, raddr, status, bound_pid in ls:
1044
+ if pid:
1045
+ conn = _common.pconn(
1046
+ fd, family, type_, laddr, raddr, status
1047
+ )
1048
+ else:
1049
+ conn = _common.sconn(
1050
+ fd, family, type_, laddr, raddr, status, bound_pid
1051
+ )
1052
+ ret.add(conn)
1053
+ return list(ret)
1054
+
1055
+
1056
+ _connections = Connections()
1057
+
1058
+
1059
+ def net_connections(kind='inet'):
1060
+ """Return system-wide open connections."""
1061
+ return _connections.retrieve(kind)
1062
+
1063
+
1064
+ def net_io_counters():
1065
+ """Return network I/O statistics for every network interface
1066
+ installed on the system as a dict of raw tuples.
1067
+ """
1068
+ with open_text("%s/net/dev" % get_procfs_path()) as f:
1069
+ lines = f.readlines()
1070
+ retdict = {}
1071
+ for line in lines[2:]:
1072
+ colon = line.rfind(':')
1073
+ assert colon > 0, repr(line)
1074
+ name = line[:colon].strip()
1075
+ fields = line[colon + 1 :].strip().split()
1076
+
1077
+ # in
1078
+ (
1079
+ bytes_recv,
1080
+ packets_recv,
1081
+ errin,
1082
+ dropin,
1083
+ fifoin, # unused
1084
+ framein, # unused
1085
+ compressedin, # unused
1086
+ multicastin, # unused
1087
+ # out
1088
+ bytes_sent,
1089
+ packets_sent,
1090
+ errout,
1091
+ dropout,
1092
+ fifoout, # unused
1093
+ collisionsout, # unused
1094
+ carrierout, # unused
1095
+ compressedout,
1096
+ ) = map(int, fields)
1097
+
1098
+ retdict[name] = (
1099
+ bytes_sent,
1100
+ bytes_recv,
1101
+ packets_sent,
1102
+ packets_recv,
1103
+ errin,
1104
+ errout,
1105
+ dropin,
1106
+ dropout,
1107
+ )
1108
+ return retdict
1109
+
1110
+
1111
+ def net_if_stats():
1112
+ """Get NIC stats (isup, duplex, speed, mtu)."""
1113
+ duplex_map = {
1114
+ cext.DUPLEX_FULL: NIC_DUPLEX_FULL,
1115
+ cext.DUPLEX_HALF: NIC_DUPLEX_HALF,
1116
+ cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN,
1117
+ }
1118
+ names = net_io_counters().keys()
1119
+ ret = {}
1120
+ for name in names:
1121
+ try:
1122
+ mtu = cext_posix.net_if_mtu(name)
1123
+ flags = cext_posix.net_if_flags(name)
1124
+ duplex, speed = cext.net_if_duplex_speed(name)
1125
+ except OSError as err:
1126
+ # https://github.com/giampaolo/psutil/issues/1279
1127
+ if err.errno != errno.ENODEV:
1128
+ raise
1129
+ else:
1130
+ debug(err)
1131
+ else:
1132
+ output_flags = ','.join(flags)
1133
+ isup = 'running' in flags
1134
+ ret[name] = _common.snicstats(
1135
+ isup, duplex_map[duplex], speed, mtu, output_flags
1136
+ )
1137
+ return ret
1138
+
1139
+
1140
+ # =====================================================================
1141
+ # --- disks
1142
+ # =====================================================================
1143
+
1144
+
1145
+ disk_usage = _psposix.disk_usage
1146
+
1147
+
1148
+ def disk_io_counters(perdisk=False):
1149
+ """Return disk I/O statistics for every disk installed on the
1150
+ system as a dict of raw tuples.
1151
+ """
1152
+
1153
+ def read_procfs():
1154
+ # OK, this is a bit confusing. The format of /proc/diskstats can
1155
+ # have 3 variations.
1156
+ # On Linux 2.4 each line has always 15 fields, e.g.:
1157
+ # "3 0 8 hda 8 8 8 8 8 8 8 8 8 8 8"
1158
+ # On Linux 2.6+ each line *usually* has 14 fields, and the disk
1159
+ # name is in another position, like this:
1160
+ # "3 0 hda 8 8 8 8 8 8 8 8 8 8 8"
1161
+ # ...unless (Linux 2.6) the line refers to a partition instead
1162
+ # of a disk, in which case the line has less fields (7):
1163
+ # "3 1 hda1 8 8 8 8"
1164
+ # 4.18+ has 4 fields added:
1165
+ # "3 0 hda 8 8 8 8 8 8 8 8 8 8 8 0 0 0 0"
1166
+ # 5.5 has 2 more fields.
1167
+ # See:
1168
+ # https://www.kernel.org/doc/Documentation/iostats.txt
1169
+ # https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats
1170
+ with open_text("%s/diskstats" % get_procfs_path()) as f:
1171
+ lines = f.readlines()
1172
+ for line in lines:
1173
+ fields = line.split()
1174
+ flen = len(fields)
1175
+ # fmt: off
1176
+ if flen == 15:
1177
+ # Linux 2.4
1178
+ name = fields[3]
1179
+ reads = int(fields[2])
1180
+ (reads_merged, rbytes, rtime, writes, writes_merged,
1181
+ wbytes, wtime, _, busy_time, _) = map(int, fields[4:14])
1182
+ elif flen == 14 or flen >= 18:
1183
+ # Linux 2.6+, line referring to a disk
1184
+ name = fields[2]
1185
+ (reads, reads_merged, rbytes, rtime, writes, writes_merged,
1186
+ wbytes, wtime, _, busy_time, _) = map(int, fields[3:14])
1187
+ elif flen == 7:
1188
+ # Linux 2.6+, line referring to a partition
1189
+ name = fields[2]
1190
+ reads, rbytes, writes, wbytes = map(int, fields[3:])
1191
+ rtime = wtime = reads_merged = writes_merged = busy_time = 0
1192
+ else:
1193
+ raise ValueError("not sure how to interpret line %r" % line)
1194
+ yield (name, reads, writes, rbytes, wbytes, rtime, wtime,
1195
+ reads_merged, writes_merged, busy_time)
1196
+ # fmt: on
1197
+
1198
+ def read_sysfs():
1199
+ for block in os.listdir('/sys/block'):
1200
+ for root, _, files in os.walk(os.path.join('/sys/block', block)):
1201
+ if 'stat' not in files:
1202
+ continue
1203
+ with open_text(os.path.join(root, 'stat')) as f:
1204
+ fields = f.read().strip().split()
1205
+ name = os.path.basename(root)
1206
+ # fmt: off
1207
+ (reads, reads_merged, rbytes, rtime, writes, writes_merged,
1208
+ wbytes, wtime, _, busy_time) = map(int, fields[:10])
1209
+ yield (name, reads, writes, rbytes, wbytes, rtime,
1210
+ wtime, reads_merged, writes_merged, busy_time)
1211
+ # fmt: on
1212
+
1213
+ if os.path.exists('%s/diskstats' % get_procfs_path()):
1214
+ gen = read_procfs()
1215
+ elif os.path.exists('/sys/block'):
1216
+ gen = read_sysfs()
1217
+ else:
1218
+ raise NotImplementedError(
1219
+ "%s/diskstats nor /sys/block filesystem are available on this "
1220
+ "system"
1221
+ % get_procfs_path()
1222
+ )
1223
+
1224
+ retdict = {}
1225
+ for entry in gen:
1226
+ # fmt: off
1227
+ (name, reads, writes, rbytes, wbytes, rtime, wtime, reads_merged,
1228
+ writes_merged, busy_time) = entry
1229
+ if not perdisk and not is_storage_device(name):
1230
+ # perdisk=False means we want to calculate totals so we skip
1231
+ # partitions (e.g. 'sda1', 'nvme0n1p1') and only include
1232
+ # base disk devices (e.g. 'sda', 'nvme0n1'). Base disks
1233
+ # include a total of all their partitions + some extra size
1234
+ # of their own:
1235
+ # $ cat /proc/diskstats
1236
+ # 259 0 sda 10485760 ...
1237
+ # 259 1 sda1 5186039 ...
1238
+ # 259 1 sda2 5082039 ...
1239
+ # See:
1240
+ # https://github.com/giampaolo/psutil/pull/1313
1241
+ continue
1242
+
1243
+ rbytes *= DISK_SECTOR_SIZE
1244
+ wbytes *= DISK_SECTOR_SIZE
1245
+ retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime,
1246
+ reads_merged, writes_merged, busy_time)
1247
+ # fmt: on
1248
+
1249
+ return retdict
1250
+
1251
+
1252
+ class RootFsDeviceFinder:
1253
+ """disk_partitions() may return partitions with device == "/dev/root"
1254
+ or "rootfs". This container class uses different strategies to try to
1255
+ obtain the real device path. Resources:
1256
+ https://bootlin.com/blog/find-root-device/
1257
+ https://www.systutorials.com/how-to-find-the-disk-where-root-is-on-in-bash-on-linux/.
1258
+ """
1259
+
1260
+ __slots__ = ['major', 'minor']
1261
+
1262
+ def __init__(self):
1263
+ dev = os.stat("/").st_dev
1264
+ self.major = os.major(dev)
1265
+ self.minor = os.minor(dev)
1266
+
1267
+ def ask_proc_partitions(self):
1268
+ with open_text("%s/partitions" % get_procfs_path()) as f:
1269
+ for line in f.readlines()[2:]:
1270
+ fields = line.split()
1271
+ if len(fields) < 4: # just for extra safety
1272
+ continue
1273
+ major = int(fields[0]) if fields[0].isdigit() else None
1274
+ minor = int(fields[1]) if fields[1].isdigit() else None
1275
+ name = fields[3]
1276
+ if major == self.major and minor == self.minor:
1277
+ if name: # just for extra safety
1278
+ return "/dev/%s" % name
1279
+
1280
+ def ask_sys_dev_block(self):
1281
+ path = "/sys/dev/block/%s:%s/uevent" % (self.major, self.minor)
1282
+ with open_text(path) as f:
1283
+ for line in f:
1284
+ if line.startswith("DEVNAME="):
1285
+ name = line.strip().rpartition("DEVNAME=")[2]
1286
+ if name: # just for extra safety
1287
+ return "/dev/%s" % name
1288
+
1289
+ def ask_sys_class_block(self):
1290
+ needle = "%s:%s" % (self.major, self.minor)
1291
+ files = glob.iglob("/sys/class/block/*/dev")
1292
+ for file in files:
1293
+ try:
1294
+ f = open_text(file)
1295
+ except FileNotFoundError: # race condition
1296
+ continue
1297
+ else:
1298
+ with f:
1299
+ data = f.read().strip()
1300
+ if data == needle:
1301
+ name = os.path.basename(os.path.dirname(file))
1302
+ return "/dev/%s" % name
1303
+
1304
+ def find(self):
1305
+ path = None
1306
+ if path is None:
1307
+ try:
1308
+ path = self.ask_proc_partitions()
1309
+ except (IOError, OSError) as err:
1310
+ debug(err)
1311
+ if path is None:
1312
+ try:
1313
+ path = self.ask_sys_dev_block()
1314
+ except (IOError, OSError) as err:
1315
+ debug(err)
1316
+ if path is None:
1317
+ try:
1318
+ path = self.ask_sys_class_block()
1319
+ except (IOError, OSError) as err:
1320
+ debug(err)
1321
+ # We use exists() because the "/dev/*" part of the path is hard
1322
+ # coded, so we want to be sure.
1323
+ if path is not None and os.path.exists(path):
1324
+ return path
1325
+
1326
+
1327
+ def disk_partitions(all=False):
1328
+ """Return mounted disk partitions as a list of namedtuples."""
1329
+ fstypes = set()
1330
+ procfs_path = get_procfs_path()
1331
+ if not all:
1332
+ with open_text("%s/filesystems" % procfs_path) as f:
1333
+ for line in f:
1334
+ line = line.strip()
1335
+ if not line.startswith("nodev"):
1336
+ fstypes.add(line.strip())
1337
+ else:
1338
+ # ignore all lines starting with "nodev" except "nodev zfs"
1339
+ fstype = line.split("\t")[1]
1340
+ if fstype == "zfs":
1341
+ fstypes.add("zfs")
1342
+
1343
+ # See: https://github.com/giampaolo/psutil/issues/1307
1344
+ if procfs_path == "/proc" and os.path.isfile('/etc/mtab'):
1345
+ mounts_path = os.path.realpath("/etc/mtab")
1346
+ else:
1347
+ mounts_path = os.path.realpath("%s/self/mounts" % procfs_path)
1348
+
1349
+ retlist = []
1350
+ partitions = cext.disk_partitions(mounts_path)
1351
+ for partition in partitions:
1352
+ device, mountpoint, fstype, opts = partition
1353
+ if device == 'none':
1354
+ device = ''
1355
+ if device in ("/dev/root", "rootfs"):
1356
+ device = RootFsDeviceFinder().find() or device
1357
+ if not all:
1358
+ if device == '' or fstype not in fstypes:
1359
+ continue
1360
+ maxfile = maxpath = None # set later
1361
+ ntuple = _common.sdiskpart(
1362
+ device, mountpoint, fstype, opts, maxfile, maxpath
1363
+ )
1364
+ retlist.append(ntuple)
1365
+
1366
+ return retlist
1367
+
1368
+
1369
+ # =====================================================================
1370
+ # --- sensors
1371
+ # =====================================================================
1372
+
1373
+
1374
+ def sensors_temperatures():
1375
+ """Return hardware (CPU and others) temperatures as a dict
1376
+ including hardware name, label, current, max and critical
1377
+ temperatures.
1378
+
1379
+ Implementation notes:
1380
+ - /sys/class/hwmon looks like the most recent interface to
1381
+ retrieve this info, and this implementation relies on it
1382
+ only (old distros will probably use something else)
1383
+ - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
1384
+ - /sys/class/thermal/thermal_zone* is another one but it's more
1385
+ difficult to parse
1386
+ """
1387
+ ret = collections.defaultdict(list)
1388
+ basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*')
1389
+ # CentOS has an intermediate /device directory:
1390
+ # https://github.com/giampaolo/psutil/issues/971
1391
+ # https://github.com/nicolargo/glances/issues/1060
1392
+ basenames.extend(glob.glob('/sys/class/hwmon/hwmon*/device/temp*_*'))
1393
+ basenames = sorted(set([x.split('_')[0] for x in basenames]))
1394
+
1395
+ # Only add the coretemp hwmon entries if they're not already in
1396
+ # /sys/class/hwmon/
1397
+ # https://github.com/giampaolo/psutil/issues/1708
1398
+ # https://github.com/giampaolo/psutil/pull/1648
1399
+ basenames2 = glob.glob(
1400
+ '/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*'
1401
+ )
1402
+ repl = re.compile('/sys/devices/platform/coretemp.*/hwmon/')
1403
+ for name in basenames2:
1404
+ altname = repl.sub('/sys/class/hwmon/', name)
1405
+ if altname not in basenames:
1406
+ basenames.append(name)
1407
+
1408
+ for base in basenames:
1409
+ try:
1410
+ path = base + '_input'
1411
+ current = float(bcat(path)) / 1000.0
1412
+ path = os.path.join(os.path.dirname(base), 'name')
1413
+ unit_name = cat(path).strip()
1414
+ except (IOError, OSError, ValueError):
1415
+ # A lot of things can go wrong here, so let's just skip the
1416
+ # whole entry. Sure thing is Linux's /sys/class/hwmon really
1417
+ # is a stinky broken mess.
1418
+ # https://github.com/giampaolo/psutil/issues/1009
1419
+ # https://github.com/giampaolo/psutil/issues/1101
1420
+ # https://github.com/giampaolo/psutil/issues/1129
1421
+ # https://github.com/giampaolo/psutil/issues/1245
1422
+ # https://github.com/giampaolo/psutil/issues/1323
1423
+ continue
1424
+
1425
+ high = bcat(base + '_max', fallback=None)
1426
+ critical = bcat(base + '_crit', fallback=None)
1427
+ label = cat(base + '_label', fallback='').strip()
1428
+
1429
+ if high is not None:
1430
+ try:
1431
+ high = float(high) / 1000.0
1432
+ except ValueError:
1433
+ high = None
1434
+ if critical is not None:
1435
+ try:
1436
+ critical = float(critical) / 1000.0
1437
+ except ValueError:
1438
+ critical = None
1439
+
1440
+ ret[unit_name].append((label, current, high, critical))
1441
+
1442
+ # Indication that no sensors were detected in /sys/class/hwmon/
1443
+ if not basenames:
1444
+ basenames = glob.glob('/sys/class/thermal/thermal_zone*')
1445
+ basenames = sorted(set(basenames))
1446
+
1447
+ for base in basenames:
1448
+ try:
1449
+ path = os.path.join(base, 'temp')
1450
+ current = float(bcat(path)) / 1000.0
1451
+ path = os.path.join(base, 'type')
1452
+ unit_name = cat(path).strip()
1453
+ except (IOError, OSError, ValueError) as err:
1454
+ debug(err)
1455
+ continue
1456
+
1457
+ trip_paths = glob.glob(base + '/trip_point*')
1458
+ trip_points = set([
1459
+ '_'.join(os.path.basename(p).split('_')[0:3])
1460
+ for p in trip_paths
1461
+ ])
1462
+ critical = None
1463
+ high = None
1464
+ for trip_point in trip_points:
1465
+ path = os.path.join(base, trip_point + "_type")
1466
+ trip_type = cat(path, fallback='').strip()
1467
+ if trip_type == 'critical':
1468
+ critical = bcat(
1469
+ os.path.join(base, trip_point + "_temp"), fallback=None
1470
+ )
1471
+ elif trip_type == 'high':
1472
+ high = bcat(
1473
+ os.path.join(base, trip_point + "_temp"), fallback=None
1474
+ )
1475
+
1476
+ if high is not None:
1477
+ try:
1478
+ high = float(high) / 1000.0
1479
+ except ValueError:
1480
+ high = None
1481
+ if critical is not None:
1482
+ try:
1483
+ critical = float(critical) / 1000.0
1484
+ except ValueError:
1485
+ critical = None
1486
+
1487
+ ret[unit_name].append(('', current, high, critical))
1488
+
1489
+ return dict(ret)
1490
+
1491
+
1492
+ def sensors_fans():
1493
+ """Return hardware fans info (for CPU and other peripherals) as a
1494
+ dict including hardware label and current speed.
1495
+
1496
+ Implementation notes:
1497
+ - /sys/class/hwmon looks like the most recent interface to
1498
+ retrieve this info, and this implementation relies on it
1499
+ only (old distros will probably use something else)
1500
+ - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
1501
+ """
1502
+ ret = collections.defaultdict(list)
1503
+ basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*')
1504
+ if not basenames:
1505
+ # CentOS has an intermediate /device directory:
1506
+ # https://github.com/giampaolo/psutil/issues/971
1507
+ basenames = glob.glob('/sys/class/hwmon/hwmon*/device/fan*_*')
1508
+
1509
+ basenames = sorted(set([x.split('_')[0] for x in basenames]))
1510
+ for base in basenames:
1511
+ try:
1512
+ current = int(bcat(base + '_input'))
1513
+ except (IOError, OSError) as err:
1514
+ debug(err)
1515
+ continue
1516
+ unit_name = cat(os.path.join(os.path.dirname(base), 'name')).strip()
1517
+ label = cat(base + '_label', fallback='').strip()
1518
+ ret[unit_name].append(_common.sfan(label, current))
1519
+
1520
+ return dict(ret)
1521
+
1522
+
1523
+ def sensors_battery():
1524
+ """Return battery information.
1525
+ Implementation note: it appears /sys/class/power_supply/BAT0/
1526
+ directory structure may vary and provide files with the same
1527
+ meaning but under different names, see:
1528
+ https://github.com/giampaolo/psutil/issues/966.
1529
+ """
1530
+ null = object()
1531
+
1532
+ def multi_bcat(*paths):
1533
+ """Attempt to read the content of multiple files which may
1534
+ not exist. If none of them exist return None.
1535
+ """
1536
+ for path in paths:
1537
+ ret = bcat(path, fallback=null)
1538
+ if ret != null:
1539
+ try:
1540
+ return int(ret)
1541
+ except ValueError:
1542
+ return ret.strip()
1543
+ return None
1544
+
1545
+ bats = [
1546
+ x
1547
+ for x in os.listdir(POWER_SUPPLY_PATH)
1548
+ if x.startswith('BAT') or 'battery' in x.lower()
1549
+ ]
1550
+ if not bats:
1551
+ return None
1552
+ # Get the first available battery. Usually this is "BAT0", except
1553
+ # some rare exceptions:
1554
+ # https://github.com/giampaolo/psutil/issues/1238
1555
+ root = os.path.join(POWER_SUPPLY_PATH, sorted(bats)[0])
1556
+
1557
+ # Base metrics.
1558
+ energy_now = multi_bcat(root + "/energy_now", root + "/charge_now")
1559
+ power_now = multi_bcat(root + "/power_now", root + "/current_now")
1560
+ energy_full = multi_bcat(root + "/energy_full", root + "/charge_full")
1561
+ time_to_empty = multi_bcat(root + "/time_to_empty_now")
1562
+
1563
+ # Percent. If we have energy_full the percentage will be more
1564
+ # accurate compared to reading /capacity file (float vs. int).
1565
+ if energy_full is not None and energy_now is not None:
1566
+ try:
1567
+ percent = 100.0 * energy_now / energy_full
1568
+ except ZeroDivisionError:
1569
+ percent = 0.0
1570
+ else:
1571
+ percent = int(cat(root + "/capacity", fallback=-1))
1572
+ if percent == -1:
1573
+ return None
1574
+
1575
+ # Is AC power cable plugged in?
1576
+ # Note: AC0 is not always available and sometimes (e.g. CentOS7)
1577
+ # it's called "AC".
1578
+ power_plugged = None
1579
+ online = multi_bcat(
1580
+ os.path.join(POWER_SUPPLY_PATH, "AC0/online"),
1581
+ os.path.join(POWER_SUPPLY_PATH, "AC/online"),
1582
+ )
1583
+ if online is not None:
1584
+ power_plugged = online == 1
1585
+ else:
1586
+ status = cat(root + "/status", fallback="").strip().lower()
1587
+ if status == "discharging":
1588
+ power_plugged = False
1589
+ elif status in ("charging", "full"):
1590
+ power_plugged = True
1591
+
1592
+ # Seconds left.
1593
+ # Note to self: we may also calculate the charging ETA as per:
1594
+ # https://github.com/thialfihar/dotfiles/blob/
1595
+ # 013937745fd9050c30146290e8f963d65c0179e6/bin/battery.py#L55
1596
+ if power_plugged:
1597
+ secsleft = _common.POWER_TIME_UNLIMITED
1598
+ elif energy_now is not None and power_now is not None:
1599
+ try:
1600
+ secsleft = int(energy_now / power_now * 3600)
1601
+ except ZeroDivisionError:
1602
+ secsleft = _common.POWER_TIME_UNKNOWN
1603
+ elif time_to_empty is not None:
1604
+ secsleft = int(time_to_empty * 60)
1605
+ if secsleft < 0:
1606
+ secsleft = _common.POWER_TIME_UNKNOWN
1607
+ else:
1608
+ secsleft = _common.POWER_TIME_UNKNOWN
1609
+
1610
+ return _common.sbattery(percent, secsleft, power_plugged)
1611
+
1612
+
1613
+ # =====================================================================
1614
+ # --- other system functions
1615
+ # =====================================================================
1616
+
1617
+
1618
+ def users():
1619
+ """Return currently connected users as a list of namedtuples."""
1620
+ retlist = []
1621
+ rawlist = cext.users()
1622
+ for item in rawlist:
1623
+ user, tty, hostname, tstamp, pid = item
1624
+ nt = _common.suser(user, tty or None, hostname, tstamp, pid)
1625
+ retlist.append(nt)
1626
+ return retlist
1627
+
1628
+
1629
+ def boot_time():
1630
+ """Return the system boot time expressed in seconds since the epoch."""
1631
+ global BOOT_TIME
1632
+ path = '%s/stat' % get_procfs_path()
1633
+ with open_binary(path) as f:
1634
+ for line in f:
1635
+ if line.startswith(b'btime'):
1636
+ ret = float(line.strip().split()[1])
1637
+ BOOT_TIME = ret
1638
+ return ret
1639
+ raise RuntimeError("line 'btime' not found in %s" % path)
1640
+
1641
+
1642
+ # =====================================================================
1643
+ # --- processes
1644
+ # =====================================================================
1645
+
1646
+
1647
+ def pids():
1648
+ """Returns a list of PIDs currently running on the system."""
1649
+ return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]
1650
+
1651
+
1652
+ def pid_exists(pid):
1653
+ """Check for the existence of a unix PID. Linux TIDs are not
1654
+ supported (always return False).
1655
+ """
1656
+ if not _psposix.pid_exists(pid):
1657
+ return False
1658
+ else:
1659
+ # Linux's apparently does not distinguish between PIDs and TIDs
1660
+ # (thread IDs).
1661
+ # listdir("/proc") won't show any TID (only PIDs) but
1662
+ # os.stat("/proc/{tid}") will succeed if {tid} exists.
1663
+ # os.kill() can also be passed a TID. This is quite confusing.
1664
+ # In here we want to enforce this distinction and support PIDs
1665
+ # only, see:
1666
+ # https://github.com/giampaolo/psutil/issues/687
1667
+ try:
1668
+ # Note: already checked that this is faster than using a
1669
+ # regular expr. Also (a lot) faster than doing
1670
+ # 'return pid in pids()'
1671
+ path = "%s/%s/status" % (get_procfs_path(), pid)
1672
+ with open_binary(path) as f:
1673
+ for line in f:
1674
+ if line.startswith(b"Tgid:"):
1675
+ tgid = int(line.split()[1])
1676
+ # If tgid and pid are the same then we're
1677
+ # dealing with a process PID.
1678
+ return tgid == pid
1679
+ raise ValueError("'Tgid' line not found in %s" % path)
1680
+ except (EnvironmentError, ValueError):
1681
+ return pid in pids()
1682
+
1683
+
1684
+ def ppid_map():
1685
+ """Obtain a {pid: ppid, ...} dict for all running processes in
1686
+ one shot. Used to speed up Process.children().
1687
+ """
1688
+ ret = {}
1689
+ procfs_path = get_procfs_path()
1690
+ for pid in pids():
1691
+ try:
1692
+ with open_binary("%s/%s/stat" % (procfs_path, pid)) as f:
1693
+ data = f.read()
1694
+ except (FileNotFoundError, ProcessLookupError):
1695
+ # Note: we should be able to access /stat for all processes
1696
+ # aka it's unlikely we'll bump into EPERM, which is good.
1697
+ pass
1698
+ else:
1699
+ rpar = data.rfind(b')')
1700
+ dset = data[rpar + 2 :].split()
1701
+ ppid = int(dset[1])
1702
+ ret[pid] = ppid
1703
+ return ret
1704
+
1705
+
1706
+ def wrap_exceptions(fun):
1707
+ """Decorator which translates bare OSError and IOError exceptions
1708
+ into NoSuchProcess and AccessDenied.
1709
+ """
1710
+
1711
+ @functools.wraps(fun)
1712
+ def wrapper(self, *args, **kwargs):
1713
+ try:
1714
+ return fun(self, *args, **kwargs)
1715
+ except PermissionError:
1716
+ raise AccessDenied(self.pid, self._name)
1717
+ except ProcessLookupError:
1718
+ self._raise_if_zombie()
1719
+ raise NoSuchProcess(self.pid, self._name)
1720
+ except FileNotFoundError:
1721
+ self._raise_if_zombie()
1722
+ if not os.path.exists("%s/%s" % (self._procfs_path, self.pid)):
1723
+ raise NoSuchProcess(self.pid, self._name)
1724
+ raise
1725
+
1726
+ return wrapper
1727
+
1728
+
1729
+ class Process:
1730
+ """Linux process implementation."""
1731
+
1732
+ __slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
1733
+
1734
+ def __init__(self, pid):
1735
+ self.pid = pid
1736
+ self._name = None
1737
+ self._ppid = None
1738
+ self._procfs_path = get_procfs_path()
1739
+
1740
+ def _is_zombie(self):
1741
+ # Note: most of the times Linux is able to return info about the
1742
+ # process even if it's a zombie, and /proc/{pid} will exist.
1743
+ # There are some exceptions though, like exe(), cmdline() and
1744
+ # memory_maps(). In these cases /proc/{pid}/{file} exists but
1745
+ # it's empty. Instead of returning a "null" value we'll raise an
1746
+ # exception.
1747
+ try:
1748
+ data = bcat("%s/%s/stat" % (self._procfs_path, self.pid))
1749
+ except (IOError, OSError):
1750
+ return False
1751
+ else:
1752
+ rpar = data.rfind(b')')
1753
+ status = data[rpar + 2 : rpar + 3]
1754
+ return status == b"Z"
1755
+
1756
+ def _raise_if_zombie(self):
1757
+ if self._is_zombie():
1758
+ raise ZombieProcess(self.pid, self._name, self._ppid)
1759
+
1760
+ def _raise_if_not_alive(self):
1761
+ """Raise NSP if the process disappeared on us."""
1762
+ # For those C function who do not raise NSP, possibly returning
1763
+ # incorrect or incomplete result.
1764
+ os.stat('%s/%s' % (self._procfs_path, self.pid))
1765
+
1766
+ @wrap_exceptions
1767
+ @memoize_when_activated
1768
+ def _parse_stat_file(self):
1769
+ """Parse /proc/{pid}/stat file and return a dict with various
1770
+ process info.
1771
+ Using "man proc" as a reference: where "man proc" refers to
1772
+ position N always subtract 3 (e.g ppid position 4 in
1773
+ 'man proc' == position 1 in here).
1774
+ The return value is cached in case oneshot() ctx manager is
1775
+ in use.
1776
+ """
1777
+ data = bcat("%s/%s/stat" % (self._procfs_path, self.pid))
1778
+ # Process name is between parentheses. It can contain spaces and
1779
+ # other parentheses. This is taken into account by looking for
1780
+ # the first occurrence of "(" and the last occurrence of ")".
1781
+ rpar = data.rfind(b')')
1782
+ name = data[data.find(b'(') + 1 : rpar]
1783
+ fields = data[rpar + 2 :].split()
1784
+
1785
+ ret = {}
1786
+ ret['name'] = name
1787
+ ret['status'] = fields[0]
1788
+ ret['ppid'] = fields[1]
1789
+ ret['ttynr'] = fields[4]
1790
+ ret['utime'] = fields[11]
1791
+ ret['stime'] = fields[12]
1792
+ ret['children_utime'] = fields[13]
1793
+ ret['children_stime'] = fields[14]
1794
+ ret['create_time'] = fields[19]
1795
+ ret['cpu_num'] = fields[36]
1796
+ ret['blkio_ticks'] = fields[39] # aka 'delayacct_blkio_ticks'
1797
+
1798
+ return ret
1799
+
1800
+ @wrap_exceptions
1801
+ @memoize_when_activated
1802
+ def _read_status_file(self):
1803
+ """Read /proc/{pid}/stat file and return its content.
1804
+ The return value is cached in case oneshot() ctx manager is
1805
+ in use.
1806
+ """
1807
+ with open_binary("%s/%s/status" % (self._procfs_path, self.pid)) as f:
1808
+ return f.read()
1809
+
1810
+ @wrap_exceptions
1811
+ @memoize_when_activated
1812
+ def _read_smaps_file(self):
1813
+ with open_binary("%s/%s/smaps" % (self._procfs_path, self.pid)) as f:
1814
+ return f.read().strip()
1815
+
1816
+ def oneshot_enter(self):
1817
+ self._parse_stat_file.cache_activate(self)
1818
+ self._read_status_file.cache_activate(self)
1819
+ self._read_smaps_file.cache_activate(self)
1820
+
1821
+ def oneshot_exit(self):
1822
+ self._parse_stat_file.cache_deactivate(self)
1823
+ self._read_status_file.cache_deactivate(self)
1824
+ self._read_smaps_file.cache_deactivate(self)
1825
+
1826
+ @wrap_exceptions
1827
+ def name(self):
1828
+ name = self._parse_stat_file()['name']
1829
+ if PY3:
1830
+ name = decode(name)
1831
+ # XXX - gets changed later and probably needs refactoring
1832
+ return name
1833
+
1834
+ @wrap_exceptions
1835
+ def exe(self):
1836
+ try:
1837
+ return readlink("%s/%s/exe" % (self._procfs_path, self.pid))
1838
+ except (FileNotFoundError, ProcessLookupError):
1839
+ self._raise_if_zombie()
1840
+ # no such file error; might be raised also if the
1841
+ # path actually exists for system processes with
1842
+ # low pids (about 0-20)
1843
+ if os.path.lexists("%s/%s" % (self._procfs_path, self.pid)):
1844
+ return ""
1845
+ raise
1846
+
1847
+ @wrap_exceptions
1848
+ def cmdline(self):
1849
+ with open_text("%s/%s/cmdline" % (self._procfs_path, self.pid)) as f:
1850
+ data = f.read()
1851
+ if not data:
1852
+ # may happen in case of zombie process
1853
+ self._raise_if_zombie()
1854
+ return []
1855
+ # 'man proc' states that args are separated by null bytes '\0'
1856
+ # and last char is supposed to be a null byte. Nevertheless
1857
+ # some processes may change their cmdline after being started
1858
+ # (via setproctitle() or similar), they are usually not
1859
+ # compliant with this rule and use spaces instead. Google
1860
+ # Chrome process is an example. See:
1861
+ # https://github.com/giampaolo/psutil/issues/1179
1862
+ sep = '\x00' if data.endswith('\x00') else ' '
1863
+ if data.endswith(sep):
1864
+ data = data[:-1]
1865
+ cmdline = data.split(sep)
1866
+ # Sometimes last char is a null byte '\0' but the args are
1867
+ # separated by spaces, see: https://github.com/giampaolo/psutil/
1868
+ # issues/1179#issuecomment-552984549
1869
+ if sep == '\x00' and len(cmdline) == 1 and ' ' in data:
1870
+ cmdline = data.split(' ')
1871
+ return cmdline
1872
+
1873
+ @wrap_exceptions
1874
+ def environ(self):
1875
+ with open_text("%s/%s/environ" % (self._procfs_path, self.pid)) as f:
1876
+ data = f.read()
1877
+ return parse_environ_block(data)
1878
+
1879
+ @wrap_exceptions
1880
+ def terminal(self):
1881
+ tty_nr = int(self._parse_stat_file()['ttynr'])
1882
+ tmap = _psposix.get_terminal_map()
1883
+ try:
1884
+ return tmap[tty_nr]
1885
+ except KeyError:
1886
+ return None
1887
+
1888
+ # May not be available on old kernels.
1889
+ if os.path.exists('/proc/%s/io' % os.getpid()):
1890
+
1891
+ @wrap_exceptions
1892
+ def io_counters(self):
1893
+ fname = "%s/%s/io" % (self._procfs_path, self.pid)
1894
+ fields = {}
1895
+ with open_binary(fname) as f:
1896
+ for line in f:
1897
+ # https://github.com/giampaolo/psutil/issues/1004
1898
+ line = line.strip()
1899
+ if line:
1900
+ try:
1901
+ name, value = line.split(b': ')
1902
+ except ValueError:
1903
+ # https://github.com/giampaolo/psutil/issues/1004
1904
+ continue
1905
+ else:
1906
+ fields[name] = int(value)
1907
+ if not fields:
1908
+ raise RuntimeError("%s file was empty" % fname)
1909
+ try:
1910
+ return pio(
1911
+ fields[b'syscr'], # read syscalls
1912
+ fields[b'syscw'], # write syscalls
1913
+ fields[b'read_bytes'], # read bytes
1914
+ fields[b'write_bytes'], # write bytes
1915
+ fields[b'rchar'], # read chars
1916
+ fields[b'wchar'], # write chars
1917
+ )
1918
+ except KeyError as err:
1919
+ raise ValueError(
1920
+ "%r field was not found in %s; found fields are %r"
1921
+ % (err.args[0], fname, fields)
1922
+ )
1923
+
1924
+ @wrap_exceptions
1925
+ def cpu_times(self):
1926
+ values = self._parse_stat_file()
1927
+ utime = float(values['utime']) / CLOCK_TICKS
1928
+ stime = float(values['stime']) / CLOCK_TICKS
1929
+ children_utime = float(values['children_utime']) / CLOCK_TICKS
1930
+ children_stime = float(values['children_stime']) / CLOCK_TICKS
1931
+ iowait = float(values['blkio_ticks']) / CLOCK_TICKS
1932
+ return pcputimes(utime, stime, children_utime, children_stime, iowait)
1933
+
1934
+ @wrap_exceptions
1935
+ def cpu_num(self):
1936
+ """What CPU the process is on."""
1937
+ return int(self._parse_stat_file()['cpu_num'])
1938
+
1939
+ @wrap_exceptions
1940
+ def wait(self, timeout=None):
1941
+ return _psposix.wait_pid(self.pid, timeout, self._name)
1942
+
1943
+ @wrap_exceptions
1944
+ def create_time(self):
1945
+ ctime = float(self._parse_stat_file()['create_time'])
1946
+ # According to documentation, starttime is in field 21 and the
1947
+ # unit is jiffies (clock ticks).
1948
+ # We first divide it for clock ticks and then add uptime returning
1949
+ # seconds since the epoch.
1950
+ # Also use cached value if available.
1951
+ bt = BOOT_TIME or boot_time()
1952
+ return (ctime / CLOCK_TICKS) + bt
1953
+
1954
+ @wrap_exceptions
1955
+ def memory_info(self):
1956
+ # ============================================================
1957
+ # | FIELD | DESCRIPTION | AKA | TOP |
1958
+ # ============================================================
1959
+ # | rss | resident set size | | RES |
1960
+ # | vms | total program size | size | VIRT |
1961
+ # | shared | shared pages (from shared mappings) | | SHR |
1962
+ # | text | text ('code') | trs | CODE |
1963
+ # | lib | library (unused in Linux 2.6) | lrs | |
1964
+ # | data | data + stack | drs | DATA |
1965
+ # | dirty | dirty pages (unused in Linux 2.6) | dt | |
1966
+ # ============================================================
1967
+ with open_binary("%s/%s/statm" % (self._procfs_path, self.pid)) as f:
1968
+ vms, rss, shared, text, lib, data, dirty = (
1969
+ int(x) * PAGESIZE for x in f.readline().split()[:7]
1970
+ )
1971
+ return pmem(rss, vms, shared, text, lib, data, dirty)
1972
+
1973
+ if HAS_PROC_SMAPS_ROLLUP or HAS_PROC_SMAPS:
1974
+
1975
+ def _parse_smaps_rollup(self):
1976
+ # /proc/pid/smaps_rollup was added to Linux in 2017. Faster
1977
+ # than /proc/pid/smaps. It reports higher PSS than */smaps
1978
+ # (from 1k up to 200k higher; tested against all processes).
1979
+ # IMPORTANT: /proc/pid/smaps_rollup is weird, because it
1980
+ # raises ESRCH / ENOENT for many PIDs, even if they're alive
1981
+ # (also as root). In that case we'll use /proc/pid/smaps as
1982
+ # fallback, which is slower but has a +50% success rate
1983
+ # compared to /proc/pid/smaps_rollup.
1984
+ uss = pss = swap = 0
1985
+ with open_binary(
1986
+ "{}/{}/smaps_rollup".format(self._procfs_path, self.pid)
1987
+ ) as f:
1988
+ for line in f:
1989
+ if line.startswith(b"Private_"):
1990
+ # Private_Clean, Private_Dirty, Private_Hugetlb
1991
+ uss += int(line.split()[1]) * 1024
1992
+ elif line.startswith(b"Pss:"):
1993
+ pss = int(line.split()[1]) * 1024
1994
+ elif line.startswith(b"Swap:"):
1995
+ swap = int(line.split()[1]) * 1024
1996
+ return (uss, pss, swap)
1997
+
1998
+ @wrap_exceptions
1999
+ def _parse_smaps(
2000
+ self,
2001
+ # Gets Private_Clean, Private_Dirty, Private_Hugetlb.
2002
+ _private_re=re.compile(br"\nPrivate.*:\s+(\d+)"),
2003
+ _pss_re=re.compile(br"\nPss\:\s+(\d+)"),
2004
+ _swap_re=re.compile(br"\nSwap\:\s+(\d+)"),
2005
+ ):
2006
+ # /proc/pid/smaps does not exist on kernels < 2.6.14 or if
2007
+ # CONFIG_MMU kernel configuration option is not enabled.
2008
+
2009
+ # Note: using 3 regexes is faster than reading the file
2010
+ # line by line.
2011
+ # XXX: on Python 3 the 2 regexes are 30% slower than on
2012
+ # Python 2 though. Figure out why.
2013
+ #
2014
+ # You might be tempted to calculate USS by subtracting
2015
+ # the "shared" value from the "resident" value in
2016
+ # /proc/<pid>/statm. But at least on Linux, statm's "shared"
2017
+ # value actually counts pages backed by files, which has
2018
+ # little to do with whether the pages are actually shared.
2019
+ # /proc/self/smaps on the other hand appears to give us the
2020
+ # correct information.
2021
+ smaps_data = self._read_smaps_file()
2022
+ # Note: smaps file can be empty for certain processes.
2023
+ # The code below will not crash though and will result to 0.
2024
+ uss = sum(map(int, _private_re.findall(smaps_data))) * 1024
2025
+ pss = sum(map(int, _pss_re.findall(smaps_data))) * 1024
2026
+ swap = sum(map(int, _swap_re.findall(smaps_data))) * 1024
2027
+ return (uss, pss, swap)
2028
+
2029
+ @wrap_exceptions
2030
+ def memory_full_info(self):
2031
+ if HAS_PROC_SMAPS_ROLLUP: # faster
2032
+ try:
2033
+ uss, pss, swap = self._parse_smaps_rollup()
2034
+ except (ProcessLookupError, FileNotFoundError):
2035
+ uss, pss, swap = self._parse_smaps()
2036
+ else:
2037
+ uss, pss, swap = self._parse_smaps()
2038
+ basic_mem = self.memory_info()
2039
+ return pfullmem(*basic_mem + (uss, pss, swap))
2040
+
2041
+ else:
2042
+ memory_full_info = memory_info
2043
+
2044
+ if HAS_PROC_SMAPS:
2045
+
2046
+ @wrap_exceptions
2047
+ def memory_maps(self):
2048
+ """Return process's mapped memory regions as a list of named
2049
+ tuples. Fields are explained in 'man proc'; here is an updated
2050
+ (Apr 2012) version: http://goo.gl/fmebo.
2051
+
2052
+ /proc/{PID}/smaps does not exist on kernels < 2.6.14 or if
2053
+ CONFIG_MMU kernel configuration option is not enabled.
2054
+ """
2055
+
2056
+ def get_blocks(lines, current_block):
2057
+ data = {}
2058
+ for line in lines:
2059
+ fields = line.split(None, 5)
2060
+ if not fields[0].endswith(b':'):
2061
+ # new block section
2062
+ yield (current_block.pop(), data)
2063
+ current_block.append(line)
2064
+ else:
2065
+ try:
2066
+ data[fields[0]] = int(fields[1]) * 1024
2067
+ except ValueError:
2068
+ if fields[0].startswith(b'VmFlags:'):
2069
+ # see issue #369
2070
+ continue
2071
+ else:
2072
+ raise ValueError(
2073
+ "don't know how to interpret line %r"
2074
+ % line
2075
+ )
2076
+ yield (current_block.pop(), data)
2077
+
2078
+ data = self._read_smaps_file()
2079
+ # Note: smaps file can be empty for certain processes or for
2080
+ # zombies.
2081
+ if not data:
2082
+ self._raise_if_zombie()
2083
+ return []
2084
+ lines = data.split(b'\n')
2085
+ ls = []
2086
+ first_line = lines.pop(0)
2087
+ current_block = [first_line]
2088
+ for header, data in get_blocks(lines, current_block):
2089
+ hfields = header.split(None, 5)
2090
+ try:
2091
+ addr, perms, offset, dev, inode, path = hfields
2092
+ except ValueError:
2093
+ addr, perms, offset, dev, inode, path = hfields + ['']
2094
+ if not path:
2095
+ path = '[anon]'
2096
+ else:
2097
+ if PY3:
2098
+ path = decode(path)
2099
+ path = path.strip()
2100
+ if path.endswith(' (deleted)') and not path_exists_strict(
2101
+ path
2102
+ ):
2103
+ path = path[:-10]
2104
+ ls.append((
2105
+ decode(addr),
2106
+ decode(perms),
2107
+ path,
2108
+ data.get(b'Rss:', 0),
2109
+ data.get(b'Size:', 0),
2110
+ data.get(b'Pss:', 0),
2111
+ data.get(b'Shared_Clean:', 0),
2112
+ data.get(b'Shared_Dirty:', 0),
2113
+ data.get(b'Private_Clean:', 0),
2114
+ data.get(b'Private_Dirty:', 0),
2115
+ data.get(b'Referenced:', 0),
2116
+ data.get(b'Anonymous:', 0),
2117
+ data.get(b'Swap:', 0),
2118
+ ))
2119
+ return ls
2120
+
2121
+ @wrap_exceptions
2122
+ def cwd(self):
2123
+ return readlink("%s/%s/cwd" % (self._procfs_path, self.pid))
2124
+
2125
+ @wrap_exceptions
2126
+ def num_ctx_switches(
2127
+ self, _ctxsw_re=re.compile(br'ctxt_switches:\t(\d+)')
2128
+ ):
2129
+ data = self._read_status_file()
2130
+ ctxsw = _ctxsw_re.findall(data)
2131
+ if not ctxsw:
2132
+ raise NotImplementedError(
2133
+ "'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'"
2134
+ "lines were not found in %s/%s/status; the kernel is "
2135
+ "probably older than 2.6.23" % (self._procfs_path, self.pid)
2136
+ )
2137
+ else:
2138
+ return _common.pctxsw(int(ctxsw[0]), int(ctxsw[1]))
2139
+
2140
+ @wrap_exceptions
2141
+ def num_threads(self, _num_threads_re=re.compile(br'Threads:\t(\d+)')):
2142
+ # Note: on Python 3 using a re is faster than iterating over file
2143
+ # line by line. On Python 2 is the exact opposite, and iterating
2144
+ # over a file on Python 3 is slower than on Python 2.
2145
+ data = self._read_status_file()
2146
+ return int(_num_threads_re.findall(data)[0])
2147
+
2148
+ @wrap_exceptions
2149
+ def threads(self):
2150
+ thread_ids = os.listdir("%s/%s/task" % (self._procfs_path, self.pid))
2151
+ thread_ids.sort()
2152
+ retlist = []
2153
+ hit_enoent = False
2154
+ for thread_id in thread_ids:
2155
+ fname = "%s/%s/task/%s/stat" % (
2156
+ self._procfs_path,
2157
+ self.pid,
2158
+ thread_id,
2159
+ )
2160
+ try:
2161
+ with open_binary(fname) as f:
2162
+ st = f.read().strip()
2163
+ except (FileNotFoundError, ProcessLookupError):
2164
+ # no such file or directory or no such process;
2165
+ # it means thread disappeared on us
2166
+ hit_enoent = True
2167
+ continue
2168
+ # ignore the first two values ("pid (exe)")
2169
+ st = st[st.find(b')') + 2 :]
2170
+ values = st.split(b' ')
2171
+ utime = float(values[11]) / CLOCK_TICKS
2172
+ stime = float(values[12]) / CLOCK_TICKS
2173
+ ntuple = _common.pthread(int(thread_id), utime, stime)
2174
+ retlist.append(ntuple)
2175
+ if hit_enoent:
2176
+ self._raise_if_not_alive()
2177
+ return retlist
2178
+
2179
+ @wrap_exceptions
2180
+ def nice_get(self):
2181
+ # with open_text('%s/%s/stat' % (self._procfs_path, self.pid)) as f:
2182
+ # data = f.read()
2183
+ # return int(data.split()[18])
2184
+
2185
+ # Use C implementation
2186
+ return cext_posix.getpriority(self.pid)
2187
+
2188
+ @wrap_exceptions
2189
+ def nice_set(self, value):
2190
+ return cext_posix.setpriority(self.pid, value)
2191
+
2192
+ # starting from CentOS 6.
2193
+ if HAS_CPU_AFFINITY:
2194
+
2195
+ @wrap_exceptions
2196
+ def cpu_affinity_get(self):
2197
+ return cext.proc_cpu_affinity_get(self.pid)
2198
+
2199
+ def _get_eligible_cpus(
2200
+ self, _re=re.compile(br"Cpus_allowed_list:\t(\d+)-(\d+)")
2201
+ ):
2202
+ # See: https://github.com/giampaolo/psutil/issues/956
2203
+ data = self._read_status_file()
2204
+ match = _re.findall(data)
2205
+ if match:
2206
+ return list(range(int(match[0][0]), int(match[0][1]) + 1))
2207
+ else:
2208
+ return list(range(len(per_cpu_times())))
2209
+
2210
+ @wrap_exceptions
2211
+ def cpu_affinity_set(self, cpus):
2212
+ try:
2213
+ cext.proc_cpu_affinity_set(self.pid, cpus)
2214
+ except (OSError, ValueError) as err:
2215
+ if isinstance(err, ValueError) or err.errno == errno.EINVAL:
2216
+ eligible_cpus = self._get_eligible_cpus()
2217
+ all_cpus = tuple(range(len(per_cpu_times())))
2218
+ for cpu in cpus:
2219
+ if cpu not in all_cpus:
2220
+ raise ValueError(
2221
+ "invalid CPU number %r; choose between %s"
2222
+ % (cpu, eligible_cpus)
2223
+ )
2224
+ if cpu not in eligible_cpus:
2225
+ raise ValueError(
2226
+ "CPU number %r is not eligible; choose "
2227
+ "between %s" % (cpu, eligible_cpus)
2228
+ )
2229
+ raise
2230
+
2231
+ # only starting from kernel 2.6.13
2232
+ if HAS_PROC_IO_PRIORITY:
2233
+
2234
+ @wrap_exceptions
2235
+ def ionice_get(self):
2236
+ ioclass, value = cext.proc_ioprio_get(self.pid)
2237
+ if enum is not None:
2238
+ ioclass = IOPriority(ioclass)
2239
+ return _common.pionice(ioclass, value)
2240
+
2241
+ @wrap_exceptions
2242
+ def ionice_set(self, ioclass, value):
2243
+ if value is None:
2244
+ value = 0
2245
+ if value and ioclass in (IOPRIO_CLASS_IDLE, IOPRIO_CLASS_NONE):
2246
+ raise ValueError("%r ioclass accepts no value" % ioclass)
2247
+ if value < 0 or value > 7:
2248
+ msg = "value not in 0-7 range"
2249
+ raise ValueError(msg)
2250
+ return cext.proc_ioprio_set(self.pid, ioclass, value)
2251
+
2252
+ if prlimit is not None:
2253
+
2254
+ @wrap_exceptions
2255
+ def rlimit(self, resource_, limits=None):
2256
+ # If pid is 0 prlimit() applies to the calling process and
2257
+ # we don't want that. We should never get here though as
2258
+ # PID 0 is not supported on Linux.
2259
+ if self.pid == 0:
2260
+ msg = "can't use prlimit() against PID 0 process"
2261
+ raise ValueError(msg)
2262
+ try:
2263
+ if limits is None:
2264
+ # get
2265
+ return prlimit(self.pid, resource_)
2266
+ else:
2267
+ # set
2268
+ if len(limits) != 2:
2269
+ msg = (
2270
+ "second argument must be a (soft, hard) "
2271
+ + "tuple, got %s" % repr(limits)
2272
+ )
2273
+ raise ValueError(msg)
2274
+ prlimit(self.pid, resource_, limits)
2275
+ except OSError as err:
2276
+ if err.errno == errno.ENOSYS:
2277
+ # I saw this happening on Travis:
2278
+ # https://travis-ci.org/giampaolo/psutil/jobs/51368273
2279
+ self._raise_if_zombie()
2280
+ raise
2281
+
2282
+ @wrap_exceptions
2283
+ def status(self):
2284
+ letter = self._parse_stat_file()['status']
2285
+ if PY3:
2286
+ letter = letter.decode()
2287
+ # XXX is '?' legit? (we're not supposed to return it anyway)
2288
+ return PROC_STATUSES.get(letter, '?')
2289
+
2290
+ @wrap_exceptions
2291
+ def open_files(self):
2292
+ retlist = []
2293
+ files = os.listdir("%s/%s/fd" % (self._procfs_path, self.pid))
2294
+ hit_enoent = False
2295
+ for fd in files:
2296
+ file = "%s/%s/fd/%s" % (self._procfs_path, self.pid, fd)
2297
+ try:
2298
+ path = readlink(file)
2299
+ except (FileNotFoundError, ProcessLookupError):
2300
+ # ENOENT == file which is gone in the meantime
2301
+ hit_enoent = True
2302
+ continue
2303
+ except OSError as err:
2304
+ if err.errno == errno.EINVAL:
2305
+ # not a link
2306
+ continue
2307
+ if err.errno == errno.ENAMETOOLONG:
2308
+ # file name too long
2309
+ debug(err)
2310
+ continue
2311
+ raise
2312
+ else:
2313
+ # If path is not an absolute there's no way to tell
2314
+ # whether it's a regular file or not, so we skip it.
2315
+ # A regular file is always supposed to be have an
2316
+ # absolute path though.
2317
+ if path.startswith('/') and isfile_strict(path):
2318
+ # Get file position and flags.
2319
+ file = "%s/%s/fdinfo/%s" % (
2320
+ self._procfs_path,
2321
+ self.pid,
2322
+ fd,
2323
+ )
2324
+ try:
2325
+ with open_binary(file) as f:
2326
+ pos = int(f.readline().split()[1])
2327
+ flags = int(f.readline().split()[1], 8)
2328
+ except (FileNotFoundError, ProcessLookupError):
2329
+ # fd gone in the meantime; process may
2330
+ # still be alive
2331
+ hit_enoent = True
2332
+ else:
2333
+ mode = file_flags_to_mode(flags)
2334
+ ntuple = popenfile(
2335
+ path, int(fd), int(pos), mode, flags
2336
+ )
2337
+ retlist.append(ntuple)
2338
+ if hit_enoent:
2339
+ self._raise_if_not_alive()
2340
+ return retlist
2341
+
2342
+ @wrap_exceptions
2343
+ def connections(self, kind='inet'):
2344
+ ret = _connections.retrieve(kind, self.pid)
2345
+ self._raise_if_not_alive()
2346
+ return ret
2347
+
2348
+ @wrap_exceptions
2349
+ def num_fds(self):
2350
+ return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
2351
+
2352
+ @wrap_exceptions
2353
+ def ppid(self):
2354
+ return int(self._parse_stat_file()['ppid'])
2355
+
2356
+ @wrap_exceptions
2357
+ def uids(self, _uids_re=re.compile(br'Uid:\t(\d+)\t(\d+)\t(\d+)')):
2358
+ data = self._read_status_file()
2359
+ real, effective, saved = _uids_re.findall(data)[0]
2360
+ return _common.puids(int(real), int(effective), int(saved))
2361
+
2362
+ @wrap_exceptions
2363
+ def gids(self, _gids_re=re.compile(br'Gid:\t(\d+)\t(\d+)\t(\d+)')):
2364
+ data = self._read_status_file()
2365
+ real, effective, saved = _gids_re.findall(data)[0]
2366
+ return _common.pgids(int(real), int(effective), int(saved))
llmeval-env/lib/python3.10/site-packages/psutil/_psosx.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """macOS platform implementation."""
6
+
7
+ import errno
8
+ import functools
9
+ import os
10
+ from collections import namedtuple
11
+
12
+ from . import _common
13
+ from . import _psposix
14
+ from . import _psutil_osx as cext
15
+ from . import _psutil_posix as cext_posix
16
+ from ._common import AccessDenied
17
+ from ._common import NoSuchProcess
18
+ from ._common import ZombieProcess
19
+ from ._common import conn_tmap
20
+ from ._common import conn_to_ntuple
21
+ from ._common import isfile_strict
22
+ from ._common import memoize_when_activated
23
+ from ._common import parse_environ_block
24
+ from ._common import usage_percent
25
+ from ._compat import PermissionError
26
+ from ._compat import ProcessLookupError
27
+
28
+
29
+ __extra__all__ = []
30
+
31
+
32
+ # =====================================================================
33
+ # --- globals
34
+ # =====================================================================
35
+
36
+
37
+ PAGESIZE = cext_posix.getpagesize()
38
+ AF_LINK = cext_posix.AF_LINK
39
+
40
+ TCP_STATUSES = {
41
+ cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
42
+ cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
43
+ cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
44
+ cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
45
+ cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
46
+ cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
47
+ cext.TCPS_CLOSED: _common.CONN_CLOSE,
48
+ cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
49
+ cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
50
+ cext.TCPS_LISTEN: _common.CONN_LISTEN,
51
+ cext.TCPS_CLOSING: _common.CONN_CLOSING,
52
+ cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
53
+ }
54
+
55
+ PROC_STATUSES = {
56
+ cext.SIDL: _common.STATUS_IDLE,
57
+ cext.SRUN: _common.STATUS_RUNNING,
58
+ cext.SSLEEP: _common.STATUS_SLEEPING,
59
+ cext.SSTOP: _common.STATUS_STOPPED,
60
+ cext.SZOMB: _common.STATUS_ZOMBIE,
61
+ }
62
+
63
+ kinfo_proc_map = dict(
64
+ ppid=0,
65
+ ruid=1,
66
+ euid=2,
67
+ suid=3,
68
+ rgid=4,
69
+ egid=5,
70
+ sgid=6,
71
+ ttynr=7,
72
+ ctime=8,
73
+ status=9,
74
+ name=10,
75
+ )
76
+
77
+ pidtaskinfo_map = dict(
78
+ cpuutime=0,
79
+ cpustime=1,
80
+ rss=2,
81
+ vms=3,
82
+ pfaults=4,
83
+ pageins=5,
84
+ numthreads=6,
85
+ volctxsw=7,
86
+ )
87
+
88
+
89
+ # =====================================================================
90
+ # --- named tuples
91
+ # =====================================================================
92
+
93
+
94
+ # fmt: off
95
+ # psutil.cpu_times()
96
+ scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle'])
97
+ # psutil.virtual_memory()
98
+ svmem = namedtuple(
99
+ 'svmem', ['total', 'available', 'percent', 'used', 'free',
100
+ 'active', 'inactive', 'wired'])
101
+ # psutil.Process.memory_info()
102
+ pmem = namedtuple('pmem', ['rss', 'vms', 'pfaults', 'pageins'])
103
+ # psutil.Process.memory_full_info()
104
+ pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
105
+ # fmt: on
106
+
107
+
108
+ # =====================================================================
109
+ # --- memory
110
+ # =====================================================================
111
+
112
+
113
+ def virtual_memory():
114
+ """System virtual memory as a namedtuple."""
115
+ total, active, inactive, wired, free, speculative = cext.virtual_mem()
116
+ # This is how Zabbix calculate avail and used mem:
117
+ # https://github.com/zabbix/zabbix/blob/trunk/src/libs/zbxsysinfo/
118
+ # osx/memory.c
119
+ # Also see: https://github.com/giampaolo/psutil/issues/1277
120
+ avail = inactive + free
121
+ used = active + wired
122
+ # This is NOT how Zabbix calculates free mem but it matches "free"
123
+ # cmdline utility.
124
+ free -= speculative
125
+ percent = usage_percent((total - avail), total, round_=1)
126
+ return svmem(total, avail, percent, used, free, active, inactive, wired)
127
+
128
+
129
+ def swap_memory():
130
+ """Swap system memory as a (total, used, free, sin, sout) tuple."""
131
+ total, used, free, sin, sout = cext.swap_mem()
132
+ percent = usage_percent(used, total, round_=1)
133
+ return _common.sswap(total, used, free, percent, sin, sout)
134
+
135
+
136
+ # =====================================================================
137
+ # --- CPU
138
+ # =====================================================================
139
+
140
+
141
+ def cpu_times():
142
+ """Return system CPU times as a namedtuple."""
143
+ user, nice, system, idle = cext.cpu_times()
144
+ return scputimes(user, nice, system, idle)
145
+
146
+
147
+ def per_cpu_times():
148
+ """Return system CPU times as a named tuple."""
149
+ ret = []
150
+ for cpu_t in cext.per_cpu_times():
151
+ user, nice, system, idle = cpu_t
152
+ item = scputimes(user, nice, system, idle)
153
+ ret.append(item)
154
+ return ret
155
+
156
+
157
+ def cpu_count_logical():
158
+ """Return the number of logical CPUs in the system."""
159
+ return cext.cpu_count_logical()
160
+
161
+
162
+ def cpu_count_cores():
163
+ """Return the number of CPU cores in the system."""
164
+ return cext.cpu_count_cores()
165
+
166
+
167
+ def cpu_stats():
168
+ ctx_switches, interrupts, soft_interrupts, syscalls, traps = (
169
+ cext.cpu_stats()
170
+ )
171
+ return _common.scpustats(
172
+ ctx_switches, interrupts, soft_interrupts, syscalls
173
+ )
174
+
175
+
176
+ def cpu_freq():
177
+ """Return CPU frequency.
178
+ On macOS per-cpu frequency is not supported.
179
+ Also, the returned frequency never changes, see:
180
+ https://arstechnica.com/civis/viewtopic.php?f=19&t=465002.
181
+ """
182
+ curr, min_, max_ = cext.cpu_freq()
183
+ return [_common.scpufreq(curr, min_, max_)]
184
+
185
+
186
+ # =====================================================================
187
+ # --- disks
188
+ # =====================================================================
189
+
190
+
191
+ disk_usage = _psposix.disk_usage
192
+ disk_io_counters = cext.disk_io_counters
193
+
194
+
195
+ def disk_partitions(all=False):
196
+ """Return mounted disk partitions as a list of namedtuples."""
197
+ retlist = []
198
+ partitions = cext.disk_partitions()
199
+ for partition in partitions:
200
+ device, mountpoint, fstype, opts = partition
201
+ if device == 'none':
202
+ device = ''
203
+ if not all:
204
+ if not os.path.isabs(device) or not os.path.exists(device):
205
+ continue
206
+ maxfile = maxpath = None # set later
207
+ ntuple = _common.sdiskpart(
208
+ device, mountpoint, fstype, opts, maxfile, maxpath
209
+ )
210
+ retlist.append(ntuple)
211
+ return retlist
212
+
213
+
214
+ # =====================================================================
215
+ # --- sensors
216
+ # =====================================================================
217
+
218
+
219
+ def sensors_battery():
220
+ """Return battery information."""
221
+ try:
222
+ percent, minsleft, power_plugged = cext.sensors_battery()
223
+ except NotImplementedError:
224
+ # no power source - return None according to interface
225
+ return None
226
+ power_plugged = power_plugged == 1
227
+ if power_plugged:
228
+ secsleft = _common.POWER_TIME_UNLIMITED
229
+ elif minsleft == -1:
230
+ secsleft = _common.POWER_TIME_UNKNOWN
231
+ else:
232
+ secsleft = minsleft * 60
233
+ return _common.sbattery(percent, secsleft, power_plugged)
234
+
235
+
236
+ # =====================================================================
237
+ # --- network
238
+ # =====================================================================
239
+
240
+
241
+ net_io_counters = cext.net_io_counters
242
+ net_if_addrs = cext_posix.net_if_addrs
243
+
244
+
245
+ def net_connections(kind='inet'):
246
+ """System-wide network connections."""
247
+ # Note: on macOS this will fail with AccessDenied unless
248
+ # the process is owned by root.
249
+ ret = []
250
+ for pid in pids():
251
+ try:
252
+ cons = Process(pid).connections(kind)
253
+ except NoSuchProcess:
254
+ continue
255
+ else:
256
+ if cons:
257
+ for c in cons:
258
+ c = list(c) + [pid]
259
+ ret.append(_common.sconn(*c))
260
+ return ret
261
+
262
+
263
+ def net_if_stats():
264
+ """Get NIC stats (isup, duplex, speed, mtu)."""
265
+ names = net_io_counters().keys()
266
+ ret = {}
267
+ for name in names:
268
+ try:
269
+ mtu = cext_posix.net_if_mtu(name)
270
+ flags = cext_posix.net_if_flags(name)
271
+ duplex, speed = cext_posix.net_if_duplex_speed(name)
272
+ except OSError as err:
273
+ # https://github.com/giampaolo/psutil/issues/1279
274
+ if err.errno != errno.ENODEV:
275
+ raise
276
+ else:
277
+ if hasattr(_common, 'NicDuplex'):
278
+ duplex = _common.NicDuplex(duplex)
279
+ output_flags = ','.join(flags)
280
+ isup = 'running' in flags
281
+ ret[name] = _common.snicstats(
282
+ isup, duplex, speed, mtu, output_flags
283
+ )
284
+ return ret
285
+
286
+
287
+ # =====================================================================
288
+ # --- other system functions
289
+ # =====================================================================
290
+
291
+
292
+ def boot_time():
293
+ """The system boot time expressed in seconds since the epoch."""
294
+ return cext.boot_time()
295
+
296
+
297
+ def users():
298
+ """Return currently connected users as a list of namedtuples."""
299
+ retlist = []
300
+ rawlist = cext.users()
301
+ for item in rawlist:
302
+ user, tty, hostname, tstamp, pid = item
303
+ if tty == '~':
304
+ continue # reboot or shutdown
305
+ if not tstamp:
306
+ continue
307
+ nt = _common.suser(user, tty or None, hostname or None, tstamp, pid)
308
+ retlist.append(nt)
309
+ return retlist
310
+
311
+
312
+ # =====================================================================
313
+ # --- processes
314
+ # =====================================================================
315
+
316
+
317
+ def pids():
318
+ ls = cext.pids()
319
+ if 0 not in ls:
320
+ # On certain macOS versions pids() C doesn't return PID 0 but
321
+ # "ps" does and the process is querable via sysctl():
322
+ # https://travis-ci.org/giampaolo/psutil/jobs/309619941
323
+ try:
324
+ Process(0).create_time()
325
+ ls.insert(0, 0)
326
+ except NoSuchProcess:
327
+ pass
328
+ except AccessDenied:
329
+ ls.insert(0, 0)
330
+ return ls
331
+
332
+
333
+ pid_exists = _psposix.pid_exists
334
+
335
+
336
+ def is_zombie(pid):
337
+ try:
338
+ st = cext.proc_kinfo_oneshot(pid)[kinfo_proc_map['status']]
339
+ return st == cext.SZOMB
340
+ except OSError:
341
+ return False
342
+
343
+
344
+ def wrap_exceptions(fun):
345
+ """Decorator which translates bare OSError exceptions into
346
+ NoSuchProcess and AccessDenied.
347
+ """
348
+
349
+ @functools.wraps(fun)
350
+ def wrapper(self, *args, **kwargs):
351
+ try:
352
+ return fun(self, *args, **kwargs)
353
+ except ProcessLookupError:
354
+ if is_zombie(self.pid):
355
+ raise ZombieProcess(self.pid, self._name, self._ppid)
356
+ else:
357
+ raise NoSuchProcess(self.pid, self._name)
358
+ except PermissionError:
359
+ raise AccessDenied(self.pid, self._name)
360
+
361
+ return wrapper
362
+
363
+
364
+ class Process:
365
+ """Wrapper class around underlying C implementation."""
366
+
367
+ __slots__ = ["pid", "_name", "_ppid", "_cache"]
368
+
369
+ def __init__(self, pid):
370
+ self.pid = pid
371
+ self._name = None
372
+ self._ppid = None
373
+
374
+ @wrap_exceptions
375
+ @memoize_when_activated
376
+ def _get_kinfo_proc(self):
377
+ # Note: should work with all PIDs without permission issues.
378
+ ret = cext.proc_kinfo_oneshot(self.pid)
379
+ assert len(ret) == len(kinfo_proc_map)
380
+ return ret
381
+
382
+ @wrap_exceptions
383
+ @memoize_when_activated
384
+ def _get_pidtaskinfo(self):
385
+ # Note: should work for PIDs owned by user only.
386
+ ret = cext.proc_pidtaskinfo_oneshot(self.pid)
387
+ assert len(ret) == len(pidtaskinfo_map)
388
+ return ret
389
+
390
+ def oneshot_enter(self):
391
+ self._get_kinfo_proc.cache_activate(self)
392
+ self._get_pidtaskinfo.cache_activate(self)
393
+
394
+ def oneshot_exit(self):
395
+ self._get_kinfo_proc.cache_deactivate(self)
396
+ self._get_pidtaskinfo.cache_deactivate(self)
397
+
398
+ @wrap_exceptions
399
+ def name(self):
400
+ name = self._get_kinfo_proc()[kinfo_proc_map['name']]
401
+ return name if name is not None else cext.proc_name(self.pid)
402
+
403
+ @wrap_exceptions
404
+ def exe(self):
405
+ return cext.proc_exe(self.pid)
406
+
407
+ @wrap_exceptions
408
+ def cmdline(self):
409
+ return cext.proc_cmdline(self.pid)
410
+
411
+ @wrap_exceptions
412
+ def environ(self):
413
+ return parse_environ_block(cext.proc_environ(self.pid))
414
+
415
+ @wrap_exceptions
416
+ def ppid(self):
417
+ self._ppid = self._get_kinfo_proc()[kinfo_proc_map['ppid']]
418
+ return self._ppid
419
+
420
+ @wrap_exceptions
421
+ def cwd(self):
422
+ return cext.proc_cwd(self.pid)
423
+
424
+ @wrap_exceptions
425
+ def uids(self):
426
+ rawtuple = self._get_kinfo_proc()
427
+ return _common.puids(
428
+ rawtuple[kinfo_proc_map['ruid']],
429
+ rawtuple[kinfo_proc_map['euid']],
430
+ rawtuple[kinfo_proc_map['suid']],
431
+ )
432
+
433
+ @wrap_exceptions
434
+ def gids(self):
435
+ rawtuple = self._get_kinfo_proc()
436
+ return _common.puids(
437
+ rawtuple[kinfo_proc_map['rgid']],
438
+ rawtuple[kinfo_proc_map['egid']],
439
+ rawtuple[kinfo_proc_map['sgid']],
440
+ )
441
+
442
+ @wrap_exceptions
443
+ def terminal(self):
444
+ tty_nr = self._get_kinfo_proc()[kinfo_proc_map['ttynr']]
445
+ tmap = _psposix.get_terminal_map()
446
+ try:
447
+ return tmap[tty_nr]
448
+ except KeyError:
449
+ return None
450
+
451
+ @wrap_exceptions
452
+ def memory_info(self):
453
+ rawtuple = self._get_pidtaskinfo()
454
+ return pmem(
455
+ rawtuple[pidtaskinfo_map['rss']],
456
+ rawtuple[pidtaskinfo_map['vms']],
457
+ rawtuple[pidtaskinfo_map['pfaults']],
458
+ rawtuple[pidtaskinfo_map['pageins']],
459
+ )
460
+
461
+ @wrap_exceptions
462
+ def memory_full_info(self):
463
+ basic_mem = self.memory_info()
464
+ uss = cext.proc_memory_uss(self.pid)
465
+ return pfullmem(*basic_mem + (uss,))
466
+
467
+ @wrap_exceptions
468
+ def cpu_times(self):
469
+ rawtuple = self._get_pidtaskinfo()
470
+ return _common.pcputimes(
471
+ rawtuple[pidtaskinfo_map['cpuutime']],
472
+ rawtuple[pidtaskinfo_map['cpustime']],
473
+ # children user / system times are not retrievable (set to 0)
474
+ 0.0,
475
+ 0.0,
476
+ )
477
+
478
+ @wrap_exceptions
479
+ def create_time(self):
480
+ return self._get_kinfo_proc()[kinfo_proc_map['ctime']]
481
+
482
+ @wrap_exceptions
483
+ def num_ctx_switches(self):
484
+ # Unvoluntary value seems not to be available;
485
+ # getrusage() numbers seems to confirm this theory.
486
+ # We set it to 0.
487
+ vol = self._get_pidtaskinfo()[pidtaskinfo_map['volctxsw']]
488
+ return _common.pctxsw(vol, 0)
489
+
490
+ @wrap_exceptions
491
+ def num_threads(self):
492
+ return self._get_pidtaskinfo()[pidtaskinfo_map['numthreads']]
493
+
494
+ @wrap_exceptions
495
+ def open_files(self):
496
+ if self.pid == 0:
497
+ return []
498
+ files = []
499
+ rawlist = cext.proc_open_files(self.pid)
500
+ for path, fd in rawlist:
501
+ if isfile_strict(path):
502
+ ntuple = _common.popenfile(path, fd)
503
+ files.append(ntuple)
504
+ return files
505
+
506
+ @wrap_exceptions
507
+ def connections(self, kind='inet'):
508
+ if kind not in conn_tmap:
509
+ raise ValueError(
510
+ "invalid %r kind argument; choose between %s"
511
+ % (kind, ', '.join([repr(x) for x in conn_tmap]))
512
+ )
513
+ families, types = conn_tmap[kind]
514
+ rawlist = cext.proc_connections(self.pid, families, types)
515
+ ret = []
516
+ for item in rawlist:
517
+ fd, fam, type, laddr, raddr, status = item
518
+ nt = conn_to_ntuple(
519
+ fd, fam, type, laddr, raddr, status, TCP_STATUSES
520
+ )
521
+ ret.append(nt)
522
+ return ret
523
+
524
+ @wrap_exceptions
525
+ def num_fds(self):
526
+ if self.pid == 0:
527
+ return 0
528
+ return cext.proc_num_fds(self.pid)
529
+
530
+ @wrap_exceptions
531
+ def wait(self, timeout=None):
532
+ return _psposix.wait_pid(self.pid, timeout, self._name)
533
+
534
+ @wrap_exceptions
535
+ def nice_get(self):
536
+ return cext_posix.getpriority(self.pid)
537
+
538
+ @wrap_exceptions
539
+ def nice_set(self, value):
540
+ return cext_posix.setpriority(self.pid, value)
541
+
542
+ @wrap_exceptions
543
+ def status(self):
544
+ code = self._get_kinfo_proc()[kinfo_proc_map['status']]
545
+ # XXX is '?' legit? (we're not supposed to return it anyway)
546
+ return PROC_STATUSES.get(code, '?')
547
+
548
+ @wrap_exceptions
549
+ def threads(self):
550
+ rawlist = cext.proc_threads(self.pid)
551
+ retlist = []
552
+ for thread_id, utime, stime in rawlist:
553
+ ntuple = _common.pthread(thread_id, utime, stime)
554
+ retlist.append(ntuple)
555
+ return retlist
llmeval-env/lib/python3.10/site-packages/psutil/_psposix.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """Routines common to all posix systems."""
6
+
7
+ import glob
8
+ import os
9
+ import signal
10
+ import sys
11
+ import time
12
+
13
+ from ._common import MACOS
14
+ from ._common import TimeoutExpired
15
+ from ._common import memoize
16
+ from ._common import sdiskusage
17
+ from ._common import usage_percent
18
+ from ._compat import PY3
19
+ from ._compat import ChildProcessError
20
+ from ._compat import FileNotFoundError
21
+ from ._compat import InterruptedError
22
+ from ._compat import PermissionError
23
+ from ._compat import ProcessLookupError
24
+ from ._compat import unicode
25
+
26
+
27
+ if MACOS:
28
+ from . import _psutil_osx
29
+
30
+
31
+ if PY3:
32
+ import enum
33
+ else:
34
+ enum = None
35
+
36
+
37
+ __all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map']
38
+
39
+
40
+ def pid_exists(pid):
41
+ """Check whether pid exists in the current process table."""
42
+ if pid == 0:
43
+ # According to "man 2 kill" PID 0 has a special meaning:
44
+ # it refers to <<every process in the process group of the
45
+ # calling process>> so we don't want to go any further.
46
+ # If we get here it means this UNIX platform *does* have
47
+ # a process with id 0.
48
+ return True
49
+ try:
50
+ os.kill(pid, 0)
51
+ except ProcessLookupError:
52
+ return False
53
+ except PermissionError:
54
+ # EPERM clearly means there's a process to deny access to
55
+ return True
56
+ # According to "man 2 kill" possible error values are
57
+ # (EINVAL, EPERM, ESRCH)
58
+ else:
59
+ return True
60
+
61
+
62
+ # Python 3.5 signals enum (contributed by me ^^):
63
+ # https://bugs.python.org/issue21076
64
+ if enum is not None and hasattr(signal, "Signals"):
65
+ Negsignal = enum.IntEnum(
66
+ 'Negsignal', dict([(x.name, -x.value) for x in signal.Signals])
67
+ )
68
+
69
+ def negsig_to_enum(num):
70
+ """Convert a negative signal value to an enum."""
71
+ try:
72
+ return Negsignal(num)
73
+ except ValueError:
74
+ return num
75
+
76
+ else: # pragma: no cover
77
+
78
+ def negsig_to_enum(num):
79
+ return num
80
+
81
+
82
+ def wait_pid(
83
+ pid,
84
+ timeout=None,
85
+ proc_name=None,
86
+ _waitpid=os.waitpid,
87
+ _timer=getattr(time, 'monotonic', time.time), # noqa: B008
88
+ _min=min,
89
+ _sleep=time.sleep,
90
+ _pid_exists=pid_exists,
91
+ ):
92
+ """Wait for a process PID to terminate.
93
+
94
+ If the process terminated normally by calling exit(3) or _exit(2),
95
+ or by returning from main(), the return value is the positive integer
96
+ passed to *exit().
97
+
98
+ If it was terminated by a signal it returns the negated value of the
99
+ signal which caused the termination (e.g. -SIGTERM).
100
+
101
+ If PID is not a children of os.getpid() (current process) just
102
+ wait until the process disappears and return None.
103
+
104
+ If PID does not exist at all return None immediately.
105
+
106
+ If *timeout* != None and process is still alive raise TimeoutExpired.
107
+ timeout=0 is also possible (either return immediately or raise).
108
+ """
109
+ if pid <= 0:
110
+ # see "man waitpid"
111
+ msg = "can't wait for PID 0"
112
+ raise ValueError(msg)
113
+ interval = 0.0001
114
+ flags = 0
115
+ if timeout is not None:
116
+ flags |= os.WNOHANG
117
+ stop_at = _timer() + timeout
118
+
119
+ def sleep(interval):
120
+ # Sleep for some time and return a new increased interval.
121
+ if timeout is not None:
122
+ if _timer() >= stop_at:
123
+ raise TimeoutExpired(timeout, pid=pid, name=proc_name)
124
+ _sleep(interval)
125
+ return _min(interval * 2, 0.04)
126
+
127
+ # See: https://linux.die.net/man/2/waitpid
128
+ while True:
129
+ try:
130
+ retpid, status = os.waitpid(pid, flags)
131
+ except InterruptedError:
132
+ interval = sleep(interval)
133
+ except ChildProcessError:
134
+ # This has two meanings:
135
+ # - PID is not a child of os.getpid() in which case
136
+ # we keep polling until it's gone
137
+ # - PID never existed in the first place
138
+ # In both cases we'll eventually return None as we
139
+ # can't determine its exit status code.
140
+ while _pid_exists(pid):
141
+ interval = sleep(interval)
142
+ return
143
+ else:
144
+ if retpid == 0:
145
+ # WNOHANG flag was used and PID is still running.
146
+ interval = sleep(interval)
147
+ continue
148
+
149
+ if os.WIFEXITED(status):
150
+ # Process terminated normally by calling exit(3) or _exit(2),
151
+ # or by returning from main(). The return value is the
152
+ # positive integer passed to *exit().
153
+ return os.WEXITSTATUS(status)
154
+ elif os.WIFSIGNALED(status):
155
+ # Process exited due to a signal. Return the negative value
156
+ # of that signal.
157
+ return negsig_to_enum(-os.WTERMSIG(status))
158
+ # elif os.WIFSTOPPED(status):
159
+ # # Process was stopped via SIGSTOP or is being traced, and
160
+ # # waitpid() was called with WUNTRACED flag. PID is still
161
+ # # alive. From now on waitpid() will keep returning (0, 0)
162
+ # # until the process state doesn't change.
163
+ # # It may make sense to catch/enable this since stopped PIDs
164
+ # # ignore SIGTERM.
165
+ # interval = sleep(interval)
166
+ # continue
167
+ # elif os.WIFCONTINUED(status):
168
+ # # Process was resumed via SIGCONT and waitpid() was called
169
+ # # with WCONTINUED flag.
170
+ # interval = sleep(interval)
171
+ # continue
172
+ else:
173
+ # Should never happen.
174
+ raise ValueError("unknown process exit status %r" % status)
175
+
176
+
177
+ def disk_usage(path):
178
+ """Return disk usage associated with path.
179
+ Note: UNIX usually reserves 5% disk space which is not accessible
180
+ by user. In this function "total" and "used" values reflect the
181
+ total and used disk space whereas "free" and "percent" represent
182
+ the "free" and "used percent" user disk space.
183
+ """
184
+ if PY3:
185
+ st = os.statvfs(path)
186
+ else: # pragma: no cover
187
+ # os.statvfs() does not support unicode on Python 2:
188
+ # - https://github.com/giampaolo/psutil/issues/416
189
+ # - http://bugs.python.org/issue18695
190
+ try:
191
+ st = os.statvfs(path)
192
+ except UnicodeEncodeError:
193
+ if isinstance(path, unicode):
194
+ try:
195
+ path = path.encode(sys.getfilesystemencoding())
196
+ except UnicodeEncodeError:
197
+ pass
198
+ st = os.statvfs(path)
199
+ else:
200
+ raise
201
+
202
+ # Total space which is only available to root (unless changed
203
+ # at system level).
204
+ total = st.f_blocks * st.f_frsize
205
+ # Remaining free space usable by root.
206
+ avail_to_root = st.f_bfree * st.f_frsize
207
+ # Remaining free space usable by user.
208
+ avail_to_user = st.f_bavail * st.f_frsize
209
+ # Total space being used in general.
210
+ used = total - avail_to_root
211
+ if MACOS:
212
+ # see: https://github.com/giampaolo/psutil/pull/2152
213
+ used = _psutil_osx.disk_usage_used(path, used)
214
+ # Total space which is available to user (same as 'total' but
215
+ # for the user).
216
+ total_user = used + avail_to_user
217
+ # User usage percent compared to the total amount of space
218
+ # the user can use. This number would be higher if compared
219
+ # to root's because the user has less space (usually -5%).
220
+ usage_percent_user = usage_percent(used, total_user, round_=1)
221
+
222
+ # NB: the percentage is -5% than what shown by df due to
223
+ # reserved blocks that we are currently not considering:
224
+ # https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462
225
+ return sdiskusage(
226
+ total=total, used=used, free=avail_to_user, percent=usage_percent_user
227
+ )
228
+
229
+
230
+ @memoize
231
+ def get_terminal_map():
232
+ """Get a map of device-id -> path as a dict.
233
+ Used by Process.terminal().
234
+ """
235
+ ret = {}
236
+ ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
237
+ for name in ls:
238
+ assert name not in ret, name
239
+ try:
240
+ ret[os.stat(name).st_rdev] = name
241
+ except FileNotFoundError:
242
+ pass
243
+ return ret
llmeval-env/lib/python3.10/site-packages/psutil/_pssunos.py ADDED
@@ -0,0 +1,756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """Sun OS Solaris platform implementation."""
6
+
7
+ import errno
8
+ import functools
9
+ import os
10
+ import socket
11
+ import subprocess
12
+ import sys
13
+ from collections import namedtuple
14
+ from socket import AF_INET
15
+
16
+ from . import _common
17
+ from . import _psposix
18
+ from . import _psutil_posix as cext_posix
19
+ from . import _psutil_sunos as cext
20
+ from ._common import AF_INET6
21
+ from ._common import AccessDenied
22
+ from ._common import NoSuchProcess
23
+ from ._common import ZombieProcess
24
+ from ._common import debug
25
+ from ._common import get_procfs_path
26
+ from ._common import isfile_strict
27
+ from ._common import memoize_when_activated
28
+ from ._common import sockfam_to_enum
29
+ from ._common import socktype_to_enum
30
+ from ._common import usage_percent
31
+ from ._compat import PY3
32
+ from ._compat import FileNotFoundError
33
+ from ._compat import PermissionError
34
+ from ._compat import ProcessLookupError
35
+ from ._compat import b
36
+
37
+
38
+ __extra__all__ = ["CONN_IDLE", "CONN_BOUND", "PROCFS_PATH"]
39
+
40
+
41
+ # =====================================================================
42
+ # --- globals
43
+ # =====================================================================
44
+
45
+
46
+ PAGE_SIZE = cext_posix.getpagesize()
47
+ AF_LINK = cext_posix.AF_LINK
48
+ IS_64_BIT = sys.maxsize > 2**32
49
+
50
+ CONN_IDLE = "IDLE"
51
+ CONN_BOUND = "BOUND"
52
+
53
+ PROC_STATUSES = {
54
+ cext.SSLEEP: _common.STATUS_SLEEPING,
55
+ cext.SRUN: _common.STATUS_RUNNING,
56
+ cext.SZOMB: _common.STATUS_ZOMBIE,
57
+ cext.SSTOP: _common.STATUS_STOPPED,
58
+ cext.SIDL: _common.STATUS_IDLE,
59
+ cext.SONPROC: _common.STATUS_RUNNING, # same as run
60
+ cext.SWAIT: _common.STATUS_WAITING,
61
+ }
62
+
63
+ TCP_STATUSES = {
64
+ cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
65
+ cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
66
+ cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
67
+ cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
68
+ cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
69
+ cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
70
+ cext.TCPS_CLOSED: _common.CONN_CLOSE,
71
+ cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
72
+ cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
73
+ cext.TCPS_LISTEN: _common.CONN_LISTEN,
74
+ cext.TCPS_CLOSING: _common.CONN_CLOSING,
75
+ cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
76
+ cext.TCPS_IDLE: CONN_IDLE, # sunos specific
77
+ cext.TCPS_BOUND: CONN_BOUND, # sunos specific
78
+ }
79
+
80
+ proc_info_map = dict(
81
+ ppid=0,
82
+ rss=1,
83
+ vms=2,
84
+ create_time=3,
85
+ nice=4,
86
+ num_threads=5,
87
+ status=6,
88
+ ttynr=7,
89
+ uid=8,
90
+ euid=9,
91
+ gid=10,
92
+ egid=11,
93
+ )
94
+
95
+
96
+ # =====================================================================
97
+ # --- named tuples
98
+ # =====================================================================
99
+
100
+
101
+ # psutil.cpu_times()
102
+ scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
103
+ # psutil.cpu_times(percpu=True)
104
+ pcputimes = namedtuple(
105
+ 'pcputimes', ['user', 'system', 'children_user', 'children_system']
106
+ )
107
+ # psutil.virtual_memory()
108
+ svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
109
+ # psutil.Process.memory_info()
110
+ pmem = namedtuple('pmem', ['rss', 'vms'])
111
+ pfullmem = pmem
112
+ # psutil.Process.memory_maps(grouped=True)
113
+ pmmap_grouped = namedtuple(
114
+ 'pmmap_grouped', ['path', 'rss', 'anonymous', 'locked']
115
+ )
116
+ # psutil.Process.memory_maps(grouped=False)
117
+ pmmap_ext = namedtuple(
118
+ 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields)
119
+ )
120
+
121
+
122
+ # =====================================================================
123
+ # --- memory
124
+ # =====================================================================
125
+
126
+
127
+ def virtual_memory():
128
+ """Report virtual memory metrics."""
129
+ # we could have done this with kstat, but IMHO this is good enough
130
+ total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE
131
+ # note: there's no difference on Solaris
132
+ free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE
133
+ used = total - free
134
+ percent = usage_percent(used, total, round_=1)
135
+ return svmem(total, avail, percent, used, free)
136
+
137
+
138
+ def swap_memory():
139
+ """Report swap memory metrics."""
140
+ sin, sout = cext.swap_mem()
141
+ # XXX
142
+ # we are supposed to get total/free by doing so:
143
+ # http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/
144
+ # usr/src/cmd/swap/swap.c
145
+ # ...nevertheless I can't manage to obtain the same numbers as 'swap'
146
+ # cmdline utility, so let's parse its output (sigh!)
147
+ p = subprocess.Popen(
148
+ [
149
+ '/usr/bin/env',
150
+ 'PATH=/usr/sbin:/sbin:%s' % os.environ['PATH'],
151
+ 'swap',
152
+ '-l',
153
+ ],
154
+ stdout=subprocess.PIPE,
155
+ )
156
+ stdout, _ = p.communicate()
157
+ if PY3:
158
+ stdout = stdout.decode(sys.stdout.encoding)
159
+ if p.returncode != 0:
160
+ raise RuntimeError("'swap -l' failed (retcode=%s)" % p.returncode)
161
+
162
+ lines = stdout.strip().split('\n')[1:]
163
+ if not lines:
164
+ msg = 'no swap device(s) configured'
165
+ raise RuntimeError(msg)
166
+ total = free = 0
167
+ for line in lines:
168
+ line = line.split()
169
+ t, f = line[3:5]
170
+ total += int(int(t) * 512)
171
+ free += int(int(f) * 512)
172
+ used = total - free
173
+ percent = usage_percent(used, total, round_=1)
174
+ return _common.sswap(
175
+ total, used, free, percent, sin * PAGE_SIZE, sout * PAGE_SIZE
176
+ )
177
+
178
+
179
+ # =====================================================================
180
+ # --- CPU
181
+ # =====================================================================
182
+
183
+
184
+ def cpu_times():
185
+ """Return system-wide CPU times as a named tuple."""
186
+ ret = cext.per_cpu_times()
187
+ return scputimes(*[sum(x) for x in zip(*ret)])
188
+
189
+
190
+ def per_cpu_times():
191
+ """Return system per-CPU times as a list of named tuples."""
192
+ ret = cext.per_cpu_times()
193
+ return [scputimes(*x) for x in ret]
194
+
195
+
196
+ def cpu_count_logical():
197
+ """Return the number of logical CPUs in the system."""
198
+ try:
199
+ return os.sysconf("SC_NPROCESSORS_ONLN")
200
+ except ValueError:
201
+ # mimic os.cpu_count() behavior
202
+ return None
203
+
204
+
205
+ def cpu_count_cores():
206
+ """Return the number of CPU cores in the system."""
207
+ return cext.cpu_count_cores()
208
+
209
+
210
+ def cpu_stats():
211
+ """Return various CPU stats as a named tuple."""
212
+ ctx_switches, interrupts, syscalls, traps = cext.cpu_stats()
213
+ soft_interrupts = 0
214
+ return _common.scpustats(
215
+ ctx_switches, interrupts, soft_interrupts, syscalls
216
+ )
217
+
218
+
219
+ # =====================================================================
220
+ # --- disks
221
+ # =====================================================================
222
+
223
+
224
+ disk_io_counters = cext.disk_io_counters
225
+ disk_usage = _psposix.disk_usage
226
+
227
+
228
+ def disk_partitions(all=False):
229
+ """Return system disk partitions."""
230
+ # TODO - the filtering logic should be better checked so that
231
+ # it tries to reflect 'df' as much as possible
232
+ retlist = []
233
+ partitions = cext.disk_partitions()
234
+ for partition in partitions:
235
+ device, mountpoint, fstype, opts = partition
236
+ if device == 'none':
237
+ device = ''
238
+ if not all:
239
+ # Differently from, say, Linux, we don't have a list of
240
+ # common fs types so the best we can do, AFAIK, is to
241
+ # filter by filesystem having a total size > 0.
242
+ try:
243
+ if not disk_usage(mountpoint).total:
244
+ continue
245
+ except OSError as err:
246
+ # https://github.com/giampaolo/psutil/issues/1674
247
+ debug("skipping %r: %s" % (mountpoint, err))
248
+ continue
249
+ maxfile = maxpath = None # set later
250
+ ntuple = _common.sdiskpart(
251
+ device, mountpoint, fstype, opts, maxfile, maxpath
252
+ )
253
+ retlist.append(ntuple)
254
+ return retlist
255
+
256
+
257
+ # =====================================================================
258
+ # --- network
259
+ # =====================================================================
260
+
261
+
262
+ net_io_counters = cext.net_io_counters
263
+ net_if_addrs = cext_posix.net_if_addrs
264
+
265
+
266
+ def net_connections(kind, _pid=-1):
267
+ """Return socket connections. If pid == -1 return system-wide
268
+ connections (as opposed to connections opened by one process only).
269
+ Only INET sockets are returned (UNIX are not).
270
+ """
271
+ cmap = _common.conn_tmap.copy()
272
+ if _pid == -1:
273
+ cmap.pop('unix', 0)
274
+ if kind not in cmap:
275
+ raise ValueError(
276
+ "invalid %r kind argument; choose between %s"
277
+ % (kind, ', '.join([repr(x) for x in cmap]))
278
+ )
279
+ families, types = _common.conn_tmap[kind]
280
+ rawlist = cext.net_connections(_pid)
281
+ ret = set()
282
+ for item in rawlist:
283
+ fd, fam, type_, laddr, raddr, status, pid = item
284
+ if fam not in families:
285
+ continue
286
+ if type_ not in types:
287
+ continue
288
+ # TODO: refactor and use _common.conn_to_ntuple.
289
+ if fam in (AF_INET, AF_INET6):
290
+ if laddr:
291
+ laddr = _common.addr(*laddr)
292
+ if raddr:
293
+ raddr = _common.addr(*raddr)
294
+ status = TCP_STATUSES[status]
295
+ fam = sockfam_to_enum(fam)
296
+ type_ = socktype_to_enum(type_)
297
+ if _pid == -1:
298
+ nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid)
299
+ else:
300
+ nt = _common.pconn(fd, fam, type_, laddr, raddr, status)
301
+ ret.add(nt)
302
+ return list(ret)
303
+
304
+
305
+ def net_if_stats():
306
+ """Get NIC stats (isup, duplex, speed, mtu)."""
307
+ ret = cext.net_if_stats()
308
+ for name, items in ret.items():
309
+ isup, duplex, speed, mtu = items
310
+ if hasattr(_common, 'NicDuplex'):
311
+ duplex = _common.NicDuplex(duplex)
312
+ ret[name] = _common.snicstats(isup, duplex, speed, mtu, '')
313
+ return ret
314
+
315
+
316
+ # =====================================================================
317
+ # --- other system functions
318
+ # =====================================================================
319
+
320
+
321
+ def boot_time():
322
+ """The system boot time expressed in seconds since the epoch."""
323
+ return cext.boot_time()
324
+
325
+
326
+ def users():
327
+ """Return currently connected users as a list of namedtuples."""
328
+ retlist = []
329
+ rawlist = cext.users()
330
+ localhost = (':0.0', ':0')
331
+ for item in rawlist:
332
+ user, tty, hostname, tstamp, user_process, pid = item
333
+ # note: the underlying C function includes entries about
334
+ # system boot, run level and others. We might want
335
+ # to use them in the future.
336
+ if not user_process:
337
+ continue
338
+ if hostname in localhost:
339
+ hostname = 'localhost'
340
+ nt = _common.suser(user, tty, hostname, tstamp, pid)
341
+ retlist.append(nt)
342
+ return retlist
343
+
344
+
345
+ # =====================================================================
346
+ # --- processes
347
+ # =====================================================================
348
+
349
+
350
+ def pids():
351
+ """Returns a list of PIDs currently running on the system."""
352
+ return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]
353
+
354
+
355
+ def pid_exists(pid):
356
+ """Check for the existence of a unix pid."""
357
+ return _psposix.pid_exists(pid)
358
+
359
+
360
+ def wrap_exceptions(fun):
361
+ """Call callable into a try/except clause and translate ENOENT,
362
+ EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
363
+ """
364
+
365
+ @functools.wraps(fun)
366
+ def wrapper(self, *args, **kwargs):
367
+ try:
368
+ return fun(self, *args, **kwargs)
369
+ except (FileNotFoundError, ProcessLookupError):
370
+ # ENOENT (no such file or directory) gets raised on open().
371
+ # ESRCH (no such process) can get raised on read() if
372
+ # process is gone in meantime.
373
+ if not pid_exists(self.pid):
374
+ raise NoSuchProcess(self.pid, self._name)
375
+ else:
376
+ raise ZombieProcess(self.pid, self._name, self._ppid)
377
+ except PermissionError:
378
+ raise AccessDenied(self.pid, self._name)
379
+ except OSError:
380
+ if self.pid == 0:
381
+ if 0 in pids():
382
+ raise AccessDenied(self.pid, self._name)
383
+ else:
384
+ raise
385
+ raise
386
+
387
+ return wrapper
388
+
389
+
390
+ class Process:
391
+ """Wrapper class around underlying C implementation."""
392
+
393
+ __slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
394
+
395
+ def __init__(self, pid):
396
+ self.pid = pid
397
+ self._name = None
398
+ self._ppid = None
399
+ self._procfs_path = get_procfs_path()
400
+
401
+ def _assert_alive(self):
402
+ """Raise NSP if the process disappeared on us."""
403
+ # For those C function who do not raise NSP, possibly returning
404
+ # incorrect or incomplete result.
405
+ os.stat('%s/%s' % (self._procfs_path, self.pid))
406
+
407
+ def oneshot_enter(self):
408
+ self._proc_name_and_args.cache_activate(self)
409
+ self._proc_basic_info.cache_activate(self)
410
+ self._proc_cred.cache_activate(self)
411
+
412
+ def oneshot_exit(self):
413
+ self._proc_name_and_args.cache_deactivate(self)
414
+ self._proc_basic_info.cache_deactivate(self)
415
+ self._proc_cred.cache_deactivate(self)
416
+
417
+ @wrap_exceptions
418
+ @memoize_when_activated
419
+ def _proc_name_and_args(self):
420
+ return cext.proc_name_and_args(self.pid, self._procfs_path)
421
+
422
+ @wrap_exceptions
423
+ @memoize_when_activated
424
+ def _proc_basic_info(self):
425
+ if self.pid == 0 and not os.path.exists(
426
+ '%s/%s/psinfo' % (self._procfs_path, self.pid)
427
+ ):
428
+ raise AccessDenied(self.pid)
429
+ ret = cext.proc_basic_info(self.pid, self._procfs_path)
430
+ assert len(ret) == len(proc_info_map)
431
+ return ret
432
+
433
+ @wrap_exceptions
434
+ @memoize_when_activated
435
+ def _proc_cred(self):
436
+ return cext.proc_cred(self.pid, self._procfs_path)
437
+
438
+ @wrap_exceptions
439
+ def name(self):
440
+ # note: max len == 15
441
+ return self._proc_name_and_args()[0]
442
+
443
+ @wrap_exceptions
444
+ def exe(self):
445
+ try:
446
+ return os.readlink(
447
+ "%s/%s/path/a.out" % (self._procfs_path, self.pid)
448
+ )
449
+ except OSError:
450
+ pass # continue and guess the exe name from the cmdline
451
+ # Will be guessed later from cmdline but we want to explicitly
452
+ # invoke cmdline here in order to get an AccessDenied
453
+ # exception if the user has not enough privileges.
454
+ self.cmdline()
455
+ return ""
456
+
457
+ @wrap_exceptions
458
+ def cmdline(self):
459
+ return self._proc_name_and_args()[1].split(' ')
460
+
461
+ @wrap_exceptions
462
+ def environ(self):
463
+ return cext.proc_environ(self.pid, self._procfs_path)
464
+
465
+ @wrap_exceptions
466
+ def create_time(self):
467
+ return self._proc_basic_info()[proc_info_map['create_time']]
468
+
469
+ @wrap_exceptions
470
+ def num_threads(self):
471
+ return self._proc_basic_info()[proc_info_map['num_threads']]
472
+
473
+ @wrap_exceptions
474
+ def nice_get(self):
475
+ # Note #1: getpriority(3) doesn't work for realtime processes.
476
+ # Psinfo is what ps uses, see:
477
+ # https://github.com/giampaolo/psutil/issues/1194
478
+ return self._proc_basic_info()[proc_info_map['nice']]
479
+
480
+ @wrap_exceptions
481
+ def nice_set(self, value):
482
+ if self.pid in (2, 3):
483
+ # Special case PIDs: internally setpriority(3) return ESRCH
484
+ # (no such process), no matter what.
485
+ # The process actually exists though, as it has a name,
486
+ # creation time, etc.
487
+ raise AccessDenied(self.pid, self._name)
488
+ return cext_posix.setpriority(self.pid, value)
489
+
490
+ @wrap_exceptions
491
+ def ppid(self):
492
+ self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
493
+ return self._ppid
494
+
495
+ @wrap_exceptions
496
+ def uids(self):
497
+ try:
498
+ real, effective, saved, _, _, _ = self._proc_cred()
499
+ except AccessDenied:
500
+ real = self._proc_basic_info()[proc_info_map['uid']]
501
+ effective = self._proc_basic_info()[proc_info_map['euid']]
502
+ saved = None
503
+ return _common.puids(real, effective, saved)
504
+
505
+ @wrap_exceptions
506
+ def gids(self):
507
+ try:
508
+ _, _, _, real, effective, saved = self._proc_cred()
509
+ except AccessDenied:
510
+ real = self._proc_basic_info()[proc_info_map['gid']]
511
+ effective = self._proc_basic_info()[proc_info_map['egid']]
512
+ saved = None
513
+ return _common.puids(real, effective, saved)
514
+
515
+ @wrap_exceptions
516
+ def cpu_times(self):
517
+ try:
518
+ times = cext.proc_cpu_times(self.pid, self._procfs_path)
519
+ except OSError as err:
520
+ if err.errno == errno.EOVERFLOW and not IS_64_BIT:
521
+ # We may get here if we attempt to query a 64bit process
522
+ # with a 32bit python.
523
+ # Error originates from read() and also tools like "cat"
524
+ # fail in the same way (!).
525
+ # Since there simply is no way to determine CPU times we
526
+ # return 0.0 as a fallback. See:
527
+ # https://github.com/giampaolo/psutil/issues/857
528
+ times = (0.0, 0.0, 0.0, 0.0)
529
+ else:
530
+ raise
531
+ return _common.pcputimes(*times)
532
+
533
+ @wrap_exceptions
534
+ def cpu_num(self):
535
+ return cext.proc_cpu_num(self.pid, self._procfs_path)
536
+
537
+ @wrap_exceptions
538
+ def terminal(self):
539
+ procfs_path = self._procfs_path
540
+ hit_enoent = False
541
+ tty = wrap_exceptions(self._proc_basic_info()[proc_info_map['ttynr']])
542
+ if tty != cext.PRNODEV:
543
+ for x in (0, 1, 2, 255):
544
+ try:
545
+ return os.readlink(
546
+ '%s/%d/path/%d' % (procfs_path, self.pid, x)
547
+ )
548
+ except FileNotFoundError:
549
+ hit_enoent = True
550
+ continue
551
+ if hit_enoent:
552
+ self._assert_alive()
553
+
554
+ @wrap_exceptions
555
+ def cwd(self):
556
+ # /proc/PID/path/cwd may not be resolved by readlink() even if
557
+ # it exists (ls shows it). If that's the case and the process
558
+ # is still alive return None (we can return None also on BSD).
559
+ # Reference: http://goo.gl/55XgO
560
+ procfs_path = self._procfs_path
561
+ try:
562
+ return os.readlink("%s/%s/path/cwd" % (procfs_path, self.pid))
563
+ except FileNotFoundError:
564
+ os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
565
+ return ""
566
+
567
+ @wrap_exceptions
568
+ def memory_info(self):
569
+ ret = self._proc_basic_info()
570
+ rss = ret[proc_info_map['rss']] * 1024
571
+ vms = ret[proc_info_map['vms']] * 1024
572
+ return pmem(rss, vms)
573
+
574
+ memory_full_info = memory_info
575
+
576
+ @wrap_exceptions
577
+ def status(self):
578
+ code = self._proc_basic_info()[proc_info_map['status']]
579
+ # XXX is '?' legit? (we're not supposed to return it anyway)
580
+ return PROC_STATUSES.get(code, '?')
581
+
582
+ @wrap_exceptions
583
+ def threads(self):
584
+ procfs_path = self._procfs_path
585
+ ret = []
586
+ tids = os.listdir('%s/%d/lwp' % (procfs_path, self.pid))
587
+ hit_enoent = False
588
+ for tid in tids:
589
+ tid = int(tid)
590
+ try:
591
+ utime, stime = cext.query_process_thread(
592
+ self.pid, tid, procfs_path
593
+ )
594
+ except EnvironmentError as err:
595
+ if err.errno == errno.EOVERFLOW and not IS_64_BIT:
596
+ # We may get here if we attempt to query a 64bit process
597
+ # with a 32bit python.
598
+ # Error originates from read() and also tools like "cat"
599
+ # fail in the same way (!).
600
+ # Since there simply is no way to determine CPU times we
601
+ # return 0.0 as a fallback. See:
602
+ # https://github.com/giampaolo/psutil/issues/857
603
+ continue
604
+ # ENOENT == thread gone in meantime
605
+ if err.errno == errno.ENOENT:
606
+ hit_enoent = True
607
+ continue
608
+ raise
609
+ else:
610
+ nt = _common.pthread(tid, utime, stime)
611
+ ret.append(nt)
612
+ if hit_enoent:
613
+ self._assert_alive()
614
+ return ret
615
+
616
+ @wrap_exceptions
617
+ def open_files(self):
618
+ retlist = []
619
+ hit_enoent = False
620
+ procfs_path = self._procfs_path
621
+ pathdir = '%s/%d/path' % (procfs_path, self.pid)
622
+ for fd in os.listdir('%s/%d/fd' % (procfs_path, self.pid)):
623
+ path = os.path.join(pathdir, fd)
624
+ if os.path.islink(path):
625
+ try:
626
+ file = os.readlink(path)
627
+ except FileNotFoundError:
628
+ hit_enoent = True
629
+ continue
630
+ else:
631
+ if isfile_strict(file):
632
+ retlist.append(_common.popenfile(file, int(fd)))
633
+ if hit_enoent:
634
+ self._assert_alive()
635
+ return retlist
636
+
637
+ def _get_unix_sockets(self, pid):
638
+ """Get UNIX sockets used by process by parsing 'pfiles' output."""
639
+ # TODO: rewrite this in C (...but the damn netstat source code
640
+ # does not include this part! Argh!!)
641
+ cmd = ["pfiles", str(pid)]
642
+ p = subprocess.Popen(
643
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
644
+ )
645
+ stdout, stderr = p.communicate()
646
+ if PY3:
647
+ stdout, stderr = (
648
+ x.decode(sys.stdout.encoding) for x in (stdout, stderr)
649
+ )
650
+ if p.returncode != 0:
651
+ if 'permission denied' in stderr.lower():
652
+ raise AccessDenied(self.pid, self._name)
653
+ if 'no such process' in stderr.lower():
654
+ raise NoSuchProcess(self.pid, self._name)
655
+ raise RuntimeError("%r command error\n%s" % (cmd, stderr))
656
+
657
+ lines = stdout.split('\n')[2:]
658
+ for i, line in enumerate(lines):
659
+ line = line.lstrip()
660
+ if line.startswith('sockname: AF_UNIX'):
661
+ path = line.split(' ', 2)[2]
662
+ type = lines[i - 2].strip()
663
+ if type == 'SOCK_STREAM':
664
+ type = socket.SOCK_STREAM
665
+ elif type == 'SOCK_DGRAM':
666
+ type = socket.SOCK_DGRAM
667
+ else:
668
+ type = -1
669
+ yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)
670
+
671
+ @wrap_exceptions
672
+ def connections(self, kind='inet'):
673
+ ret = net_connections(kind, _pid=self.pid)
674
+ # The underlying C implementation retrieves all OS connections
675
+ # and filters them by PID. At this point we can't tell whether
676
+ # an empty list means there were no connections for process or
677
+ # process is no longer active so we force NSP in case the PID
678
+ # is no longer there.
679
+ if not ret:
680
+ # will raise NSP if process is gone
681
+ os.stat('%s/%s' % (self._procfs_path, self.pid))
682
+
683
+ # UNIX sockets
684
+ if kind in ('all', 'unix'):
685
+ ret.extend([
686
+ _common.pconn(*conn)
687
+ for conn in self._get_unix_sockets(self.pid)
688
+ ])
689
+ return ret
690
+
691
+ nt_mmap_grouped = namedtuple('mmap', 'path rss anon locked')
692
+ nt_mmap_ext = namedtuple('mmap', 'addr perms path rss anon locked')
693
+
694
+ @wrap_exceptions
695
+ def memory_maps(self):
696
+ def toaddr(start, end):
697
+ return '%s-%s' % (
698
+ hex(start)[2:].strip('L'),
699
+ hex(end)[2:].strip('L'),
700
+ )
701
+
702
+ procfs_path = self._procfs_path
703
+ retlist = []
704
+ try:
705
+ rawlist = cext.proc_memory_maps(self.pid, procfs_path)
706
+ except OSError as err:
707
+ if err.errno == errno.EOVERFLOW and not IS_64_BIT:
708
+ # We may get here if we attempt to query a 64bit process
709
+ # with a 32bit python.
710
+ # Error originates from read() and also tools like "cat"
711
+ # fail in the same way (!).
712
+ # Since there simply is no way to determine CPU times we
713
+ # return 0.0 as a fallback. See:
714
+ # https://github.com/giampaolo/psutil/issues/857
715
+ return []
716
+ else:
717
+ raise
718
+ hit_enoent = False
719
+ for item in rawlist:
720
+ addr, addrsize, perm, name, rss, anon, locked = item
721
+ addr = toaddr(addr, addrsize)
722
+ if not name.startswith('['):
723
+ try:
724
+ name = os.readlink(
725
+ '%s/%s/path/%s' % (procfs_path, self.pid, name)
726
+ )
727
+ except OSError as err:
728
+ if err.errno == errno.ENOENT:
729
+ # sometimes the link may not be resolved by
730
+ # readlink() even if it exists (ls shows it).
731
+ # If that's the case we just return the
732
+ # unresolved link path.
733
+ # This seems an incosistency with /proc similar
734
+ # to: http://goo.gl/55XgO
735
+ name = '%s/%s/path/%s' % (procfs_path, self.pid, name)
736
+ hit_enoent = True
737
+ else:
738
+ raise
739
+ retlist.append((addr, perm, name, rss, anon, locked))
740
+ if hit_enoent:
741
+ self._assert_alive()
742
+ return retlist
743
+
744
+ @wrap_exceptions
745
+ def num_fds(self):
746
+ return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
747
+
748
+ @wrap_exceptions
749
+ def num_ctx_switches(self):
750
+ return _common.pctxsw(
751
+ *cext.proc_num_ctx_switches(self.pid, self._procfs_path)
752
+ )
753
+
754
+ @wrap_exceptions
755
+ def wait(self, timeout=None):
756
+ return _psposix.wait_pid(self.pid, timeout, self._name)
llmeval-env/lib/python3.10/site-packages/psutil/_psutil_linux.abi3.so ADDED
Binary file (115 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/_psutil_posix.abi3.so ADDED
Binary file (71.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/_pswindows.py ADDED
@@ -0,0 +1,1170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """Windows platform implementation."""
6
+
7
+ import contextlib
8
+ import errno
9
+ import functools
10
+ import os
11
+ import signal
12
+ import sys
13
+ import time
14
+ from collections import namedtuple
15
+
16
+ from . import _common
17
+ from ._common import ENCODING
18
+ from ._common import ENCODING_ERRS
19
+ from ._common import AccessDenied
20
+ from ._common import NoSuchProcess
21
+ from ._common import TimeoutExpired
22
+ from ._common import conn_tmap
23
+ from ._common import conn_to_ntuple
24
+ from ._common import debug
25
+ from ._common import isfile_strict
26
+ from ._common import memoize
27
+ from ._common import memoize_when_activated
28
+ from ._common import parse_environ_block
29
+ from ._common import usage_percent
30
+ from ._compat import PY3
31
+ from ._compat import long
32
+ from ._compat import lru_cache
33
+ from ._compat import range
34
+ from ._compat import unicode
35
+ from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS
36
+ from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS
37
+ from ._psutil_windows import HIGH_PRIORITY_CLASS
38
+ from ._psutil_windows import IDLE_PRIORITY_CLASS
39
+ from ._psutil_windows import NORMAL_PRIORITY_CLASS
40
+ from ._psutil_windows import REALTIME_PRIORITY_CLASS
41
+
42
+
43
+ try:
44
+ from . import _psutil_windows as cext
45
+ except ImportError as err:
46
+ if (
47
+ str(err).lower().startswith("dll load failed")
48
+ and sys.getwindowsversion()[0] < 6
49
+ ):
50
+ # We may get here if:
51
+ # 1) we are on an old Windows version
52
+ # 2) psutil was installed via pip + wheel
53
+ # See: https://github.com/giampaolo/psutil/issues/811
54
+ msg = "this Windows version is too old (< Windows Vista); "
55
+ msg += "psutil 3.4.2 is the latest version which supports Windows "
56
+ msg += "2000, XP and 2003 server"
57
+ raise RuntimeError(msg)
58
+ else:
59
+ raise
60
+
61
+ if PY3:
62
+ import enum
63
+ else:
64
+ enum = None
65
+
66
+ # process priority constants, import from __init__.py:
67
+ # http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx
68
+ # fmt: off
69
+ __extra__all__ = [
70
+ "win_service_iter", "win_service_get",
71
+ # Process priority
72
+ "ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
73
+ "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS", "NORMAL_PRIORITY_CLASS",
74
+ "REALTIME_PRIORITY_CLASS",
75
+ # IO priority
76
+ "IOPRIO_VERYLOW", "IOPRIO_LOW", "IOPRIO_NORMAL", "IOPRIO_HIGH",
77
+ # others
78
+ "CONN_DELETE_TCB", "AF_LINK",
79
+ ]
80
+ # fmt: on
81
+
82
+
83
+ # =====================================================================
84
+ # --- globals
85
+ # =====================================================================
86
+
87
+ CONN_DELETE_TCB = "DELETE_TCB"
88
+ ERROR_PARTIAL_COPY = 299
89
+ PYPY = '__pypy__' in sys.builtin_module_names
90
+
91
+ if enum is None:
92
+ AF_LINK = -1
93
+ else:
94
+ AddressFamily = enum.IntEnum('AddressFamily', {'AF_LINK': -1})
95
+ AF_LINK = AddressFamily.AF_LINK
96
+
97
+ TCP_STATUSES = {
98
+ cext.MIB_TCP_STATE_ESTAB: _common.CONN_ESTABLISHED,
99
+ cext.MIB_TCP_STATE_SYN_SENT: _common.CONN_SYN_SENT,
100
+ cext.MIB_TCP_STATE_SYN_RCVD: _common.CONN_SYN_RECV,
101
+ cext.MIB_TCP_STATE_FIN_WAIT1: _common.CONN_FIN_WAIT1,
102
+ cext.MIB_TCP_STATE_FIN_WAIT2: _common.CONN_FIN_WAIT2,
103
+ cext.MIB_TCP_STATE_TIME_WAIT: _common.CONN_TIME_WAIT,
104
+ cext.MIB_TCP_STATE_CLOSED: _common.CONN_CLOSE,
105
+ cext.MIB_TCP_STATE_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
106
+ cext.MIB_TCP_STATE_LAST_ACK: _common.CONN_LAST_ACK,
107
+ cext.MIB_TCP_STATE_LISTEN: _common.CONN_LISTEN,
108
+ cext.MIB_TCP_STATE_CLOSING: _common.CONN_CLOSING,
109
+ cext.MIB_TCP_STATE_DELETE_TCB: CONN_DELETE_TCB,
110
+ cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
111
+ }
112
+
113
+ if enum is not None:
114
+
115
+ class Priority(enum.IntEnum):
116
+ ABOVE_NORMAL_PRIORITY_CLASS = ABOVE_NORMAL_PRIORITY_CLASS
117
+ BELOW_NORMAL_PRIORITY_CLASS = BELOW_NORMAL_PRIORITY_CLASS
118
+ HIGH_PRIORITY_CLASS = HIGH_PRIORITY_CLASS
119
+ IDLE_PRIORITY_CLASS = IDLE_PRIORITY_CLASS
120
+ NORMAL_PRIORITY_CLASS = NORMAL_PRIORITY_CLASS
121
+ REALTIME_PRIORITY_CLASS = REALTIME_PRIORITY_CLASS
122
+
123
+ globals().update(Priority.__members__)
124
+
125
+ if enum is None:
126
+ IOPRIO_VERYLOW = 0
127
+ IOPRIO_LOW = 1
128
+ IOPRIO_NORMAL = 2
129
+ IOPRIO_HIGH = 3
130
+ else:
131
+
132
+ class IOPriority(enum.IntEnum):
133
+ IOPRIO_VERYLOW = 0
134
+ IOPRIO_LOW = 1
135
+ IOPRIO_NORMAL = 2
136
+ IOPRIO_HIGH = 3
137
+
138
+ globals().update(IOPriority.__members__)
139
+
140
+ pinfo_map = dict(
141
+ num_handles=0,
142
+ ctx_switches=1,
143
+ user_time=2,
144
+ kernel_time=3,
145
+ create_time=4,
146
+ num_threads=5,
147
+ io_rcount=6,
148
+ io_wcount=7,
149
+ io_rbytes=8,
150
+ io_wbytes=9,
151
+ io_count_others=10,
152
+ io_bytes_others=11,
153
+ num_page_faults=12,
154
+ peak_wset=13,
155
+ wset=14,
156
+ peak_paged_pool=15,
157
+ paged_pool=16,
158
+ peak_non_paged_pool=17,
159
+ non_paged_pool=18,
160
+ pagefile=19,
161
+ peak_pagefile=20,
162
+ mem_private=21,
163
+ )
164
+
165
+
166
+ # =====================================================================
167
+ # --- named tuples
168
+ # =====================================================================
169
+
170
+
171
+ # fmt: off
172
+ # psutil.cpu_times()
173
+ scputimes = namedtuple('scputimes',
174
+ ['user', 'system', 'idle', 'interrupt', 'dpc'])
175
+ # psutil.virtual_memory()
176
+ svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
177
+ # psutil.Process.memory_info()
178
+ pmem = namedtuple(
179
+ 'pmem', ['rss', 'vms',
180
+ 'num_page_faults', 'peak_wset', 'wset', 'peak_paged_pool',
181
+ 'paged_pool', 'peak_nonpaged_pool', 'nonpaged_pool',
182
+ 'pagefile', 'peak_pagefile', 'private'])
183
+ # psutil.Process.memory_full_info()
184
+ pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
185
+ # psutil.Process.memory_maps(grouped=True)
186
+ pmmap_grouped = namedtuple('pmmap_grouped', ['path', 'rss'])
187
+ # psutil.Process.memory_maps(grouped=False)
188
+ pmmap_ext = namedtuple(
189
+ 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
190
+ # psutil.Process.io_counters()
191
+ pio = namedtuple('pio', ['read_count', 'write_count',
192
+ 'read_bytes', 'write_bytes',
193
+ 'other_count', 'other_bytes'])
194
+ # fmt: on
195
+
196
+
197
+ # =====================================================================
198
+ # --- utils
199
+ # =====================================================================
200
+
201
+
202
+ @lru_cache(maxsize=512)
203
+ def convert_dos_path(s):
204
+ r"""Convert paths using native DOS format like:
205
+ "\Device\HarddiskVolume1\Windows\systemew\file.txt"
206
+ into:
207
+ "C:\Windows\systemew\file.txt".
208
+ """
209
+ rawdrive = '\\'.join(s.split('\\')[:3])
210
+ driveletter = cext.QueryDosDevice(rawdrive)
211
+ remainder = s[len(rawdrive) :]
212
+ return os.path.join(driveletter, remainder)
213
+
214
+
215
+ def py2_strencode(s):
216
+ """Encode a unicode string to a byte string by using the default fs
217
+ encoding + "replace" error handler.
218
+ """
219
+ if PY3:
220
+ return s
221
+ else:
222
+ if isinstance(s, str):
223
+ return s
224
+ else:
225
+ return s.encode(ENCODING, ENCODING_ERRS)
226
+
227
+
228
+ @memoize
229
+ def getpagesize():
230
+ return cext.getpagesize()
231
+
232
+
233
+ # =====================================================================
234
+ # --- memory
235
+ # =====================================================================
236
+
237
+
238
+ def virtual_memory():
239
+ """System virtual memory as a namedtuple."""
240
+ mem = cext.virtual_mem()
241
+ totphys, availphys, totsys, availsys = mem
242
+ #
243
+ total = totphys
244
+ avail = availphys
245
+ free = availphys
246
+ used = total - avail
247
+ percent = usage_percent((total - avail), total, round_=1)
248
+ return svmem(total, avail, percent, used, free)
249
+
250
+
251
+ def swap_memory():
252
+ """Swap system memory as a (total, used, free, sin, sout) tuple."""
253
+ mem = cext.virtual_mem()
254
+
255
+ total_phys = mem[0]
256
+ total_system = mem[2]
257
+
258
+ # system memory (commit total/limit) is the sum of physical and swap
259
+ # thus physical memory values need to be subtracted to get swap values
260
+ total = total_system - total_phys
261
+ # commit total is incremented immediately (decrementing free_system)
262
+ # while the corresponding free physical value is not decremented until
263
+ # pages are accessed, so we can't use free system memory for swap.
264
+ # instead, we calculate page file usage based on performance counter
265
+ if total > 0:
266
+ percentswap = cext.swap_percent()
267
+ used = int(0.01 * percentswap * total)
268
+ else:
269
+ percentswap = 0.0
270
+ used = 0
271
+
272
+ free = total - used
273
+ percent = round(percentswap, 1)
274
+ return _common.sswap(total, used, free, percent, 0, 0)
275
+
276
+
277
+ # =====================================================================
278
+ # --- disk
279
+ # =====================================================================
280
+
281
+
282
+ disk_io_counters = cext.disk_io_counters
283
+
284
+
285
+ def disk_usage(path):
286
+ """Return disk usage associated with path."""
287
+ if PY3 and isinstance(path, bytes):
288
+ # XXX: do we want to use "strict"? Probably yes, in order
289
+ # to fail immediately. After all we are accepting input here...
290
+ path = path.decode(ENCODING, errors="strict")
291
+ total, free = cext.disk_usage(path)
292
+ used = total - free
293
+ percent = usage_percent(used, total, round_=1)
294
+ return _common.sdiskusage(total, used, free, percent)
295
+
296
+
297
+ def disk_partitions(all):
298
+ """Return disk partitions."""
299
+ rawlist = cext.disk_partitions(all)
300
+ return [_common.sdiskpart(*x) for x in rawlist]
301
+
302
+
303
+ # =====================================================================
304
+ # --- CPU
305
+ # =====================================================================
306
+
307
+
308
+ def cpu_times():
309
+ """Return system CPU times as a named tuple."""
310
+ user, system, idle = cext.cpu_times()
311
+ # Internally, GetSystemTimes() is used, and it doesn't return
312
+ # interrupt and dpc times. cext.per_cpu_times() does, so we
313
+ # rely on it to get those only.
314
+ percpu_summed = scputimes(*[sum(n) for n in zip(*cext.per_cpu_times())])
315
+ return scputimes(
316
+ user, system, idle, percpu_summed.interrupt, percpu_summed.dpc
317
+ )
318
+
319
+
320
+ def per_cpu_times():
321
+ """Return system per-CPU times as a list of named tuples."""
322
+ ret = []
323
+ for user, system, idle, interrupt, dpc in cext.per_cpu_times():
324
+ item = scputimes(user, system, idle, interrupt, dpc)
325
+ ret.append(item)
326
+ return ret
327
+
328
+
329
+ def cpu_count_logical():
330
+ """Return the number of logical CPUs in the system."""
331
+ return cext.cpu_count_logical()
332
+
333
+
334
+ def cpu_count_cores():
335
+ """Return the number of CPU cores in the system."""
336
+ return cext.cpu_count_cores()
337
+
338
+
339
+ def cpu_stats():
340
+ """Return CPU statistics."""
341
+ ctx_switches, interrupts, dpcs, syscalls = cext.cpu_stats()
342
+ soft_interrupts = 0
343
+ return _common.scpustats(
344
+ ctx_switches, interrupts, soft_interrupts, syscalls
345
+ )
346
+
347
+
348
+ def cpu_freq():
349
+ """Return CPU frequency.
350
+ On Windows per-cpu frequency is not supported.
351
+ """
352
+ curr, max_ = cext.cpu_freq()
353
+ min_ = 0.0
354
+ return [_common.scpufreq(float(curr), min_, float(max_))]
355
+
356
+
357
+ _loadavg_inititialized = False
358
+
359
+
360
+ def getloadavg():
361
+ """Return the number of processes in the system run queue averaged
362
+ over the last 1, 5, and 15 minutes respectively as a tuple.
363
+ """
364
+ global _loadavg_inititialized
365
+
366
+ if not _loadavg_inititialized:
367
+ cext.init_loadavg_counter()
368
+ _loadavg_inititialized = True
369
+
370
+ # Drop to 2 decimal points which is what Linux does
371
+ raw_loads = cext.getloadavg()
372
+ return tuple([round(load, 2) for load in raw_loads])
373
+
374
+
375
+ # =====================================================================
376
+ # --- network
377
+ # =====================================================================
378
+
379
+
380
+ def net_connections(kind, _pid=-1):
381
+ """Return socket connections. If pid == -1 return system-wide
382
+ connections (as opposed to connections opened by one process only).
383
+ """
384
+ if kind not in conn_tmap:
385
+ raise ValueError(
386
+ "invalid %r kind argument; choose between %s"
387
+ % (kind, ', '.join([repr(x) for x in conn_tmap]))
388
+ )
389
+ families, types = conn_tmap[kind]
390
+ rawlist = cext.net_connections(_pid, families, types)
391
+ ret = set()
392
+ for item in rawlist:
393
+ fd, fam, type, laddr, raddr, status, pid = item
394
+ nt = conn_to_ntuple(
395
+ fd,
396
+ fam,
397
+ type,
398
+ laddr,
399
+ raddr,
400
+ status,
401
+ TCP_STATUSES,
402
+ pid=pid if _pid == -1 else None,
403
+ )
404
+ ret.add(nt)
405
+ return list(ret)
406
+
407
+
408
+ def net_if_stats():
409
+ """Get NIC stats (isup, duplex, speed, mtu)."""
410
+ ret = {}
411
+ rawdict = cext.net_if_stats()
412
+ for name, items in rawdict.items():
413
+ if not PY3:
414
+ assert isinstance(name, unicode), type(name)
415
+ name = py2_strencode(name)
416
+ isup, duplex, speed, mtu = items
417
+ if hasattr(_common, 'NicDuplex'):
418
+ duplex = _common.NicDuplex(duplex)
419
+ ret[name] = _common.snicstats(isup, duplex, speed, mtu, '')
420
+ return ret
421
+
422
+
423
+ def net_io_counters():
424
+ """Return network I/O statistics for every network interface
425
+ installed on the system as a dict of raw tuples.
426
+ """
427
+ ret = cext.net_io_counters()
428
+ return dict([(py2_strencode(k), v) for k, v in ret.items()])
429
+
430
+
431
+ def net_if_addrs():
432
+ """Return the addresses associated to each NIC."""
433
+ ret = []
434
+ for items in cext.net_if_addrs():
435
+ items = list(items)
436
+ items[0] = py2_strencode(items[0])
437
+ ret.append(items)
438
+ return ret
439
+
440
+
441
+ # =====================================================================
442
+ # --- sensors
443
+ # =====================================================================
444
+
445
+
446
+ def sensors_battery():
447
+ """Return battery information."""
448
+ # For constants meaning see:
449
+ # https://msdn.microsoft.com/en-us/library/windows/desktop/
450
+ # aa373232(v=vs.85).aspx
451
+ acline_status, flags, percent, secsleft = cext.sensors_battery()
452
+ power_plugged = acline_status == 1
453
+ no_battery = bool(flags & 128)
454
+ charging = bool(flags & 8)
455
+
456
+ if no_battery:
457
+ return None
458
+ if power_plugged or charging:
459
+ secsleft = _common.POWER_TIME_UNLIMITED
460
+ elif secsleft == -1:
461
+ secsleft = _common.POWER_TIME_UNKNOWN
462
+
463
+ return _common.sbattery(percent, secsleft, power_plugged)
464
+
465
+
466
+ # =====================================================================
467
+ # --- other system functions
468
+ # =====================================================================
469
+
470
+
471
+ _last_btime = 0
472
+
473
+
474
+ def boot_time():
475
+ """The system boot time expressed in seconds since the epoch."""
476
+ # This dirty hack is to adjust the precision of the returned
477
+ # value which may have a 1 second fluctuation, see:
478
+ # https://github.com/giampaolo/psutil/issues/1007
479
+ global _last_btime
480
+ ret = float(cext.boot_time())
481
+ if abs(ret - _last_btime) <= 1:
482
+ return _last_btime
483
+ else:
484
+ _last_btime = ret
485
+ return ret
486
+
487
+
488
+ def users():
489
+ """Return currently connected users as a list of namedtuples."""
490
+ retlist = []
491
+ rawlist = cext.users()
492
+ for item in rawlist:
493
+ user, hostname, tstamp = item
494
+ user = py2_strencode(user)
495
+ nt = _common.suser(user, None, hostname, tstamp, None)
496
+ retlist.append(nt)
497
+ return retlist
498
+
499
+
500
+ # =====================================================================
501
+ # --- Windows services
502
+ # =====================================================================
503
+
504
+
505
+ def win_service_iter():
506
+ """Yields a list of WindowsService instances."""
507
+ for name, display_name in cext.winservice_enumerate():
508
+ yield WindowsService(py2_strencode(name), py2_strencode(display_name))
509
+
510
+
511
+ def win_service_get(name):
512
+ """Open a Windows service and return it as a WindowsService instance."""
513
+ service = WindowsService(name, None)
514
+ service._display_name = service._query_config()['display_name']
515
+ return service
516
+
517
+
518
+ class WindowsService:
519
+ """Represents an installed Windows service."""
520
+
521
+ def __init__(self, name, display_name):
522
+ self._name = name
523
+ self._display_name = display_name
524
+
525
+ def __str__(self):
526
+ details = "(name=%r, display_name=%r)" % (
527
+ self._name,
528
+ self._display_name,
529
+ )
530
+ return "%s%s" % (self.__class__.__name__, details)
531
+
532
+ def __repr__(self):
533
+ return "<%s at %s>" % (self.__str__(), id(self))
534
+
535
+ def __eq__(self, other):
536
+ # Test for equality with another WindosService object based
537
+ # on name.
538
+ if not isinstance(other, WindowsService):
539
+ return NotImplemented
540
+ return self._name == other._name
541
+
542
+ def __ne__(self, other):
543
+ return not self == other
544
+
545
+ def _query_config(self):
546
+ with self._wrap_exceptions():
547
+ display_name, binpath, username, start_type = (
548
+ cext.winservice_query_config(self._name)
549
+ )
550
+ # XXX - update _self.display_name?
551
+ return dict(
552
+ display_name=py2_strencode(display_name),
553
+ binpath=py2_strencode(binpath),
554
+ username=py2_strencode(username),
555
+ start_type=py2_strencode(start_type),
556
+ )
557
+
558
+ def _query_status(self):
559
+ with self._wrap_exceptions():
560
+ status, pid = cext.winservice_query_status(self._name)
561
+ if pid == 0:
562
+ pid = None
563
+ return dict(status=status, pid=pid)
564
+
565
+ @contextlib.contextmanager
566
+ def _wrap_exceptions(self):
567
+ """Ctx manager which translates bare OSError and WindowsError
568
+ exceptions into NoSuchProcess and AccessDenied.
569
+ """
570
+ try:
571
+ yield
572
+ except OSError as err:
573
+ if is_permission_err(err):
574
+ msg = (
575
+ "service %r is not querable (not enough privileges)"
576
+ % self._name
577
+ )
578
+ raise AccessDenied(pid=None, name=self._name, msg=msg)
579
+ elif err.winerror in (
580
+ cext.ERROR_INVALID_NAME,
581
+ cext.ERROR_SERVICE_DOES_NOT_EXIST,
582
+ ):
583
+ msg = "service %r does not exist" % self._name
584
+ raise NoSuchProcess(pid=None, name=self._name, msg=msg)
585
+ else:
586
+ raise
587
+
588
+ # config query
589
+
590
+ def name(self):
591
+ """The service name. This string is how a service is referenced
592
+ and can be passed to win_service_get() to get a new
593
+ WindowsService instance.
594
+ """
595
+ return self._name
596
+
597
+ def display_name(self):
598
+ """The service display name. The value is cached when this class
599
+ is instantiated.
600
+ """
601
+ return self._display_name
602
+
603
+ def binpath(self):
604
+ """The fully qualified path to the service binary/exe file as
605
+ a string, including command line arguments.
606
+ """
607
+ return self._query_config()['binpath']
608
+
609
+ def username(self):
610
+ """The name of the user that owns this service."""
611
+ return self._query_config()['username']
612
+
613
+ def start_type(self):
614
+ """A string which can either be "automatic", "manual" or
615
+ "disabled".
616
+ """
617
+ return self._query_config()['start_type']
618
+
619
+ # status query
620
+
621
+ def pid(self):
622
+ """The process PID, if any, else None. This can be passed
623
+ to Process class to control the service's process.
624
+ """
625
+ return self._query_status()['pid']
626
+
627
+ def status(self):
628
+ """Service status as a string."""
629
+ return self._query_status()['status']
630
+
631
+ def description(self):
632
+ """Service long description."""
633
+ return py2_strencode(cext.winservice_query_descr(self.name()))
634
+
635
+ # utils
636
+
637
+ def as_dict(self):
638
+ """Utility method retrieving all the information above as a
639
+ dictionary.
640
+ """
641
+ d = self._query_config()
642
+ d.update(self._query_status())
643
+ d['name'] = self.name()
644
+ d['display_name'] = self.display_name()
645
+ d['description'] = self.description()
646
+ return d
647
+
648
+ # actions
649
+ # XXX: the necessary C bindings for start() and stop() are
650
+ # implemented but for now I prefer not to expose them.
651
+ # I may change my mind in the future. Reasons:
652
+ # - they require Administrator privileges
653
+ # - can't implement a timeout for stop() (unless by using a thread,
654
+ # which sucks)
655
+ # - would require adding ServiceAlreadyStarted and
656
+ # ServiceAlreadyStopped exceptions, adding two new APIs.
657
+ # - we might also want to have modify(), which would basically mean
658
+ # rewriting win32serviceutil.ChangeServiceConfig, which involves a
659
+ # lot of stuff (and API constants which would pollute the API), see:
660
+ # http://pyxr.sourceforge.net/PyXR/c/python24/lib/site-packages/
661
+ # win32/lib/win32serviceutil.py.html#0175
662
+ # - psutil is typically about "read only" monitoring stuff;
663
+ # win_service_* APIs should only be used to retrieve a service and
664
+ # check whether it's running
665
+
666
+ # def start(self, timeout=None):
667
+ # with self._wrap_exceptions():
668
+ # cext.winservice_start(self.name())
669
+ # if timeout:
670
+ # giveup_at = time.time() + timeout
671
+ # while True:
672
+ # if self.status() == "running":
673
+ # return
674
+ # else:
675
+ # if time.time() > giveup_at:
676
+ # raise TimeoutExpired(timeout)
677
+ # else:
678
+ # time.sleep(.1)
679
+
680
+ # def stop(self):
681
+ # # Note: timeout is not implemented because it's just not
682
+ # # possible, see:
683
+ # # http://stackoverflow.com/questions/11973228/
684
+ # with self._wrap_exceptions():
685
+ # return cext.winservice_stop(self.name())
686
+
687
+
688
+ # =====================================================================
689
+ # --- processes
690
+ # =====================================================================
691
+
692
+
693
+ pids = cext.pids
694
+ pid_exists = cext.pid_exists
695
+ ppid_map = cext.ppid_map # used internally by Process.children()
696
+
697
+
698
+ def is_permission_err(exc):
699
+ """Return True if this is a permission error."""
700
+ assert isinstance(exc, OSError), exc
701
+ if exc.errno in (errno.EPERM, errno.EACCES):
702
+ return True
703
+ # On Python 2 OSError doesn't always have 'winerror'. Sometimes
704
+ # it does, in which case the original exception was WindowsError
705
+ # (which is a subclass of OSError).
706
+ if getattr(exc, "winerror", -1) in (
707
+ cext.ERROR_ACCESS_DENIED,
708
+ cext.ERROR_PRIVILEGE_NOT_HELD,
709
+ ):
710
+ return True
711
+ return False
712
+
713
+
714
+ def convert_oserror(exc, pid=None, name=None):
715
+ """Convert OSError into NoSuchProcess or AccessDenied."""
716
+ assert isinstance(exc, OSError), exc
717
+ if is_permission_err(exc):
718
+ return AccessDenied(pid=pid, name=name)
719
+ if exc.errno == errno.ESRCH:
720
+ return NoSuchProcess(pid=pid, name=name)
721
+ raise exc
722
+
723
+
724
+ def wrap_exceptions(fun):
725
+ """Decorator which converts OSError into NoSuchProcess or AccessDenied."""
726
+
727
+ @functools.wraps(fun)
728
+ def wrapper(self, *args, **kwargs):
729
+ try:
730
+ return fun(self, *args, **kwargs)
731
+ except OSError as err:
732
+ raise convert_oserror(err, pid=self.pid, name=self._name)
733
+
734
+ return wrapper
735
+
736
+
737
+ def retry_error_partial_copy(fun):
738
+ """Workaround for https://github.com/giampaolo/psutil/issues/875.
739
+ See: https://stackoverflow.com/questions/4457745#4457745.
740
+ """
741
+
742
+ @functools.wraps(fun)
743
+ def wrapper(self, *args, **kwargs):
744
+ delay = 0.0001
745
+ times = 33
746
+ for _ in range(times): # retries for roughly 1 second
747
+ try:
748
+ return fun(self, *args, **kwargs)
749
+ except WindowsError as _:
750
+ err = _
751
+ if err.winerror == ERROR_PARTIAL_COPY:
752
+ time.sleep(delay)
753
+ delay = min(delay * 2, 0.04)
754
+ continue
755
+ raise
756
+ msg = (
757
+ "{} retried {} times, converted to AccessDenied as it's still"
758
+ "returning {}".format(fun, times, err)
759
+ )
760
+ raise AccessDenied(pid=self.pid, name=self._name, msg=msg)
761
+
762
+ return wrapper
763
+
764
+
765
+ class Process:
766
+ """Wrapper class around underlying C implementation."""
767
+
768
+ __slots__ = ["pid", "_name", "_ppid", "_cache"]
769
+
770
+ def __init__(self, pid):
771
+ self.pid = pid
772
+ self._name = None
773
+ self._ppid = None
774
+
775
+ # --- oneshot() stuff
776
+
777
+ def oneshot_enter(self):
778
+ self._proc_info.cache_activate(self)
779
+ self.exe.cache_activate(self)
780
+
781
+ def oneshot_exit(self):
782
+ self._proc_info.cache_deactivate(self)
783
+ self.exe.cache_deactivate(self)
784
+
785
+ @memoize_when_activated
786
+ def _proc_info(self):
787
+ """Return multiple information about this process as a
788
+ raw tuple.
789
+ """
790
+ ret = cext.proc_info(self.pid)
791
+ assert len(ret) == len(pinfo_map)
792
+ return ret
793
+
794
+ def name(self):
795
+ """Return process name, which on Windows is always the final
796
+ part of the executable.
797
+ """
798
+ # This is how PIDs 0 and 4 are always represented in taskmgr
799
+ # and process-hacker.
800
+ if self.pid == 0:
801
+ return "System Idle Process"
802
+ if self.pid == 4:
803
+ return "System"
804
+ return os.path.basename(self.exe())
805
+
806
+ @wrap_exceptions
807
+ @memoize_when_activated
808
+ def exe(self):
809
+ if PYPY:
810
+ try:
811
+ exe = cext.proc_exe(self.pid)
812
+ except WindowsError as err:
813
+ # 24 = ERROR_TOO_MANY_OPEN_FILES. Not sure why this happens
814
+ # (perhaps PyPy's JIT delaying garbage collection of files?).
815
+ if err.errno == 24:
816
+ debug("%r translated into AccessDenied" % err)
817
+ raise AccessDenied(self.pid, self._name)
818
+ raise
819
+ else:
820
+ exe = cext.proc_exe(self.pid)
821
+ if not PY3:
822
+ exe = py2_strencode(exe)
823
+ if exe.startswith('\\'):
824
+ return convert_dos_path(exe)
825
+ return exe # May be "Registry", "MemCompression", ...
826
+
827
+ @wrap_exceptions
828
+ @retry_error_partial_copy
829
+ def cmdline(self):
830
+ if cext.WINVER >= cext.WINDOWS_8_1:
831
+ # PEB method detects cmdline changes but requires more
832
+ # privileges: https://github.com/giampaolo/psutil/pull/1398
833
+ try:
834
+ ret = cext.proc_cmdline(self.pid, use_peb=True)
835
+ except OSError as err:
836
+ if is_permission_err(err):
837
+ ret = cext.proc_cmdline(self.pid, use_peb=False)
838
+ else:
839
+ raise
840
+ else:
841
+ ret = cext.proc_cmdline(self.pid, use_peb=True)
842
+ if PY3:
843
+ return ret
844
+ else:
845
+ return [py2_strencode(s) for s in ret]
846
+
847
+ @wrap_exceptions
848
+ @retry_error_partial_copy
849
+ def environ(self):
850
+ ustr = cext.proc_environ(self.pid)
851
+ if ustr and not PY3:
852
+ assert isinstance(ustr, unicode), type(ustr)
853
+ return parse_environ_block(py2_strencode(ustr))
854
+
855
+ def ppid(self):
856
+ try:
857
+ return ppid_map()[self.pid]
858
+ except KeyError:
859
+ raise NoSuchProcess(self.pid, self._name)
860
+
861
+ def _get_raw_meminfo(self):
862
+ try:
863
+ return cext.proc_memory_info(self.pid)
864
+ except OSError as err:
865
+ if is_permission_err(err):
866
+ # TODO: the C ext can probably be refactored in order
867
+ # to get this from cext.proc_info()
868
+ info = self._proc_info()
869
+ return (
870
+ info[pinfo_map['num_page_faults']],
871
+ info[pinfo_map['peak_wset']],
872
+ info[pinfo_map['wset']],
873
+ info[pinfo_map['peak_paged_pool']],
874
+ info[pinfo_map['paged_pool']],
875
+ info[pinfo_map['peak_non_paged_pool']],
876
+ info[pinfo_map['non_paged_pool']],
877
+ info[pinfo_map['pagefile']],
878
+ info[pinfo_map['peak_pagefile']],
879
+ info[pinfo_map['mem_private']],
880
+ )
881
+ raise
882
+
883
+ @wrap_exceptions
884
+ def memory_info(self):
885
+ # on Windows RSS == WorkingSetSize and VSM == PagefileUsage.
886
+ # Underlying C function returns fields of PROCESS_MEMORY_COUNTERS
887
+ # struct.
888
+ t = self._get_raw_meminfo()
889
+ rss = t[2] # wset
890
+ vms = t[7] # pagefile
891
+ return pmem(*(rss, vms) + t)
892
+
893
+ @wrap_exceptions
894
+ def memory_full_info(self):
895
+ basic_mem = self.memory_info()
896
+ uss = cext.proc_memory_uss(self.pid)
897
+ uss *= getpagesize()
898
+ return pfullmem(*basic_mem + (uss,))
899
+
900
+ def memory_maps(self):
901
+ try:
902
+ raw = cext.proc_memory_maps(self.pid)
903
+ except OSError as err:
904
+ # XXX - can't use wrap_exceptions decorator as we're
905
+ # returning a generator; probably needs refactoring.
906
+ raise convert_oserror(err, self.pid, self._name)
907
+ else:
908
+ for addr, perm, path, rss in raw:
909
+ path = convert_dos_path(path)
910
+ if not PY3:
911
+ path = py2_strencode(path)
912
+ addr = hex(addr)
913
+ yield (addr, perm, path, rss)
914
+
915
+ @wrap_exceptions
916
+ def kill(self):
917
+ return cext.proc_kill(self.pid)
918
+
919
+ @wrap_exceptions
920
+ def send_signal(self, sig):
921
+ if sig == signal.SIGTERM:
922
+ cext.proc_kill(self.pid)
923
+ # py >= 2.7
924
+ elif sig in (
925
+ getattr(signal, "CTRL_C_EVENT", object()),
926
+ getattr(signal, "CTRL_BREAK_EVENT", object()),
927
+ ):
928
+ os.kill(self.pid, sig)
929
+ else:
930
+ msg = (
931
+ "only SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals "
932
+ "are supported on Windows"
933
+ )
934
+ raise ValueError(msg)
935
+
936
+ @wrap_exceptions
937
+ def wait(self, timeout=None):
938
+ if timeout is None:
939
+ cext_timeout = cext.INFINITE
940
+ else:
941
+ # WaitForSingleObject() expects time in milliseconds.
942
+ cext_timeout = int(timeout * 1000)
943
+
944
+ timer = getattr(time, 'monotonic', time.time)
945
+ stop_at = timer() + timeout if timeout is not None else None
946
+
947
+ try:
948
+ # Exit code is supposed to come from GetExitCodeProcess().
949
+ # May also be None if OpenProcess() failed with
950
+ # ERROR_INVALID_PARAMETER, meaning PID is already gone.
951
+ exit_code = cext.proc_wait(self.pid, cext_timeout)
952
+ except cext.TimeoutExpired:
953
+ # WaitForSingleObject() returned WAIT_TIMEOUT. Just raise.
954
+ raise TimeoutExpired(timeout, self.pid, self._name)
955
+ except cext.TimeoutAbandoned:
956
+ # WaitForSingleObject() returned WAIT_ABANDONED, see:
957
+ # https://github.com/giampaolo/psutil/issues/1224
958
+ # We'll just rely on the internal polling and return None
959
+ # when the PID disappears. Subprocess module does the same
960
+ # (return None):
961
+ # https://github.com/python/cpython/blob/
962
+ # be50a7b627d0aa37e08fa8e2d5568891f19903ce/
963
+ # Lib/subprocess.py#L1193-L1194
964
+ exit_code = None
965
+
966
+ # At this point WaitForSingleObject() returned WAIT_OBJECT_0,
967
+ # meaning the process is gone. Stupidly there are cases where
968
+ # its PID may still stick around so we do a further internal
969
+ # polling.
970
+ delay = 0.0001
971
+ while True:
972
+ if not pid_exists(self.pid):
973
+ return exit_code
974
+ if stop_at and timer() >= stop_at:
975
+ raise TimeoutExpired(timeout, pid=self.pid, name=self._name)
976
+ time.sleep(delay)
977
+ delay = min(delay * 2, 0.04) # incremental delay
978
+
979
+ @wrap_exceptions
980
+ def username(self):
981
+ if self.pid in (0, 4):
982
+ return 'NT AUTHORITY\\SYSTEM'
983
+ domain, user = cext.proc_username(self.pid)
984
+ return py2_strencode(domain) + '\\' + py2_strencode(user)
985
+
986
+ @wrap_exceptions
987
+ def create_time(self):
988
+ # Note: proc_times() not put under oneshot() 'cause create_time()
989
+ # is already cached by the main Process class.
990
+ try:
991
+ user, system, created = cext.proc_times(self.pid)
992
+ return created
993
+ except OSError as err:
994
+ if is_permission_err(err):
995
+ return self._proc_info()[pinfo_map['create_time']]
996
+ raise
997
+
998
+ @wrap_exceptions
999
+ def num_threads(self):
1000
+ return self._proc_info()[pinfo_map['num_threads']]
1001
+
1002
+ @wrap_exceptions
1003
+ def threads(self):
1004
+ rawlist = cext.proc_threads(self.pid)
1005
+ retlist = []
1006
+ for thread_id, utime, stime in rawlist:
1007
+ ntuple = _common.pthread(thread_id, utime, stime)
1008
+ retlist.append(ntuple)
1009
+ return retlist
1010
+
1011
+ @wrap_exceptions
1012
+ def cpu_times(self):
1013
+ try:
1014
+ user, system, created = cext.proc_times(self.pid)
1015
+ except OSError as err:
1016
+ if not is_permission_err(err):
1017
+ raise
1018
+ info = self._proc_info()
1019
+ user = info[pinfo_map['user_time']]
1020
+ system = info[pinfo_map['kernel_time']]
1021
+ # Children user/system times are not retrievable (set to 0).
1022
+ return _common.pcputimes(user, system, 0.0, 0.0)
1023
+
1024
+ @wrap_exceptions
1025
+ def suspend(self):
1026
+ cext.proc_suspend_or_resume(self.pid, True)
1027
+
1028
+ @wrap_exceptions
1029
+ def resume(self):
1030
+ cext.proc_suspend_or_resume(self.pid, False)
1031
+
1032
+ @wrap_exceptions
1033
+ @retry_error_partial_copy
1034
+ def cwd(self):
1035
+ if self.pid in (0, 4):
1036
+ raise AccessDenied(self.pid, self._name)
1037
+ # return a normalized pathname since the native C function appends
1038
+ # "\\" at the and of the path
1039
+ path = cext.proc_cwd(self.pid)
1040
+ return py2_strencode(os.path.normpath(path))
1041
+
1042
+ @wrap_exceptions
1043
+ def open_files(self):
1044
+ if self.pid in (0, 4):
1045
+ return []
1046
+ ret = set()
1047
+ # Filenames come in in native format like:
1048
+ # "\Device\HarddiskVolume1\Windows\systemew\file.txt"
1049
+ # Convert the first part in the corresponding drive letter
1050
+ # (e.g. "C:\") by using Windows's QueryDosDevice()
1051
+ raw_file_names = cext.proc_open_files(self.pid)
1052
+ for _file in raw_file_names:
1053
+ _file = convert_dos_path(_file)
1054
+ if isfile_strict(_file):
1055
+ if not PY3:
1056
+ _file = py2_strencode(_file)
1057
+ ntuple = _common.popenfile(_file, -1)
1058
+ ret.add(ntuple)
1059
+ return list(ret)
1060
+
1061
+ @wrap_exceptions
1062
+ def connections(self, kind='inet'):
1063
+ return net_connections(kind, _pid=self.pid)
1064
+
1065
+ @wrap_exceptions
1066
+ def nice_get(self):
1067
+ value = cext.proc_priority_get(self.pid)
1068
+ if enum is not None:
1069
+ value = Priority(value)
1070
+ return value
1071
+
1072
+ @wrap_exceptions
1073
+ def nice_set(self, value):
1074
+ return cext.proc_priority_set(self.pid, value)
1075
+
1076
+ @wrap_exceptions
1077
+ def ionice_get(self):
1078
+ ret = cext.proc_io_priority_get(self.pid)
1079
+ if enum is not None:
1080
+ ret = IOPriority(ret)
1081
+ return ret
1082
+
1083
+ @wrap_exceptions
1084
+ def ionice_set(self, ioclass, value):
1085
+ if value:
1086
+ msg = "value argument not accepted on Windows"
1087
+ raise TypeError(msg)
1088
+ if ioclass not in (
1089
+ IOPRIO_VERYLOW,
1090
+ IOPRIO_LOW,
1091
+ IOPRIO_NORMAL,
1092
+ IOPRIO_HIGH,
1093
+ ):
1094
+ raise ValueError("%s is not a valid priority" % ioclass)
1095
+ cext.proc_io_priority_set(self.pid, ioclass)
1096
+
1097
+ @wrap_exceptions
1098
+ def io_counters(self):
1099
+ try:
1100
+ ret = cext.proc_io_counters(self.pid)
1101
+ except OSError as err:
1102
+ if not is_permission_err(err):
1103
+ raise
1104
+ info = self._proc_info()
1105
+ ret = (
1106
+ info[pinfo_map['io_rcount']],
1107
+ info[pinfo_map['io_wcount']],
1108
+ info[pinfo_map['io_rbytes']],
1109
+ info[pinfo_map['io_wbytes']],
1110
+ info[pinfo_map['io_count_others']],
1111
+ info[pinfo_map['io_bytes_others']],
1112
+ )
1113
+ return pio(*ret)
1114
+
1115
+ @wrap_exceptions
1116
+ def status(self):
1117
+ suspended = cext.proc_is_suspended(self.pid)
1118
+ if suspended:
1119
+ return _common.STATUS_STOPPED
1120
+ else:
1121
+ return _common.STATUS_RUNNING
1122
+
1123
+ @wrap_exceptions
1124
+ def cpu_affinity_get(self):
1125
+ def from_bitmask(x):
1126
+ return [i for i in range(64) if (1 << i) & x]
1127
+
1128
+ bitmask = cext.proc_cpu_affinity_get(self.pid)
1129
+ return from_bitmask(bitmask)
1130
+
1131
+ @wrap_exceptions
1132
+ def cpu_affinity_set(self, value):
1133
+ def to_bitmask(ls):
1134
+ if not ls:
1135
+ raise ValueError("invalid argument %r" % ls)
1136
+ out = 0
1137
+ for b in ls:
1138
+ out |= 2**b
1139
+ return out
1140
+
1141
+ # SetProcessAffinityMask() states that ERROR_INVALID_PARAMETER
1142
+ # is returned for an invalid CPU but this seems not to be true,
1143
+ # therefore we check CPUs validy beforehand.
1144
+ allcpus = list(range(len(per_cpu_times())))
1145
+ for cpu in value:
1146
+ if cpu not in allcpus:
1147
+ if not isinstance(cpu, (int, long)):
1148
+ raise TypeError(
1149
+ "invalid CPU %r; an integer is required" % cpu
1150
+ )
1151
+ else:
1152
+ raise ValueError("invalid CPU %r" % cpu)
1153
+
1154
+ bitmask = to_bitmask(value)
1155
+ cext.proc_cpu_affinity_set(self.pid, bitmask)
1156
+
1157
+ @wrap_exceptions
1158
+ def num_handles(self):
1159
+ try:
1160
+ return cext.proc_num_handles(self.pid)
1161
+ except OSError as err:
1162
+ if is_permission_err(err):
1163
+ return self._proc_info()[pinfo_map['num_handles']]
1164
+ raise
1165
+
1166
+ @wrap_exceptions
1167
+ def num_ctx_switches(self):
1168
+ ctx_switches = self._proc_info()[pinfo_map['ctx_switches']]
1169
+ # only voluntary ctx switches are supported
1170
+ return _common.pctxsw(ctx_switches, 0)
llmeval-env/lib/python3.10/site-packages/psutil/tests/__init__.py ADDED
@@ -0,0 +1,2043 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
+ # Use of this source code is governed by a BSD-style license that can be
5
+ # found in the LICENSE file.
6
+
7
+ """Test utilities."""
8
+
9
+ from __future__ import print_function
10
+
11
+ import atexit
12
+ import contextlib
13
+ import ctypes
14
+ import errno
15
+ import functools
16
+ import gc
17
+ import inspect
18
+ import os
19
+ import platform
20
+ import random
21
+ import re
22
+ import select
23
+ import shlex
24
+ import shutil
25
+ import signal
26
+ import socket
27
+ import stat
28
+ import subprocess
29
+ import sys
30
+ import tempfile
31
+ import textwrap
32
+ import threading
33
+ import time
34
+ import unittest
35
+ import warnings
36
+ from socket import AF_INET
37
+ from socket import AF_INET6
38
+ from socket import SOCK_STREAM
39
+
40
+ import psutil
41
+ from psutil import AIX
42
+ from psutil import LINUX
43
+ from psutil import MACOS
44
+ from psutil import NETBSD
45
+ from psutil import OPENBSD
46
+ from psutil import POSIX
47
+ from psutil import SUNOS
48
+ from psutil import WINDOWS
49
+ from psutil._common import bytes2human
50
+ from psutil._common import debug
51
+ from psutil._common import memoize
52
+ from psutil._common import print_color
53
+ from psutil._common import supports_ipv6
54
+ from psutil._compat import PY3
55
+ from psutil._compat import FileExistsError
56
+ from psutil._compat import FileNotFoundError
57
+ from psutil._compat import range
58
+ from psutil._compat import super
59
+ from psutil._compat import u
60
+ from psutil._compat import unicode
61
+ from psutil._compat import which
62
+
63
+
64
+ try:
65
+ from unittest import mock # py3
66
+ except ImportError:
67
+ with warnings.catch_warnings():
68
+ warnings.simplefilter("ignore")
69
+ import mock # NOQA - requires "pip install mock"
70
+
71
+ if PY3:
72
+ import enum
73
+ else:
74
+ enum = None
75
+
76
+ if POSIX:
77
+ from psutil._psposix import wait_pid
78
+
79
+
80
+ # fmt: off
81
+ __all__ = [
82
+ # constants
83
+ 'APPVEYOR', 'DEVNULL', 'GLOBAL_TIMEOUT', 'TOLERANCE_SYS_MEM', 'NO_RETRIES',
84
+ 'PYPY', 'PYTHON_EXE', 'PYTHON_EXE_ENV', 'ROOT_DIR', 'SCRIPTS_DIR',
85
+ 'TESTFN_PREFIX', 'UNICODE_SUFFIX', 'INVALID_UNICODE_SUFFIX',
86
+ 'CI_TESTING', 'VALID_PROC_STATUSES', 'TOLERANCE_DISK_USAGE', 'IS_64BIT',
87
+ "HAS_CPU_AFFINITY", "HAS_CPU_FREQ", "HAS_ENVIRON", "HAS_PROC_IO_COUNTERS",
88
+ "HAS_IONICE", "HAS_MEMORY_MAPS", "HAS_PROC_CPU_NUM", "HAS_RLIMIT",
89
+ "HAS_SENSORS_BATTERY", "HAS_BATTERY", "HAS_SENSORS_FANS",
90
+ "HAS_SENSORS_TEMPERATURES", "MACOS_11PLUS",
91
+ "MACOS_12PLUS", "COVERAGE",
92
+ # subprocesses
93
+ 'pyrun', 'terminate', 'reap_children', 'spawn_testproc', 'spawn_zombie',
94
+ 'spawn_children_pair',
95
+ # threads
96
+ 'ThreadTask',
97
+ # test utils
98
+ 'unittest', 'skip_on_access_denied', 'skip_on_not_implemented',
99
+ 'retry_on_failure', 'TestMemoryLeak', 'PsutilTestCase',
100
+ 'process_namespace', 'system_namespace', 'print_sysinfo',
101
+ 'is_win_secure_system_proc',
102
+ # fs utils
103
+ 'chdir', 'safe_rmpath', 'create_py_exe', 'create_c_exe', 'get_testfn',
104
+ # os
105
+ 'get_winver', 'kernel_version',
106
+ # sync primitives
107
+ 'call_until', 'wait_for_pid', 'wait_for_file',
108
+ # network
109
+ 'check_net_address', 'filter_proc_connections',
110
+ 'get_free_port', 'bind_socket', 'bind_unix_socket', 'tcp_socketpair',
111
+ 'unix_socketpair', 'create_sockets',
112
+ # compat
113
+ 'reload_module', 'import_module_by_path',
114
+ # others
115
+ 'warn', 'copyload_shared_lib', 'is_namedtuple',
116
+ ]
117
+ # fmt: on
118
+
119
+
120
+ # ===================================================================
121
+ # --- constants
122
+ # ===================================================================
123
+
124
+ # --- platforms
125
+
126
+ PYPY = '__pypy__' in sys.builtin_module_names
127
+ # whether we're running this test suite on a Continuous Integration service
128
+ APPVEYOR = 'APPVEYOR' in os.environ
129
+ GITHUB_ACTIONS = 'GITHUB_ACTIONS' in os.environ or 'CIBUILDWHEEL' in os.environ
130
+ CI_TESTING = APPVEYOR or GITHUB_ACTIONS
131
+ COVERAGE = 'COVERAGE_RUN' in os.environ
132
+ # are we a 64 bit process?
133
+ IS_64BIT = sys.maxsize > 2**32
134
+
135
+
136
+ @memoize
137
+ def macos_version():
138
+ version_str = platform.mac_ver()[0]
139
+ version = tuple(map(int, version_str.split(".")[:2]))
140
+ if version == (10, 16):
141
+ # When built against an older macOS SDK, Python will report
142
+ # macOS 10.16 instead of the real version.
143
+ version_str = subprocess.check_output(
144
+ [
145
+ sys.executable,
146
+ "-sS",
147
+ "-c",
148
+ "import platform; print(platform.mac_ver()[0])",
149
+ ],
150
+ env={"SYSTEM_VERSION_COMPAT": "0"},
151
+ universal_newlines=True,
152
+ )
153
+ version = tuple(map(int, version_str.split(".")[:2]))
154
+ return version
155
+
156
+
157
+ if MACOS:
158
+ MACOS_11PLUS = macos_version() > (10, 15)
159
+ MACOS_12PLUS = macos_version() >= (12, 0)
160
+ else:
161
+ MACOS_11PLUS = False
162
+ MACOS_12PLUS = False
163
+
164
+
165
+ # --- configurable defaults
166
+
167
+ # how many times retry_on_failure() decorator will retry
168
+ NO_RETRIES = 10
169
+ # bytes tolerance for system-wide related tests
170
+ TOLERANCE_SYS_MEM = 5 * 1024 * 1024 # 5MB
171
+ TOLERANCE_DISK_USAGE = 10 * 1024 * 1024 # 10MB
172
+ # the timeout used in functions which have to wait
173
+ GLOBAL_TIMEOUT = 5
174
+ # be more tolerant if we're on CI in order to avoid false positives
175
+ if CI_TESTING:
176
+ NO_RETRIES *= 3
177
+ GLOBAL_TIMEOUT *= 3
178
+ TOLERANCE_SYS_MEM *= 4
179
+ TOLERANCE_DISK_USAGE *= 3
180
+
181
+ # --- file names
182
+
183
+ # Disambiguate TESTFN for parallel testing.
184
+ if os.name == 'java':
185
+ # Jython disallows @ in module names
186
+ TESTFN_PREFIX = '$psutil-%s-' % os.getpid()
187
+ else:
188
+ TESTFN_PREFIX = '@psutil-%s-' % os.getpid()
189
+ UNICODE_SUFFIX = u("-ƒőő")
190
+ # An invalid unicode string.
191
+ if PY3:
192
+ INVALID_UNICODE_SUFFIX = b"f\xc0\x80".decode('utf8', 'surrogateescape')
193
+ else:
194
+ INVALID_UNICODE_SUFFIX = "f\xc0\x80"
195
+ ASCII_FS = sys.getfilesystemencoding().lower() in ('ascii', 'us-ascii')
196
+
197
+ # --- paths
198
+
199
+ ROOT_DIR = os.path.realpath(
200
+ os.path.join(os.path.dirname(__file__), '..', '..')
201
+ )
202
+ SCRIPTS_DIR = os.environ.get(
203
+ "PSUTIL_SCRIPTS_DIR", os.path.join(ROOT_DIR, 'scripts')
204
+ )
205
+ HERE = os.path.realpath(os.path.dirname(__file__))
206
+
207
+ # --- support
208
+
209
+ HAS_CONNECTIONS_UNIX = POSIX and not SUNOS
210
+ HAS_CPU_AFFINITY = hasattr(psutil.Process, "cpu_affinity")
211
+ HAS_CPU_FREQ = hasattr(psutil, "cpu_freq")
212
+ HAS_GETLOADAVG = hasattr(psutil, "getloadavg")
213
+ HAS_ENVIRON = hasattr(psutil.Process, "environ")
214
+ HAS_IONICE = hasattr(psutil.Process, "ionice")
215
+ HAS_MEMORY_MAPS = hasattr(psutil.Process, "memory_maps")
216
+ HAS_NET_IO_COUNTERS = hasattr(psutil, "net_io_counters")
217
+ HAS_PROC_CPU_NUM = hasattr(psutil.Process, "cpu_num")
218
+ HAS_PROC_IO_COUNTERS = hasattr(psutil.Process, "io_counters")
219
+ HAS_RLIMIT = hasattr(psutil.Process, "rlimit")
220
+ HAS_SENSORS_BATTERY = hasattr(psutil, "sensors_battery")
221
+ try:
222
+ HAS_BATTERY = HAS_SENSORS_BATTERY and bool(psutil.sensors_battery())
223
+ except Exception: # noqa: BLE001
224
+ HAS_BATTERY = False
225
+ HAS_SENSORS_FANS = hasattr(psutil, "sensors_fans")
226
+ HAS_SENSORS_TEMPERATURES = hasattr(psutil, "sensors_temperatures")
227
+ HAS_THREADS = hasattr(psutil.Process, "threads")
228
+ SKIP_SYSCONS = (MACOS or AIX) and os.getuid() != 0
229
+
230
+ # --- misc
231
+
232
+
233
+ def _get_py_exe():
234
+ def attempt(exe):
235
+ try:
236
+ subprocess.check_call(
237
+ [exe, "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
238
+ )
239
+ except subprocess.CalledProcessError:
240
+ return None
241
+ else:
242
+ return exe
243
+
244
+ env = os.environ.copy()
245
+
246
+ # On Windows, starting with python 3.7, virtual environments use a
247
+ # venv launcher startup process. This does not play well when
248
+ # counting spawned processes, or when relying on the PID of the
249
+ # spawned process to do some checks, e.g. connections check per PID.
250
+ # Let's use the base python in this case.
251
+ base = getattr(sys, "_base_executable", None)
252
+ if WINDOWS and sys.version_info >= (3, 7) and base is not None:
253
+ # We need to set __PYVENV_LAUNCHER__ to sys.executable for the
254
+ # base python executable to know about the environment.
255
+ env["__PYVENV_LAUNCHER__"] = sys.executable
256
+ return base, env
257
+ elif GITHUB_ACTIONS:
258
+ return sys.executable, env
259
+ elif MACOS:
260
+ exe = (
261
+ attempt(sys.executable)
262
+ or attempt(os.path.realpath(sys.executable))
263
+ or attempt(which("python%s.%s" % sys.version_info[:2]))
264
+ or attempt(psutil.Process().exe())
265
+ )
266
+ if not exe:
267
+ raise ValueError("can't find python exe real abspath")
268
+ return exe, env
269
+ else:
270
+ exe = os.path.realpath(sys.executable)
271
+ assert os.path.exists(exe), exe
272
+ return exe, env
273
+
274
+
275
+ PYTHON_EXE, PYTHON_EXE_ENV = _get_py_exe()
276
+ DEVNULL = open(os.devnull, 'r+')
277
+ atexit.register(DEVNULL.close)
278
+
279
+ VALID_PROC_STATUSES = [
280
+ getattr(psutil, x) for x in dir(psutil) if x.startswith('STATUS_')
281
+ ]
282
+ AF_UNIX = getattr(socket, "AF_UNIX", object())
283
+
284
+ _subprocesses_started = set()
285
+ _pids_started = set()
286
+
287
+
288
+ # ===================================================================
289
+ # --- threads
290
+ # ===================================================================
291
+
292
+
293
+ class ThreadTask(threading.Thread):
294
+ """A thread task which does nothing expect staying alive."""
295
+
296
+ def __init__(self):
297
+ super().__init__()
298
+ self._running = False
299
+ self._interval = 0.001
300
+ self._flag = threading.Event()
301
+
302
+ def __repr__(self):
303
+ name = self.__class__.__name__
304
+ return '<%s running=%s at %#x>' % (name, self._running, id(self))
305
+
306
+ def __enter__(self):
307
+ self.start()
308
+ return self
309
+
310
+ def __exit__(self, *args, **kwargs):
311
+ self.stop()
312
+
313
+ def start(self):
314
+ """Start thread and keep it running until an explicit
315
+ stop() request. Polls for shutdown every 'timeout' seconds.
316
+ """
317
+ if self._running:
318
+ raise ValueError("already started")
319
+ threading.Thread.start(self)
320
+ self._flag.wait()
321
+
322
+ def run(self):
323
+ self._running = True
324
+ self._flag.set()
325
+ while self._running:
326
+ time.sleep(self._interval)
327
+
328
+ def stop(self):
329
+ """Stop thread execution and and waits until it is stopped."""
330
+ if not self._running:
331
+ raise ValueError("already stopped")
332
+ self._running = False
333
+ self.join()
334
+
335
+
336
+ # ===================================================================
337
+ # --- subprocesses
338
+ # ===================================================================
339
+
340
+
341
+ def _reap_children_on_err(fun):
342
+ @functools.wraps(fun)
343
+ def wrapper(*args, **kwargs):
344
+ try:
345
+ return fun(*args, **kwargs)
346
+ except Exception:
347
+ reap_children()
348
+ raise
349
+
350
+ return wrapper
351
+
352
+
353
+ @_reap_children_on_err
354
+ def spawn_testproc(cmd=None, **kwds):
355
+ """Create a python subprocess which does nothing for some secs and
356
+ return it as a subprocess.Popen instance.
357
+ If "cmd" is specified that is used instead of python.
358
+ By default stdin and stdout are redirected to /dev/null.
359
+ It also attempts to make sure the process is in a reasonably
360
+ initialized state.
361
+ The process is registered for cleanup on reap_children().
362
+ """
363
+ kwds.setdefault("stdin", DEVNULL)
364
+ kwds.setdefault("stdout", DEVNULL)
365
+ kwds.setdefault("cwd", os.getcwd())
366
+ kwds.setdefault("env", PYTHON_EXE_ENV)
367
+ if WINDOWS:
368
+ # Prevents the subprocess to open error dialogs. This will also
369
+ # cause stderr to be suppressed, which is suboptimal in order
370
+ # to debug broken tests.
371
+ CREATE_NO_WINDOW = 0x8000000
372
+ kwds.setdefault("creationflags", CREATE_NO_WINDOW)
373
+ if cmd is None:
374
+ testfn = get_testfn(dir=os.getcwd())
375
+ try:
376
+ safe_rmpath(testfn)
377
+ pyline = (
378
+ "import time;"
379
+ + "open(r'%s', 'w').close();" % testfn
380
+ + "[time.sleep(0.1) for x in range(100)];" # 10 secs
381
+ )
382
+ cmd = [PYTHON_EXE, "-c", pyline]
383
+ sproc = subprocess.Popen(cmd, **kwds)
384
+ _subprocesses_started.add(sproc)
385
+ wait_for_file(testfn, delete=True, empty=True)
386
+ finally:
387
+ safe_rmpath(testfn)
388
+ else:
389
+ sproc = subprocess.Popen(cmd, **kwds)
390
+ _subprocesses_started.add(sproc)
391
+ wait_for_pid(sproc.pid)
392
+ return sproc
393
+
394
+
395
+ @_reap_children_on_err
396
+ def spawn_children_pair():
397
+ """Create a subprocess which creates another one as in:
398
+ A (us) -> B (child) -> C (grandchild).
399
+ Return a (child, grandchild) tuple.
400
+ The 2 processes are fully initialized and will live for 60 secs
401
+ and are registered for cleanup on reap_children().
402
+ """
403
+ tfile = None
404
+ testfn = get_testfn(dir=os.getcwd())
405
+ try:
406
+ s = textwrap.dedent("""\
407
+ import subprocess, os, sys, time
408
+ s = "import os, time;"
409
+ s += "f = open('%s', 'w');"
410
+ s += "f.write(str(os.getpid()));"
411
+ s += "f.close();"
412
+ s += "time.sleep(60);"
413
+ p = subprocess.Popen([r'%s', '-c', s])
414
+ p.wait()
415
+ """ % (os.path.basename(testfn), PYTHON_EXE))
416
+ # On Windows if we create a subprocess with CREATE_NO_WINDOW flag
417
+ # set (which is the default) a "conhost.exe" extra process will be
418
+ # spawned as a child. We don't want that.
419
+ if WINDOWS:
420
+ subp, tfile = pyrun(s, creationflags=0)
421
+ else:
422
+ subp, tfile = pyrun(s)
423
+ child = psutil.Process(subp.pid)
424
+ grandchild_pid = int(wait_for_file(testfn, delete=True, empty=False))
425
+ _pids_started.add(grandchild_pid)
426
+ grandchild = psutil.Process(grandchild_pid)
427
+ return (child, grandchild)
428
+ finally:
429
+ safe_rmpath(testfn)
430
+ if tfile is not None:
431
+ safe_rmpath(tfile)
432
+
433
+
434
+ def spawn_zombie():
435
+ """Create a zombie process and return a (parent, zombie) process tuple.
436
+ In order to kill the zombie parent must be terminate()d first, then
437
+ zombie must be wait()ed on.
438
+ """
439
+ assert psutil.POSIX
440
+ unix_file = get_testfn()
441
+ src = textwrap.dedent("""\
442
+ import os, sys, time, socket, contextlib
443
+ child_pid = os.fork()
444
+ if child_pid > 0:
445
+ time.sleep(3000)
446
+ else:
447
+ # this is the zombie process
448
+ s = socket.socket(socket.AF_UNIX)
449
+ with contextlib.closing(s):
450
+ s.connect('%s')
451
+ if sys.version_info < (3, ):
452
+ pid = str(os.getpid())
453
+ else:
454
+ pid = bytes(str(os.getpid()), 'ascii')
455
+ s.sendall(pid)
456
+ """ % unix_file)
457
+ tfile = None
458
+ sock = bind_unix_socket(unix_file)
459
+ try:
460
+ sock.settimeout(GLOBAL_TIMEOUT)
461
+ parent, tfile = pyrun(src)
462
+ conn, _ = sock.accept()
463
+ try:
464
+ select.select([conn.fileno()], [], [], GLOBAL_TIMEOUT)
465
+ zpid = int(conn.recv(1024))
466
+ _pids_started.add(zpid)
467
+ zombie = psutil.Process(zpid)
468
+ call_until(zombie.status, "ret == psutil.STATUS_ZOMBIE")
469
+ return (parent, zombie)
470
+ finally:
471
+ conn.close()
472
+ finally:
473
+ sock.close()
474
+ safe_rmpath(unix_file)
475
+ if tfile is not None:
476
+ safe_rmpath(tfile)
477
+
478
+
479
+ @_reap_children_on_err
480
+ def pyrun(src, **kwds):
481
+ """Run python 'src' code string in a separate interpreter.
482
+ Returns a subprocess.Popen instance and the test file where the source
483
+ code was written.
484
+ """
485
+ kwds.setdefault("stdout", None)
486
+ kwds.setdefault("stderr", None)
487
+ srcfile = get_testfn()
488
+ try:
489
+ with open(srcfile, "w") as f:
490
+ f.write(src)
491
+ subp = spawn_testproc([PYTHON_EXE, f.name], **kwds)
492
+ wait_for_pid(subp.pid)
493
+ return (subp, srcfile)
494
+ except Exception:
495
+ safe_rmpath(srcfile)
496
+ raise
497
+
498
+
499
+ @_reap_children_on_err
500
+ def sh(cmd, **kwds):
501
+ """Run cmd in a subprocess and return its output.
502
+ raises RuntimeError on error.
503
+ """
504
+ # Prevents subprocess to open error dialogs in case of error.
505
+ flags = 0x8000000 if WINDOWS else 0
506
+ kwds.setdefault("stdout", subprocess.PIPE)
507
+ kwds.setdefault("stderr", subprocess.PIPE)
508
+ kwds.setdefault("universal_newlines", True)
509
+ kwds.setdefault("creationflags", flags)
510
+ if isinstance(cmd, str):
511
+ cmd = shlex.split(cmd)
512
+ p = subprocess.Popen(cmd, **kwds)
513
+ _subprocesses_started.add(p)
514
+ if PY3:
515
+ stdout, stderr = p.communicate(timeout=GLOBAL_TIMEOUT)
516
+ else:
517
+ stdout, stderr = p.communicate()
518
+ if p.returncode != 0:
519
+ raise RuntimeError(stderr)
520
+ if stderr:
521
+ warn(stderr)
522
+ if stdout.endswith('\n'):
523
+ stdout = stdout[:-1]
524
+ return stdout
525
+
526
+
527
+ def terminate(proc_or_pid, sig=signal.SIGTERM, wait_timeout=GLOBAL_TIMEOUT):
528
+ """Terminate a process and wait() for it.
529
+ Process can be a PID or an instance of psutil.Process(),
530
+ subprocess.Popen() or psutil.Popen().
531
+ If it's a subprocess.Popen() or psutil.Popen() instance also closes
532
+ its stdin / stdout / stderr fds.
533
+ PID is wait()ed even if the process is already gone (kills zombies).
534
+ Does nothing if the process does not exist.
535
+ Return process exit status.
536
+ """
537
+
538
+ def wait(proc, timeout):
539
+ if isinstance(proc, subprocess.Popen) and not PY3:
540
+ proc.wait()
541
+ else:
542
+ proc.wait(timeout)
543
+ if WINDOWS and isinstance(proc, subprocess.Popen):
544
+ # Otherwise PID may still hang around.
545
+ try:
546
+ return psutil.Process(proc.pid).wait(timeout)
547
+ except psutil.NoSuchProcess:
548
+ pass
549
+
550
+ def sendsig(proc, sig):
551
+ # XXX: otherwise the build hangs for some reason.
552
+ if MACOS and GITHUB_ACTIONS:
553
+ sig = signal.SIGKILL
554
+ # If the process received SIGSTOP, SIGCONT is necessary first,
555
+ # otherwise SIGTERM won't work.
556
+ if POSIX and sig != signal.SIGKILL:
557
+ proc.send_signal(signal.SIGCONT)
558
+ proc.send_signal(sig)
559
+
560
+ def term_subprocess_proc(proc, timeout):
561
+ try:
562
+ sendsig(proc, sig)
563
+ except OSError as err:
564
+ if WINDOWS and err.winerror == 6: # "invalid handle"
565
+ pass
566
+ elif err.errno != errno.ESRCH:
567
+ raise
568
+ return wait(proc, timeout)
569
+
570
+ def term_psutil_proc(proc, timeout):
571
+ try:
572
+ sendsig(proc, sig)
573
+ except psutil.NoSuchProcess:
574
+ pass
575
+ return wait(proc, timeout)
576
+
577
+ def term_pid(pid, timeout):
578
+ try:
579
+ proc = psutil.Process(pid)
580
+ except psutil.NoSuchProcess:
581
+ # Needed to kill zombies.
582
+ if POSIX:
583
+ return wait_pid(pid, timeout)
584
+ else:
585
+ return term_psutil_proc(proc, timeout)
586
+
587
+ def flush_popen(proc):
588
+ if proc.stdout:
589
+ proc.stdout.close()
590
+ if proc.stderr:
591
+ proc.stderr.close()
592
+ # Flushing a BufferedWriter may raise an error.
593
+ if proc.stdin:
594
+ proc.stdin.close()
595
+
596
+ p = proc_or_pid
597
+ try:
598
+ if isinstance(p, int):
599
+ return term_pid(p, wait_timeout)
600
+ elif isinstance(p, (psutil.Process, psutil.Popen)):
601
+ return term_psutil_proc(p, wait_timeout)
602
+ elif isinstance(p, subprocess.Popen):
603
+ return term_subprocess_proc(p, wait_timeout)
604
+ else:
605
+ raise TypeError("wrong type %r" % p)
606
+ finally:
607
+ if isinstance(p, (subprocess.Popen, psutil.Popen)):
608
+ flush_popen(p)
609
+ pid = p if isinstance(p, int) else p.pid
610
+ assert not psutil.pid_exists(pid), pid
611
+
612
+
613
+ def reap_children(recursive=False):
614
+ """Terminate and wait() any subprocess started by this test suite
615
+ and any children currently running, ensuring that no processes stick
616
+ around to hog resources.
617
+ If recursive is True it also tries to terminate and wait()
618
+ all grandchildren started by this process.
619
+ """
620
+ # Get the children here before terminating them, as in case of
621
+ # recursive=True we don't want to lose the intermediate reference
622
+ # pointing to the grandchildren.
623
+ children = psutil.Process().children(recursive=recursive)
624
+
625
+ # Terminate subprocess.Popen.
626
+ while _subprocesses_started:
627
+ subp = _subprocesses_started.pop()
628
+ terminate(subp)
629
+
630
+ # Collect started pids.
631
+ while _pids_started:
632
+ pid = _pids_started.pop()
633
+ terminate(pid)
634
+
635
+ # Terminate children.
636
+ if children:
637
+ for p in children:
638
+ terminate(p, wait_timeout=None)
639
+ _, alive = psutil.wait_procs(children, timeout=GLOBAL_TIMEOUT)
640
+ for p in alive:
641
+ warn("couldn't terminate process %r; attempting kill()" % p)
642
+ terminate(p, sig=signal.SIGKILL)
643
+
644
+
645
+ # ===================================================================
646
+ # --- OS
647
+ # ===================================================================
648
+
649
+
650
+ def kernel_version():
651
+ """Return a tuple such as (2, 6, 36)."""
652
+ if not POSIX:
653
+ raise NotImplementedError("not POSIX")
654
+ s = ""
655
+ uname = os.uname()[2]
656
+ for c in uname:
657
+ if c.isdigit() or c == '.':
658
+ s += c
659
+ else:
660
+ break
661
+ if not s:
662
+ raise ValueError("can't parse %r" % uname)
663
+ minor = 0
664
+ micro = 0
665
+ nums = s.split('.')
666
+ major = int(nums[0])
667
+ if len(nums) >= 2:
668
+ minor = int(nums[1])
669
+ if len(nums) >= 3:
670
+ micro = int(nums[2])
671
+ return (major, minor, micro)
672
+
673
+
674
+ def get_winver():
675
+ if not WINDOWS:
676
+ raise NotImplementedError("not WINDOWS")
677
+ wv = sys.getwindowsversion()
678
+ if hasattr(wv, 'service_pack_major'): # python >= 2.7
679
+ sp = wv.service_pack_major or 0
680
+ else:
681
+ r = re.search(r"\s\d$", wv[4])
682
+ sp = int(r.group(0)) if r else 0
683
+ return (wv[0], wv[1], sp)
684
+
685
+
686
+ # ===================================================================
687
+ # --- sync primitives
688
+ # ===================================================================
689
+
690
+
691
+ class retry:
692
+ """A retry decorator."""
693
+
694
+ def __init__(
695
+ self,
696
+ exception=Exception,
697
+ timeout=None,
698
+ retries=None,
699
+ interval=0.001,
700
+ logfun=None,
701
+ ):
702
+ if timeout and retries:
703
+ raise ValueError("timeout and retries args are mutually exclusive")
704
+ self.exception = exception
705
+ self.timeout = timeout
706
+ self.retries = retries
707
+ self.interval = interval
708
+ self.logfun = logfun
709
+
710
+ def __iter__(self):
711
+ if self.timeout:
712
+ stop_at = time.time() + self.timeout
713
+ while time.time() < stop_at:
714
+ yield
715
+ elif self.retries:
716
+ for _ in range(self.retries):
717
+ yield
718
+ else:
719
+ while True:
720
+ yield
721
+
722
+ def sleep(self):
723
+ if self.interval is not None:
724
+ time.sleep(self.interval)
725
+
726
+ def __call__(self, fun):
727
+ @functools.wraps(fun)
728
+ def wrapper(*args, **kwargs):
729
+ exc = None
730
+ for _ in self:
731
+ try:
732
+ return fun(*args, **kwargs)
733
+ except self.exception as _: # NOQA
734
+ exc = _
735
+ if self.logfun is not None:
736
+ self.logfun(exc)
737
+ self.sleep()
738
+ continue
739
+ if PY3:
740
+ raise exc
741
+ else:
742
+ raise
743
+
744
+ # This way the user of the decorated function can change config
745
+ # parameters.
746
+ wrapper.decorator = self
747
+ return wrapper
748
+
749
+
750
+ @retry(
751
+ exception=psutil.NoSuchProcess,
752
+ logfun=None,
753
+ timeout=GLOBAL_TIMEOUT,
754
+ interval=0.001,
755
+ )
756
+ def wait_for_pid(pid):
757
+ """Wait for pid to show up in the process list then return.
758
+ Used in the test suite to give time the sub process to initialize.
759
+ """
760
+ if pid not in psutil.pids():
761
+ raise psutil.NoSuchProcess(pid)
762
+ psutil.Process(pid)
763
+
764
+
765
+ @retry(
766
+ exception=(FileNotFoundError, AssertionError),
767
+ logfun=None,
768
+ timeout=GLOBAL_TIMEOUT,
769
+ interval=0.001,
770
+ )
771
+ def wait_for_file(fname, delete=True, empty=False):
772
+ """Wait for a file to be written on disk with some content."""
773
+ with open(fname, "rb") as f:
774
+ data = f.read()
775
+ if not empty:
776
+ assert data
777
+ if delete:
778
+ safe_rmpath(fname)
779
+ return data
780
+
781
+
782
+ @retry(
783
+ exception=AssertionError,
784
+ logfun=None,
785
+ timeout=GLOBAL_TIMEOUT,
786
+ interval=0.001,
787
+ )
788
+ def call_until(fun, expr):
789
+ """Keep calling function for timeout secs and exit if eval()
790
+ expression is True.
791
+ """
792
+ ret = fun()
793
+ assert eval(expr) # noqa
794
+ return ret
795
+
796
+
797
+ # ===================================================================
798
+ # --- fs
799
+ # ===================================================================
800
+
801
+
802
+ def safe_rmpath(path):
803
+ """Convenience function for removing temporary test files or dirs."""
804
+
805
+ def retry_fun(fun):
806
+ # On Windows it could happen that the file or directory has
807
+ # open handles or references preventing the delete operation
808
+ # to succeed immediately, so we retry for a while. See:
809
+ # https://bugs.python.org/issue33240
810
+ stop_at = time.time() + GLOBAL_TIMEOUT
811
+ while time.time() < stop_at:
812
+ try:
813
+ return fun()
814
+ except FileNotFoundError:
815
+ pass
816
+ except WindowsError as _:
817
+ err = _
818
+ warn("ignoring %s" % (str(err)))
819
+ time.sleep(0.01)
820
+ raise err
821
+
822
+ try:
823
+ st = os.stat(path)
824
+ if stat.S_ISDIR(st.st_mode):
825
+ fun = functools.partial(shutil.rmtree, path)
826
+ else:
827
+ fun = functools.partial(os.remove, path)
828
+ if POSIX:
829
+ fun()
830
+ else:
831
+ retry_fun(fun)
832
+ except FileNotFoundError:
833
+ pass
834
+
835
+
836
+ def safe_mkdir(dir):
837
+ """Convenience function for creating a directory."""
838
+ try:
839
+ os.mkdir(dir)
840
+ except FileExistsError:
841
+ pass
842
+
843
+
844
+ @contextlib.contextmanager
845
+ def chdir(dirname):
846
+ """Context manager which temporarily changes the current directory."""
847
+ curdir = os.getcwd()
848
+ try:
849
+ os.chdir(dirname)
850
+ yield
851
+ finally:
852
+ os.chdir(curdir)
853
+
854
+
855
+ def create_py_exe(path):
856
+ """Create a Python executable file in the given location."""
857
+ assert not os.path.exists(path), path
858
+ atexit.register(safe_rmpath, path)
859
+ shutil.copyfile(PYTHON_EXE, path)
860
+ if POSIX:
861
+ st = os.stat(path)
862
+ os.chmod(path, st.st_mode | stat.S_IEXEC)
863
+ return path
864
+
865
+
866
+ def create_c_exe(path, c_code=None):
867
+ """Create a compiled C executable in the given location."""
868
+ assert not os.path.exists(path), path
869
+ if not which("gcc"):
870
+ raise unittest.SkipTest("gcc is not installed")
871
+ if c_code is None:
872
+ c_code = textwrap.dedent("""
873
+ #include <unistd.h>
874
+ int main() {
875
+ pause();
876
+ return 1;
877
+ }
878
+ """)
879
+ else:
880
+ assert isinstance(c_code, str), c_code
881
+
882
+ atexit.register(safe_rmpath, path)
883
+ with open(get_testfn(suffix='.c'), "w") as f:
884
+ f.write(c_code)
885
+ try:
886
+ subprocess.check_call(["gcc", f.name, "-o", path])
887
+ finally:
888
+ safe_rmpath(f.name)
889
+ return path
890
+
891
+
892
+ def get_testfn(suffix="", dir=None):
893
+ """Return an absolute pathname of a file or dir that did not
894
+ exist at the time this call is made. Also schedule it for safe
895
+ deletion at interpreter exit. It's technically racy but probably
896
+ not really due to the time variant.
897
+ """
898
+ while True:
899
+ name = tempfile.mktemp(prefix=TESTFN_PREFIX, suffix=suffix, dir=dir)
900
+ if not os.path.exists(name): # also include dirs
901
+ path = os.path.realpath(name) # needed for OSX
902
+ atexit.register(safe_rmpath, path)
903
+ return path
904
+
905
+
906
+ # ===================================================================
907
+ # --- testing
908
+ # ===================================================================
909
+
910
+
911
+ class TestCase(unittest.TestCase):
912
+
913
+ # Print a full path representation of the single unit tests
914
+ # being run.
915
+ def __str__(self):
916
+ fqmod = self.__class__.__module__
917
+ if not fqmod.startswith('psutil.'):
918
+ fqmod = 'psutil.tests.' + fqmod
919
+ return "%s.%s.%s" % (
920
+ fqmod,
921
+ self.__class__.__name__,
922
+ self._testMethodName,
923
+ )
924
+
925
+ # assertRaisesRegexp renamed to assertRaisesRegex in 3.3;
926
+ # add support for the new name.
927
+ if not hasattr(unittest.TestCase, 'assertRaisesRegex'):
928
+ assertRaisesRegex = unittest.TestCase.assertRaisesRegexp # noqa
929
+
930
+ # ...otherwise multiprocessing.Pool complains
931
+ if not PY3:
932
+
933
+ def runTest(self):
934
+ pass
935
+
936
+ @contextlib.contextmanager
937
+ def subTest(self, *args, **kw):
938
+ # fake it for python 2.7
939
+ yield
940
+
941
+
942
+ # monkey patch default unittest.TestCase
943
+ unittest.TestCase = TestCase
944
+
945
+
946
+ class PsutilTestCase(TestCase):
947
+ """Test class providing auto-cleanup wrappers on top of process
948
+ test utilities.
949
+ """
950
+
951
+ def get_testfn(self, suffix="", dir=None):
952
+ fname = get_testfn(suffix=suffix, dir=dir)
953
+ self.addCleanup(safe_rmpath, fname)
954
+ return fname
955
+
956
+ def spawn_testproc(self, *args, **kwds):
957
+ sproc = spawn_testproc(*args, **kwds)
958
+ self.addCleanup(terminate, sproc)
959
+ return sproc
960
+
961
+ def spawn_children_pair(self):
962
+ child1, child2 = spawn_children_pair()
963
+ self.addCleanup(terminate, child2)
964
+ self.addCleanup(terminate, child1) # executed first
965
+ return (child1, child2)
966
+
967
+ def spawn_zombie(self):
968
+ parent, zombie = spawn_zombie()
969
+ self.addCleanup(terminate, zombie)
970
+ self.addCleanup(terminate, parent) # executed first
971
+ return (parent, zombie)
972
+
973
+ def pyrun(self, *args, **kwds):
974
+ sproc, srcfile = pyrun(*args, **kwds)
975
+ self.addCleanup(safe_rmpath, srcfile)
976
+ self.addCleanup(terminate, sproc) # executed first
977
+ return sproc
978
+
979
+ def _check_proc_exc(self, proc, exc):
980
+ self.assertIsInstance(exc, psutil.Error)
981
+ self.assertEqual(exc.pid, proc.pid)
982
+ self.assertEqual(exc.name, proc._name)
983
+ if exc.name:
984
+ self.assertNotEqual(exc.name, "")
985
+ if isinstance(exc, psutil.ZombieProcess):
986
+ self.assertEqual(exc.ppid, proc._ppid)
987
+ if exc.ppid is not None:
988
+ self.assertGreaterEqual(exc.ppid, 0)
989
+ str(exc)
990
+ repr(exc)
991
+
992
+ def assertPidGone(self, pid):
993
+ with self.assertRaises(psutil.NoSuchProcess) as cm:
994
+ try:
995
+ psutil.Process(pid)
996
+ except psutil.ZombieProcess:
997
+ raise AssertionError("wasn't supposed to raise ZombieProcess")
998
+ self.assertEqual(cm.exception.pid, pid)
999
+ self.assertEqual(cm.exception.name, None)
1000
+ assert not psutil.pid_exists(pid), pid
1001
+ self.assertNotIn(pid, psutil.pids())
1002
+ self.assertNotIn(pid, [x.pid for x in psutil.process_iter()])
1003
+
1004
+ def assertProcessGone(self, proc):
1005
+ self.assertPidGone(proc.pid)
1006
+ ns = process_namespace(proc)
1007
+ for fun, name in ns.iter(ns.all, clear_cache=True):
1008
+ with self.subTest(proc=proc, name=name):
1009
+ try:
1010
+ ret = fun()
1011
+ except psutil.ZombieProcess:
1012
+ raise
1013
+ except psutil.NoSuchProcess as exc:
1014
+ self._check_proc_exc(proc, exc)
1015
+ else:
1016
+ msg = "Process.%s() didn't raise NSP and returned %r" % (
1017
+ name,
1018
+ ret,
1019
+ )
1020
+ raise AssertionError(msg)
1021
+ proc.wait(timeout=0) # assert not raise TimeoutExpired
1022
+
1023
+ def assertProcessZombie(self, proc):
1024
+ # A zombie process should always be instantiable.
1025
+ clone = psutil.Process(proc.pid)
1026
+ # Cloned zombie on Open/NetBSD has null creation time, see:
1027
+ # https://github.com/giampaolo/psutil/issues/2287
1028
+ self.assertEqual(proc, clone)
1029
+ if not (OPENBSD or NETBSD):
1030
+ self.assertEqual(hash(proc), hash(clone))
1031
+ # Its status always be querable.
1032
+ self.assertEqual(proc.status(), psutil.STATUS_ZOMBIE)
1033
+ # It should be considered 'running'.
1034
+ assert proc.is_running()
1035
+ assert psutil.pid_exists(proc.pid)
1036
+ # as_dict() shouldn't crash.
1037
+ proc.as_dict()
1038
+ # It should show up in pids() and process_iter().
1039
+ self.assertIn(proc.pid, psutil.pids())
1040
+ self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
1041
+ psutil._pmap = {}
1042
+ self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
1043
+ # Call all methods.
1044
+ ns = process_namespace(proc)
1045
+ for fun, name in ns.iter(ns.all, clear_cache=True):
1046
+ with self.subTest(proc=proc, name=name):
1047
+ try:
1048
+ fun()
1049
+ except (psutil.ZombieProcess, psutil.AccessDenied) as exc:
1050
+ self._check_proc_exc(proc, exc)
1051
+ if LINUX:
1052
+ # https://github.com/giampaolo/psutil/pull/2288
1053
+ with self.assertRaises(psutil.ZombieProcess) as cm:
1054
+ proc.cmdline()
1055
+ self._check_proc_exc(proc, cm.exception)
1056
+ with self.assertRaises(psutil.ZombieProcess) as cm:
1057
+ proc.exe()
1058
+ self._check_proc_exc(proc, cm.exception)
1059
+ with self.assertRaises(psutil.ZombieProcess) as cm:
1060
+ proc.memory_maps()
1061
+ self._check_proc_exc(proc, cm.exception)
1062
+ # Zombie cannot be signaled or terminated.
1063
+ proc.suspend()
1064
+ proc.resume()
1065
+ proc.terminate()
1066
+ proc.kill()
1067
+ assert proc.is_running()
1068
+ assert psutil.pid_exists(proc.pid)
1069
+ self.assertIn(proc.pid, psutil.pids())
1070
+ self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
1071
+ psutil._pmap = {}
1072
+ self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
1073
+
1074
+ # Its parent should 'see' it (edit: not true on BSD and MACOS).
1075
+ # descendants = [x.pid for x in psutil.Process().children(
1076
+ # recursive=True)]
1077
+ # self.assertIn(proc.pid, descendants)
1078
+
1079
+ # __eq__ can't be relied upon because creation time may not be
1080
+ # querable.
1081
+ # self.assertEqual(proc, psutil.Process(proc.pid))
1082
+
1083
+ # XXX should we also assume ppid() to be usable? Note: this
1084
+ # would be an important use case as the only way to get
1085
+ # rid of a zombie is to kill its parent.
1086
+ # self.assertEqual(proc.ppid(), os.getpid())
1087
+
1088
+
1089
+ @unittest.skipIf(PYPY, "unreliable on PYPY")
1090
+ class TestMemoryLeak(PsutilTestCase):
1091
+ """Test framework class for detecting function memory leaks,
1092
+ typically functions implemented in C which forgot to free() memory
1093
+ from the heap. It does so by checking whether the process memory
1094
+ usage increased before and after calling the function many times.
1095
+
1096
+ Note that this is hard (probably impossible) to do reliably, due
1097
+ to how the OS handles memory, the GC and so on (memory can even
1098
+ decrease!). In order to avoid false positives, in case of failure
1099
+ (mem > 0) we retry the test for up to 5 times, increasing call
1100
+ repetitions each time. If the memory keeps increasing then it's a
1101
+ failure.
1102
+
1103
+ If available (Linux, OSX, Windows), USS memory is used for comparison,
1104
+ since it's supposed to be more precise, see:
1105
+ https://gmpy.dev/blog/2016/real-process-memory-and-environ-in-python
1106
+ If not, RSS memory is used. mallinfo() on Linux and _heapwalk() on
1107
+ Windows may give even more precision, but at the moment are not
1108
+ implemented.
1109
+
1110
+ PyPy appears to be completely unstable for this framework, probably
1111
+ because of its JIT, so tests on PYPY are skipped.
1112
+
1113
+ Usage:
1114
+
1115
+ class TestLeaks(psutil.tests.TestMemoryLeak):
1116
+
1117
+ def test_fun(self):
1118
+ self.execute(some_function)
1119
+ """
1120
+
1121
+ # Configurable class attrs.
1122
+ times = 200
1123
+ warmup_times = 10
1124
+ tolerance = 0 # memory
1125
+ retries = 10 if CI_TESTING else 5
1126
+ verbose = True
1127
+ _thisproc = psutil.Process()
1128
+ _psutil_debug_orig = bool(os.getenv('PSUTIL_DEBUG'))
1129
+
1130
+ @classmethod
1131
+ def setUpClass(cls):
1132
+ psutil._set_debug(False) # avoid spamming to stderr
1133
+
1134
+ @classmethod
1135
+ def tearDownClass(cls):
1136
+ psutil._set_debug(cls._psutil_debug_orig)
1137
+
1138
+ def _get_mem(self):
1139
+ # USS is the closest thing we have to "real" memory usage and it
1140
+ # should be less likely to produce false positives.
1141
+ mem = self._thisproc.memory_full_info()
1142
+ return getattr(mem, "uss", mem.rss)
1143
+
1144
+ def _get_num_fds(self):
1145
+ if POSIX:
1146
+ return self._thisproc.num_fds()
1147
+ else:
1148
+ return self._thisproc.num_handles()
1149
+
1150
+ def _log(self, msg):
1151
+ if self.verbose:
1152
+ print_color(msg, color="yellow", file=sys.stderr)
1153
+
1154
+ def _check_fds(self, fun):
1155
+ """Makes sure num_fds() (POSIX) or num_handles() (Windows) does
1156
+ not increase after calling a function. Used to discover forgotten
1157
+ close(2) and CloseHandle syscalls.
1158
+ """
1159
+ before = self._get_num_fds()
1160
+ self.call(fun)
1161
+ after = self._get_num_fds()
1162
+ diff = after - before
1163
+ if diff < 0:
1164
+ raise self.fail(
1165
+ "negative diff %r (gc probably collected a "
1166
+ "resource from a previous test)" % diff
1167
+ )
1168
+ if diff > 0:
1169
+ type_ = "fd" if POSIX else "handle"
1170
+ if diff > 1:
1171
+ type_ += "s"
1172
+ msg = "%s unclosed %s after calling %r" % (diff, type_, fun)
1173
+ raise self.fail(msg)
1174
+
1175
+ def _call_ntimes(self, fun, times):
1176
+ """Get 2 distinct memory samples, before and after having
1177
+ called fun repeatedly, and return the memory difference.
1178
+ """
1179
+ gc.collect(generation=1)
1180
+ mem1 = self._get_mem()
1181
+ for x in range(times):
1182
+ ret = self.call(fun)
1183
+ del x, ret
1184
+ gc.collect(generation=1)
1185
+ mem2 = self._get_mem()
1186
+ self.assertEqual(gc.garbage, [])
1187
+ diff = mem2 - mem1 # can also be negative
1188
+ return diff
1189
+
1190
+ def _check_mem(self, fun, times, retries, tolerance):
1191
+ messages = []
1192
+ prev_mem = 0
1193
+ increase = times
1194
+ for idx in range(1, retries + 1):
1195
+ mem = self._call_ntimes(fun, times)
1196
+ msg = "Run #%s: extra-mem=%s, per-call=%s, calls=%s" % (
1197
+ idx,
1198
+ bytes2human(mem),
1199
+ bytes2human(mem / times),
1200
+ times,
1201
+ )
1202
+ messages.append(msg)
1203
+ success = mem <= tolerance or mem <= prev_mem
1204
+ if success:
1205
+ if idx > 1:
1206
+ self._log(msg)
1207
+ return
1208
+ else:
1209
+ if idx == 1:
1210
+ print() # NOQA
1211
+ self._log(msg)
1212
+ times += increase
1213
+ prev_mem = mem
1214
+ raise self.fail(". ".join(messages))
1215
+
1216
+ # ---
1217
+
1218
+ def call(self, fun):
1219
+ return fun()
1220
+
1221
+ def execute(
1222
+ self, fun, times=None, warmup_times=None, retries=None, tolerance=None
1223
+ ):
1224
+ """Test a callable."""
1225
+ times = times if times is not None else self.times
1226
+ warmup_times = (
1227
+ warmup_times if warmup_times is not None else self.warmup_times
1228
+ )
1229
+ retries = retries if retries is not None else self.retries
1230
+ tolerance = tolerance if tolerance is not None else self.tolerance
1231
+ try:
1232
+ assert times >= 1, "times must be >= 1"
1233
+ assert warmup_times >= 0, "warmup_times must be >= 0"
1234
+ assert retries >= 0, "retries must be >= 0"
1235
+ assert tolerance >= 0, "tolerance must be >= 0"
1236
+ except AssertionError as err:
1237
+ raise ValueError(str(err))
1238
+
1239
+ self._call_ntimes(fun, warmup_times) # warm up
1240
+ self._check_fds(fun)
1241
+ self._check_mem(fun, times=times, retries=retries, tolerance=tolerance)
1242
+
1243
+ def execute_w_exc(self, exc, fun, **kwargs):
1244
+ """Convenience method to test a callable while making sure it
1245
+ raises an exception on every call.
1246
+ """
1247
+
1248
+ def call():
1249
+ self.assertRaises(exc, fun)
1250
+
1251
+ self.execute(call, **kwargs)
1252
+
1253
+
1254
+ def print_sysinfo():
1255
+ import collections
1256
+ import datetime
1257
+ import getpass
1258
+ import locale
1259
+ import pprint
1260
+
1261
+ try:
1262
+ import pip
1263
+ except ImportError:
1264
+ pip = None
1265
+ try:
1266
+ import wheel
1267
+ except ImportError:
1268
+ wheel = None
1269
+
1270
+ info = collections.OrderedDict()
1271
+
1272
+ # OS
1273
+ if psutil.LINUX and which('lsb_release'):
1274
+ info['OS'] = sh('lsb_release -d -s')
1275
+ elif psutil.OSX:
1276
+ info['OS'] = 'Darwin %s' % platform.mac_ver()[0]
1277
+ elif psutil.WINDOWS:
1278
+ info['OS'] = "Windows " + ' '.join(map(str, platform.win32_ver()))
1279
+ if hasattr(platform, 'win32_edition'):
1280
+ info['OS'] += ", " + platform.win32_edition()
1281
+ else:
1282
+ info['OS'] = "%s %s" % (platform.system(), platform.version())
1283
+ info['arch'] = ', '.join(
1284
+ list(platform.architecture()) + [platform.machine()]
1285
+ )
1286
+ if psutil.POSIX:
1287
+ info['kernel'] = platform.uname()[2]
1288
+
1289
+ # python
1290
+ info['python'] = ', '.join([
1291
+ platform.python_implementation(),
1292
+ platform.python_version(),
1293
+ platform.python_compiler(),
1294
+ ])
1295
+ info['pip'] = getattr(pip, '__version__', 'not installed')
1296
+ if wheel is not None:
1297
+ info['pip'] += " (wheel=%s)" % wheel.__version__
1298
+
1299
+ # UNIX
1300
+ if psutil.POSIX:
1301
+ if which('gcc'):
1302
+ out = sh(['gcc', '--version'])
1303
+ info['gcc'] = str(out).split('\n')[0]
1304
+ else:
1305
+ info['gcc'] = 'not installed'
1306
+ s = platform.libc_ver()[1]
1307
+ if s:
1308
+ info['glibc'] = s
1309
+
1310
+ # system
1311
+ info['fs-encoding'] = sys.getfilesystemencoding()
1312
+ lang = locale.getlocale()
1313
+ info['lang'] = '%s, %s' % (lang[0], lang[1])
1314
+ info['boot-time'] = datetime.datetime.fromtimestamp(
1315
+ psutil.boot_time()
1316
+ ).strftime("%Y-%m-%d %H:%M:%S")
1317
+ info['time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1318
+ info['user'] = getpass.getuser()
1319
+ info['home'] = os.path.expanduser("~")
1320
+ info['cwd'] = os.getcwd()
1321
+ info['pyexe'] = PYTHON_EXE
1322
+ info['hostname'] = platform.node()
1323
+ info['PID'] = os.getpid()
1324
+
1325
+ # metrics
1326
+ info['cpus'] = psutil.cpu_count()
1327
+ info['loadavg'] = "%.1f%%, %.1f%%, %.1f%%" % (
1328
+ tuple([x / psutil.cpu_count() * 100 for x in psutil.getloadavg()])
1329
+ )
1330
+ mem = psutil.virtual_memory()
1331
+ info['memory'] = "%s%%, used=%s, total=%s" % (
1332
+ int(mem.percent),
1333
+ bytes2human(mem.used),
1334
+ bytes2human(mem.total),
1335
+ )
1336
+ swap = psutil.swap_memory()
1337
+ info['swap'] = "%s%%, used=%s, total=%s" % (
1338
+ int(swap.percent),
1339
+ bytes2human(swap.used),
1340
+ bytes2human(swap.total),
1341
+ )
1342
+ info['pids'] = len(psutil.pids())
1343
+ pinfo = psutil.Process().as_dict()
1344
+ pinfo.pop('memory_maps', None)
1345
+ info['proc'] = pprint.pformat(pinfo)
1346
+
1347
+ print("=" * 70, file=sys.stderr) # NOQA
1348
+ for k, v in info.items():
1349
+ print("%-17s %s" % (k + ':', v), file=sys.stderr) # NOQA
1350
+ print("=" * 70, file=sys.stderr) # NOQA
1351
+ sys.stdout.flush()
1352
+
1353
+ if WINDOWS:
1354
+ os.system("tasklist")
1355
+ elif which("ps"):
1356
+ os.system("ps aux")
1357
+ print("=" * 70, file=sys.stderr) # NOQA
1358
+ sys.stdout.flush()
1359
+
1360
+
1361
+ def is_win_secure_system_proc(pid):
1362
+ # see: https://github.com/giampaolo/psutil/issues/2338
1363
+ @memoize
1364
+ def get_procs():
1365
+ ret = {}
1366
+ out = sh("tasklist.exe /NH /FO csv")
1367
+ for line in out.splitlines()[1:]:
1368
+ bits = [x.replace('"', "") for x in line.split(",")]
1369
+ name, pid = bits[0], int(bits[1])
1370
+ ret[pid] = name
1371
+ return ret
1372
+
1373
+ try:
1374
+ return get_procs()[pid] == "Secure System"
1375
+ except KeyError:
1376
+ return False
1377
+
1378
+
1379
+ def _get_eligible_cpu():
1380
+ p = psutil.Process()
1381
+ if hasattr(p, "cpu_num"):
1382
+ return p.cpu_num()
1383
+ elif hasattr(p, "cpu_affinity"):
1384
+ return random.choice(p.cpu_affinity())
1385
+ return 0
1386
+
1387
+
1388
+ class process_namespace:
1389
+ """A container that lists all Process class method names + some
1390
+ reasonable parameters to be called with. Utility methods (parent(),
1391
+ children(), ...) are excluded.
1392
+
1393
+ >>> ns = process_namespace(psutil.Process())
1394
+ >>> for fun, name in ns.iter(ns.getters):
1395
+ ... fun()
1396
+ """
1397
+
1398
+ utils = [('cpu_percent', (), {}), ('memory_percent', (), {})]
1399
+
1400
+ ignored = [
1401
+ ('as_dict', (), {}),
1402
+ ('children', (), {'recursive': True}),
1403
+ ('is_running', (), {}),
1404
+ ('memory_info_ex', (), {}),
1405
+ ('oneshot', (), {}),
1406
+ ('parent', (), {}),
1407
+ ('parents', (), {}),
1408
+ ('pid', (), {}),
1409
+ ('wait', (0,), {}),
1410
+ ]
1411
+
1412
+ getters = [
1413
+ ('cmdline', (), {}),
1414
+ ('connections', (), {'kind': 'all'}),
1415
+ ('cpu_times', (), {}),
1416
+ ('create_time', (), {}),
1417
+ ('cwd', (), {}),
1418
+ ('exe', (), {}),
1419
+ ('memory_full_info', (), {}),
1420
+ ('memory_info', (), {}),
1421
+ ('name', (), {}),
1422
+ ('nice', (), {}),
1423
+ ('num_ctx_switches', (), {}),
1424
+ ('num_threads', (), {}),
1425
+ ('open_files', (), {}),
1426
+ ('ppid', (), {}),
1427
+ ('status', (), {}),
1428
+ ('threads', (), {}),
1429
+ ('username', (), {}),
1430
+ ]
1431
+ if POSIX:
1432
+ getters += [('uids', (), {})]
1433
+ getters += [('gids', (), {})]
1434
+ getters += [('terminal', (), {})]
1435
+ getters += [('num_fds', (), {})]
1436
+ if HAS_PROC_IO_COUNTERS:
1437
+ getters += [('io_counters', (), {})]
1438
+ if HAS_IONICE:
1439
+ getters += [('ionice', (), {})]
1440
+ if HAS_RLIMIT:
1441
+ getters += [('rlimit', (psutil.RLIMIT_NOFILE,), {})]
1442
+ if HAS_CPU_AFFINITY:
1443
+ getters += [('cpu_affinity', (), {})]
1444
+ if HAS_PROC_CPU_NUM:
1445
+ getters += [('cpu_num', (), {})]
1446
+ if HAS_ENVIRON:
1447
+ getters += [('environ', (), {})]
1448
+ if WINDOWS:
1449
+ getters += [('num_handles', (), {})]
1450
+ if HAS_MEMORY_MAPS:
1451
+ getters += [('memory_maps', (), {'grouped': False})]
1452
+
1453
+ setters = []
1454
+ if POSIX:
1455
+ setters += [('nice', (0,), {})]
1456
+ else:
1457
+ setters += [('nice', (psutil.NORMAL_PRIORITY_CLASS,), {})]
1458
+ if HAS_RLIMIT:
1459
+ setters += [('rlimit', (psutil.RLIMIT_NOFILE, (1024, 4096)), {})]
1460
+ if HAS_IONICE:
1461
+ if LINUX:
1462
+ setters += [('ionice', (psutil.IOPRIO_CLASS_NONE, 0), {})]
1463
+ else:
1464
+ setters += [('ionice', (psutil.IOPRIO_NORMAL,), {})]
1465
+ if HAS_CPU_AFFINITY:
1466
+ setters += [('cpu_affinity', ([_get_eligible_cpu()],), {})]
1467
+
1468
+ killers = [
1469
+ ('send_signal', (signal.SIGTERM,), {}),
1470
+ ('suspend', (), {}),
1471
+ ('resume', (), {}),
1472
+ ('terminate', (), {}),
1473
+ ('kill', (), {}),
1474
+ ]
1475
+ if WINDOWS:
1476
+ killers += [('send_signal', (signal.CTRL_C_EVENT,), {})]
1477
+ killers += [('send_signal', (signal.CTRL_BREAK_EVENT,), {})]
1478
+
1479
+ all = utils + getters + setters + killers
1480
+
1481
+ def __init__(self, proc):
1482
+ self._proc = proc
1483
+
1484
+ def iter(self, ls, clear_cache=True):
1485
+ """Given a list of tuples yields a set of (fun, fun_name) tuples
1486
+ in random order.
1487
+ """
1488
+ ls = list(ls)
1489
+ random.shuffle(ls)
1490
+ for fun_name, args, kwds in ls:
1491
+ if clear_cache:
1492
+ self.clear_cache()
1493
+ fun = getattr(self._proc, fun_name)
1494
+ fun = functools.partial(fun, *args, **kwds)
1495
+ yield (fun, fun_name)
1496
+
1497
+ def clear_cache(self):
1498
+ """Clear the cache of a Process instance."""
1499
+ self._proc._init(self._proc.pid, _ignore_nsp=True)
1500
+
1501
+ @classmethod
1502
+ def test_class_coverage(cls, test_class, ls):
1503
+ """Given a TestCase instance and a list of tuples checks that
1504
+ the class defines the required test method names.
1505
+ """
1506
+ for fun_name, _, _ in ls:
1507
+ meth_name = 'test_' + fun_name
1508
+ if not hasattr(test_class, meth_name):
1509
+ msg = "%r class should define a '%s' method" % (
1510
+ test_class.__class__.__name__,
1511
+ meth_name,
1512
+ )
1513
+ raise AttributeError(msg)
1514
+
1515
+ @classmethod
1516
+ def test(cls):
1517
+ this = set([x[0] for x in cls.all])
1518
+ ignored = set([x[0] for x in cls.ignored])
1519
+ klass = set([x for x in dir(psutil.Process) if x[0] != '_'])
1520
+ leftout = (this | ignored) ^ klass
1521
+ if leftout:
1522
+ raise ValueError("uncovered Process class names: %r" % leftout)
1523
+
1524
+
1525
+ class system_namespace:
1526
+ """A container that lists all the module-level, system-related APIs.
1527
+ Utilities such as cpu_percent() are excluded. Usage:
1528
+
1529
+ >>> ns = system_namespace
1530
+ >>> for fun, name in ns.iter(ns.getters):
1531
+ ... fun()
1532
+ """
1533
+
1534
+ getters = [
1535
+ ('boot_time', (), {}),
1536
+ ('cpu_count', (), {'logical': False}),
1537
+ ('cpu_count', (), {'logical': True}),
1538
+ ('cpu_stats', (), {}),
1539
+ ('cpu_times', (), {'percpu': False}),
1540
+ ('cpu_times', (), {'percpu': True}),
1541
+ ('disk_io_counters', (), {'perdisk': True}),
1542
+ ('disk_partitions', (), {'all': True}),
1543
+ ('disk_usage', (os.getcwd(),), {}),
1544
+ ('net_connections', (), {'kind': 'all'}),
1545
+ ('net_if_addrs', (), {}),
1546
+ ('net_if_stats', (), {}),
1547
+ ('net_io_counters', (), {'pernic': True}),
1548
+ ('pid_exists', (os.getpid(),), {}),
1549
+ ('pids', (), {}),
1550
+ ('swap_memory', (), {}),
1551
+ ('users', (), {}),
1552
+ ('virtual_memory', (), {}),
1553
+ ]
1554
+ if HAS_CPU_FREQ:
1555
+ getters += [('cpu_freq', (), {'percpu': True})]
1556
+ if HAS_GETLOADAVG:
1557
+ getters += [('getloadavg', (), {})]
1558
+ if HAS_SENSORS_TEMPERATURES:
1559
+ getters += [('sensors_temperatures', (), {})]
1560
+ if HAS_SENSORS_FANS:
1561
+ getters += [('sensors_fans', (), {})]
1562
+ if HAS_SENSORS_BATTERY:
1563
+ getters += [('sensors_battery', (), {})]
1564
+ if WINDOWS:
1565
+ getters += [('win_service_iter', (), {})]
1566
+ getters += [('win_service_get', ('alg',), {})]
1567
+
1568
+ ignored = [
1569
+ ('process_iter', (), {}),
1570
+ ('wait_procs', ([psutil.Process()],), {}),
1571
+ ('cpu_percent', (), {}),
1572
+ ('cpu_times_percent', (), {}),
1573
+ ]
1574
+
1575
+ all = getters
1576
+
1577
+ @staticmethod
1578
+ def iter(ls):
1579
+ """Given a list of tuples yields a set of (fun, fun_name) tuples
1580
+ in random order.
1581
+ """
1582
+ ls = list(ls)
1583
+ random.shuffle(ls)
1584
+ for fun_name, args, kwds in ls:
1585
+ fun = getattr(psutil, fun_name)
1586
+ fun = functools.partial(fun, *args, **kwds)
1587
+ yield (fun, fun_name)
1588
+
1589
+ test_class_coverage = process_namespace.test_class_coverage
1590
+
1591
+
1592
+ def serialrun(klass):
1593
+ """A decorator to mark a TestCase class. When running parallel tests,
1594
+ class' unit tests will be run serially (1 process).
1595
+ """
1596
+ # assert issubclass(klass, unittest.TestCase), klass
1597
+ assert inspect.isclass(klass), klass
1598
+ klass._serialrun = True
1599
+ return klass
1600
+
1601
+
1602
+ def retry_on_failure(retries=NO_RETRIES):
1603
+ """Decorator which runs a test function and retries N times before
1604
+ actually failing.
1605
+ """
1606
+
1607
+ def logfun(exc):
1608
+ print("%r, retrying" % exc, file=sys.stderr) # NOQA
1609
+
1610
+ return retry(
1611
+ exception=AssertionError, timeout=None, retries=retries, logfun=logfun
1612
+ )
1613
+
1614
+
1615
+ def skip_on_access_denied(only_if=None):
1616
+ """Decorator to Ignore AccessDenied exceptions."""
1617
+
1618
+ def decorator(fun):
1619
+ @functools.wraps(fun)
1620
+ def wrapper(*args, **kwargs):
1621
+ try:
1622
+ return fun(*args, **kwargs)
1623
+ except psutil.AccessDenied:
1624
+ if only_if is not None:
1625
+ if not only_if:
1626
+ raise
1627
+ raise unittest.SkipTest("raises AccessDenied")
1628
+
1629
+ return wrapper
1630
+
1631
+ return decorator
1632
+
1633
+
1634
+ def skip_on_not_implemented(only_if=None):
1635
+ """Decorator to Ignore NotImplementedError exceptions."""
1636
+
1637
+ def decorator(fun):
1638
+ @functools.wraps(fun)
1639
+ def wrapper(*args, **kwargs):
1640
+ try:
1641
+ return fun(*args, **kwargs)
1642
+ except NotImplementedError:
1643
+ if only_if is not None:
1644
+ if not only_if:
1645
+ raise
1646
+ msg = (
1647
+ "%r was skipped because it raised NotImplementedError"
1648
+ % fun.__name__
1649
+ )
1650
+ raise unittest.SkipTest(msg)
1651
+
1652
+ return wrapper
1653
+
1654
+ return decorator
1655
+
1656
+
1657
+ # ===================================================================
1658
+ # --- network
1659
+ # ===================================================================
1660
+
1661
+
1662
+ # XXX: no longer used
1663
+ def get_free_port(host='127.0.0.1'):
1664
+ """Return an unused TCP port. Subject to race conditions."""
1665
+ with contextlib.closing(socket.socket()) as sock:
1666
+ sock.bind((host, 0))
1667
+ return sock.getsockname()[1]
1668
+
1669
+
1670
+ def bind_socket(family=AF_INET, type=SOCK_STREAM, addr=None):
1671
+ """Binds a generic socket."""
1672
+ if addr is None and family in (AF_INET, AF_INET6):
1673
+ addr = ("", 0)
1674
+ sock = socket.socket(family, type)
1675
+ try:
1676
+ if os.name not in ('nt', 'cygwin'):
1677
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1678
+ sock.bind(addr)
1679
+ if type == socket.SOCK_STREAM:
1680
+ sock.listen(5)
1681
+ return sock
1682
+ except Exception:
1683
+ sock.close()
1684
+ raise
1685
+
1686
+
1687
+ def bind_unix_socket(name, type=socket.SOCK_STREAM):
1688
+ """Bind a UNIX socket."""
1689
+ assert psutil.POSIX
1690
+ assert not os.path.exists(name), name
1691
+ sock = socket.socket(socket.AF_UNIX, type)
1692
+ try:
1693
+ sock.bind(name)
1694
+ if type == socket.SOCK_STREAM:
1695
+ sock.listen(5)
1696
+ except Exception:
1697
+ sock.close()
1698
+ raise
1699
+ return sock
1700
+
1701
+
1702
+ def tcp_socketpair(family, addr=("", 0)):
1703
+ """Build a pair of TCP sockets connected to each other.
1704
+ Return a (server, client) tuple.
1705
+ """
1706
+ with contextlib.closing(socket.socket(family, SOCK_STREAM)) as ll:
1707
+ ll.bind(addr)
1708
+ ll.listen(5)
1709
+ addr = ll.getsockname()
1710
+ c = socket.socket(family, SOCK_STREAM)
1711
+ try:
1712
+ c.connect(addr)
1713
+ caddr = c.getsockname()
1714
+ while True:
1715
+ a, addr = ll.accept()
1716
+ # check that we've got the correct client
1717
+ if addr == caddr:
1718
+ return (a, c)
1719
+ a.close()
1720
+ except OSError:
1721
+ c.close()
1722
+ raise
1723
+
1724
+
1725
+ def unix_socketpair(name):
1726
+ """Build a pair of UNIX sockets connected to each other through
1727
+ the same UNIX file name.
1728
+ Return a (server, client) tuple.
1729
+ """
1730
+ assert psutil.POSIX
1731
+ server = client = None
1732
+ try:
1733
+ server = bind_unix_socket(name, type=socket.SOCK_STREAM)
1734
+ server.setblocking(0)
1735
+ client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1736
+ client.setblocking(0)
1737
+ client.connect(name)
1738
+ # new = server.accept()
1739
+ except Exception:
1740
+ if server is not None:
1741
+ server.close()
1742
+ if client is not None:
1743
+ client.close()
1744
+ raise
1745
+ return (server, client)
1746
+
1747
+
1748
+ @contextlib.contextmanager
1749
+ def create_sockets():
1750
+ """Open as many socket families / types as possible."""
1751
+ socks = []
1752
+ fname1 = fname2 = None
1753
+ try:
1754
+ socks.append(bind_socket(socket.AF_INET, socket.SOCK_STREAM))
1755
+ socks.append(bind_socket(socket.AF_INET, socket.SOCK_DGRAM))
1756
+ if supports_ipv6():
1757
+ socks.append(bind_socket(socket.AF_INET6, socket.SOCK_STREAM))
1758
+ socks.append(bind_socket(socket.AF_INET6, socket.SOCK_DGRAM))
1759
+ if POSIX and HAS_CONNECTIONS_UNIX:
1760
+ fname1 = get_testfn()
1761
+ fname2 = get_testfn()
1762
+ s1, s2 = unix_socketpair(fname1)
1763
+ s3 = bind_unix_socket(fname2, type=socket.SOCK_DGRAM)
1764
+ for s in (s1, s2, s3):
1765
+ socks.append(s)
1766
+ yield socks
1767
+ finally:
1768
+ for s in socks:
1769
+ s.close()
1770
+ for fname in (fname1, fname2):
1771
+ if fname is not None:
1772
+ safe_rmpath(fname)
1773
+
1774
+
1775
+ def check_net_address(addr, family):
1776
+ """Check a net address validity. Supported families are IPv4,
1777
+ IPv6 and MAC addresses.
1778
+ """
1779
+ import ipaddress # python >= 3.3 / requires "pip install ipaddress"
1780
+
1781
+ if enum and PY3 and not PYPY:
1782
+ assert isinstance(family, enum.IntEnum), family
1783
+ if family == socket.AF_INET:
1784
+ octs = [int(x) for x in addr.split('.')]
1785
+ assert len(octs) == 4, addr
1786
+ for num in octs:
1787
+ assert 0 <= num <= 255, addr
1788
+ if not PY3:
1789
+ addr = unicode(addr)
1790
+ ipaddress.IPv4Address(addr)
1791
+ elif family == socket.AF_INET6:
1792
+ assert isinstance(addr, str), addr
1793
+ if not PY3:
1794
+ addr = unicode(addr)
1795
+ ipaddress.IPv6Address(addr)
1796
+ elif family == psutil.AF_LINK:
1797
+ assert re.match(r'([a-fA-F0-9]{2}[:|\-]?){6}', addr) is not None, addr
1798
+ else:
1799
+ raise ValueError("unknown family %r" % family)
1800
+
1801
+
1802
+ def check_connection_ntuple(conn):
1803
+ """Check validity of a connection namedtuple."""
1804
+
1805
+ def check_ntuple(conn):
1806
+ has_pid = len(conn) == 7
1807
+ assert len(conn) in (6, 7), len(conn)
1808
+ assert conn[0] == conn.fd, conn.fd
1809
+ assert conn[1] == conn.family, conn.family
1810
+ assert conn[2] == conn.type, conn.type
1811
+ assert conn[3] == conn.laddr, conn.laddr
1812
+ assert conn[4] == conn.raddr, conn.raddr
1813
+ assert conn[5] == conn.status, conn.status
1814
+ if has_pid:
1815
+ assert conn[6] == conn.pid, conn.pid
1816
+
1817
+ def check_family(conn):
1818
+ assert conn.family in (AF_INET, AF_INET6, AF_UNIX), conn.family
1819
+ if enum is not None:
1820
+ assert isinstance(conn.family, enum.IntEnum), conn
1821
+ else:
1822
+ assert isinstance(conn.family, int), conn
1823
+ if conn.family == AF_INET:
1824
+ # actually try to bind the local socket; ignore IPv6
1825
+ # sockets as their address might be represented as
1826
+ # an IPv4-mapped-address (e.g. "::127.0.0.1")
1827
+ # and that's rejected by bind()
1828
+ s = socket.socket(conn.family, conn.type)
1829
+ with contextlib.closing(s):
1830
+ try:
1831
+ s.bind((conn.laddr[0], 0))
1832
+ except socket.error as err:
1833
+ if err.errno != errno.EADDRNOTAVAIL:
1834
+ raise
1835
+ elif conn.family == AF_UNIX:
1836
+ assert conn.status == psutil.CONN_NONE, conn.status
1837
+
1838
+ def check_type(conn):
1839
+ # SOCK_SEQPACKET may happen in case of AF_UNIX socks
1840
+ SOCK_SEQPACKET = getattr(socket, "SOCK_SEQPACKET", object())
1841
+ assert conn.type in (
1842
+ socket.SOCK_STREAM,
1843
+ socket.SOCK_DGRAM,
1844
+ SOCK_SEQPACKET,
1845
+ ), conn.type
1846
+ if enum is not None:
1847
+ assert isinstance(conn.type, enum.IntEnum), conn
1848
+ else:
1849
+ assert isinstance(conn.type, int), conn
1850
+ if conn.type == socket.SOCK_DGRAM:
1851
+ assert conn.status == psutil.CONN_NONE, conn.status
1852
+
1853
+ def check_addrs(conn):
1854
+ # check IP address and port sanity
1855
+ for addr in (conn.laddr, conn.raddr):
1856
+ if conn.family in (AF_INET, AF_INET6):
1857
+ assert isinstance(addr, tuple), type(addr)
1858
+ if not addr:
1859
+ continue
1860
+ assert isinstance(addr.port, int), type(addr.port)
1861
+ assert 0 <= addr.port <= 65535, addr.port
1862
+ check_net_address(addr.ip, conn.family)
1863
+ elif conn.family == AF_UNIX:
1864
+ assert isinstance(addr, str), type(addr)
1865
+
1866
+ def check_status(conn):
1867
+ assert isinstance(conn.status, str), conn.status
1868
+ valids = [
1869
+ getattr(psutil, x) for x in dir(psutil) if x.startswith('CONN_')
1870
+ ]
1871
+ assert conn.status in valids, conn.status
1872
+ if conn.family in (AF_INET, AF_INET6) and conn.type == SOCK_STREAM:
1873
+ assert conn.status != psutil.CONN_NONE, conn.status
1874
+ else:
1875
+ assert conn.status == psutil.CONN_NONE, conn.status
1876
+
1877
+ check_ntuple(conn)
1878
+ check_family(conn)
1879
+ check_type(conn)
1880
+ check_addrs(conn)
1881
+ check_status(conn)
1882
+
1883
+
1884
+ def filter_proc_connections(cons):
1885
+ """Our process may start with some open UNIX sockets which are not
1886
+ initialized by us, invalidating unit tests.
1887
+ """
1888
+ new = []
1889
+ for conn in cons:
1890
+ if POSIX and conn.family == socket.AF_UNIX:
1891
+ if MACOS and "/syslog" in conn.raddr:
1892
+ debug("skipping %s" % str(conn))
1893
+ continue
1894
+ new.append(conn)
1895
+ return new
1896
+
1897
+
1898
+ # ===================================================================
1899
+ # --- compatibility
1900
+ # ===================================================================
1901
+
1902
+
1903
+ def reload_module(module):
1904
+ """Backport of importlib.reload of Python 3.3+."""
1905
+ try:
1906
+ import importlib
1907
+
1908
+ if not hasattr(importlib, 'reload'): # python <=3.3
1909
+ raise ImportError
1910
+ except ImportError:
1911
+ import imp
1912
+
1913
+ return imp.reload(module)
1914
+ else:
1915
+ return importlib.reload(module)
1916
+
1917
+
1918
+ def import_module_by_path(path):
1919
+ name = os.path.splitext(os.path.basename(path))[0]
1920
+ if sys.version_info[0] < 3:
1921
+ import imp
1922
+
1923
+ return imp.load_source(name, path)
1924
+ else:
1925
+ import importlib.util
1926
+
1927
+ spec = importlib.util.spec_from_file_location(name, path)
1928
+ mod = importlib.util.module_from_spec(spec)
1929
+ spec.loader.exec_module(mod)
1930
+ return mod
1931
+
1932
+
1933
+ # ===================================================================
1934
+ # --- others
1935
+ # ===================================================================
1936
+
1937
+
1938
+ def warn(msg):
1939
+ """Raise a warning msg."""
1940
+ warnings.warn(msg, UserWarning, stacklevel=2)
1941
+
1942
+
1943
+ def is_namedtuple(x):
1944
+ """Check if object is an instance of namedtuple."""
1945
+ t = type(x)
1946
+ b = t.__bases__
1947
+ if len(b) != 1 or b[0] != tuple:
1948
+ return False
1949
+ f = getattr(t, '_fields', None)
1950
+ if not isinstance(f, tuple):
1951
+ return False
1952
+ return all(isinstance(n, str) for n in f)
1953
+
1954
+
1955
+ if POSIX:
1956
+
1957
+ @contextlib.contextmanager
1958
+ def copyload_shared_lib(suffix=""):
1959
+ """Ctx manager which picks up a random shared CO lib used
1960
+ by this process, copies it in another location and loads it
1961
+ in memory via ctypes. Return the new absolutized path.
1962
+ """
1963
+ exe = 'pypy' if PYPY else 'python'
1964
+ ext = ".so"
1965
+ dst = get_testfn(suffix=suffix + ext)
1966
+ libs = [
1967
+ x.path
1968
+ for x in psutil.Process().memory_maps()
1969
+ if os.path.splitext(x.path)[1] == ext and exe in x.path.lower()
1970
+ ]
1971
+ src = random.choice(libs)
1972
+ shutil.copyfile(src, dst)
1973
+ try:
1974
+ ctypes.CDLL(dst)
1975
+ yield dst
1976
+ finally:
1977
+ safe_rmpath(dst)
1978
+
1979
+ else:
1980
+
1981
+ @contextlib.contextmanager
1982
+ def copyload_shared_lib(suffix=""):
1983
+ """Ctx manager which picks up a random shared DLL lib used
1984
+ by this process, copies it in another location and loads it
1985
+ in memory via ctypes.
1986
+ Return the new absolutized, normcased path.
1987
+ """
1988
+ from ctypes import WinError
1989
+ from ctypes import wintypes
1990
+
1991
+ ext = ".dll"
1992
+ dst = get_testfn(suffix=suffix + ext)
1993
+ libs = [
1994
+ x.path
1995
+ for x in psutil.Process().memory_maps()
1996
+ if x.path.lower().endswith(ext)
1997
+ and 'python' in os.path.basename(x.path).lower()
1998
+ and 'wow64' not in x.path.lower()
1999
+ ]
2000
+ if PYPY and not libs:
2001
+ libs = [
2002
+ x.path
2003
+ for x in psutil.Process().memory_maps()
2004
+ if 'pypy' in os.path.basename(x.path).lower()
2005
+ ]
2006
+ src = random.choice(libs)
2007
+ shutil.copyfile(src, dst)
2008
+ cfile = None
2009
+ try:
2010
+ cfile = ctypes.WinDLL(dst)
2011
+ yield dst
2012
+ finally:
2013
+ # Work around OverflowError:
2014
+ # - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/
2015
+ # job/o53330pbnri9bcw7
2016
+ # - http://bugs.python.org/issue30286
2017
+ # - http://stackoverflow.com/questions/23522055
2018
+ if cfile is not None:
2019
+ FreeLibrary = ctypes.windll.kernel32.FreeLibrary
2020
+ FreeLibrary.argtypes = [wintypes.HMODULE]
2021
+ ret = FreeLibrary(cfile._handle)
2022
+ if ret == 0:
2023
+ WinError()
2024
+ safe_rmpath(dst)
2025
+
2026
+
2027
+ # ===================================================================
2028
+ # --- Exit funs (first is executed last)
2029
+ # ===================================================================
2030
+
2031
+
2032
+ # this is executed first
2033
+ @atexit.register
2034
+ def cleanup_test_procs():
2035
+ reap_children(recursive=True)
2036
+
2037
+
2038
+ # atexit module does not execute exit functions in case of SIGTERM, which
2039
+ # gets sent to test subprocesses, which is a problem if they import this
2040
+ # module. With this it will. See:
2041
+ # https://gmpy.dev/blog/2016/how-to-always-execute-exit-functions-in-python
2042
+ if POSIX:
2043
+ signal.signal(signal.SIGTERM, lambda sig, _: sys.exit(sig))
llmeval-env/lib/python3.10/site-packages/psutil/tests/__main__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """Run unit tests. This is invoked by:
6
+ $ python -m psutil.tests.
7
+ """
8
+
9
+ from .runner import main
10
+
11
+
12
+ main()
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (53.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (307 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/runner.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_aix.cpython-310.pyc ADDED
Binary file (3.39 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_bsd.cpython-310.pyc ADDED
Binary file (19.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_connections.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_contracts.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_linux.cpython-310.pyc ADDED
Binary file (73.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_memleaks.cpython-310.pyc ADDED
Binary file (22.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_misc.cpython-310.pyc ADDED
Binary file (29.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/psutil/tests/__pycache__/test_osx.cpython-310.pyc ADDED
Binary file (6.6 kB). View file