Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- llmeval-env/lib/python3.10/site-packages/colorama/__init__.py +7 -0
- llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/ansi.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/ansitowin32.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/initialise.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/win32.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/winterm.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/ansi.py +102 -0
- llmeval-env/lib/python3.10/site-packages/colorama/ansitowin32.py +277 -0
- llmeval-env/lib/python3.10/site-packages/colorama/initialise.py +121 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/__init__.py +1 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/ansi_test.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/initialise_test.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/isatty_test.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/utils.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/winterm_test.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/ansi_test.py +76 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/ansitowin32_test.py +294 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/initialise_test.py +189 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/isatty_test.py +57 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/utils.py +49 -0
- llmeval-env/lib/python3.10/site-packages/colorama/tests/winterm_test.py +131 -0
- llmeval-env/lib/python3.10/site-packages/colorama/win32.py +180 -0
- llmeval-env/lib/python3.10/site-packages/colorama/winterm.py +195 -0
- llmeval-env/lib/python3.10/site-packages/jsonlines/__init__.py +20 -0
- llmeval-env/lib/python3.10/site-packages/jsonlines/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/jsonlines/__pycache__/jsonlines.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/jsonlines/jsonlines.py +665 -0
- llmeval-env/lib/python3.10/site-packages/jsonlines/py.typed +0 -0
- llmeval-env/lib/python3.10/site-packages/psutil/_psbsd.py +977 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdq-42585.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jd-61.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdf-61.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdq-61.json.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/data-v1-dl-61.arff.gz +3 -0
- llmeval-env/lib/python3.10/site-packages/sqlitedict-2.1.0.egg-info/installed-files.txt +6 -0
- llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__init__.py +1 -0
- llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__pycache__/logger.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__pycache__/std.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__pycache__/tqdm_multiprocess.cpython-310.pyc +0 -0
.gitattributes
CHANGED
@@ -86,3 +86,4 @@ llmeval-env/lib/python3.10/site-packages/lxml/objectify.cpython-310-x86_64-linux
|
|
86 |
llmeval-env/lib/python3.10/site-packages/tokenizers/tokenizers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
87 |
llmeval-env/lib/python3.10/site-packages/numpy.libs/libopenblas64_p-r0-0cf96a72.3.23.dev.so filter=lfs diff=lfs merge=lfs -text
|
88 |
llmeval-env/lib/python3.10/site-packages/regex/_regex.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
86 |
llmeval-env/lib/python3.10/site-packages/tokenizers/tokenizers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
87 |
llmeval-env/lib/python3.10/site-packages/numpy.libs/libopenblas64_p-r0-0cf96a72.3.23.dev.so filter=lfs diff=lfs merge=lfs -text
|
88 |
llmeval-env/lib/python3.10/site-packages/regex/_regex.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
89 |
+
llmeval-env/lib/python3.10/site-packages/triton/_C/libtriton.so filter=lfs diff=lfs merge=lfs -text
|
llmeval-env/lib/python3.10/site-packages/colorama/__init__.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
from .initialise import init, deinit, reinit, colorama_text, just_fix_windows_console
|
3 |
+
from .ansi import Fore, Back, Style, Cursor
|
4 |
+
from .ansitowin32 import AnsiToWin32
|
5 |
+
|
6 |
+
__version__ = '0.4.6'
|
7 |
+
|
llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (467 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/ansi.cpython-310.pyc
ADDED
Binary file (2.99 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/ansitowin32.cpython-310.pyc
ADDED
Binary file (8.51 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/initialise.cpython-310.pyc
ADDED
Binary file (2.25 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/win32.cpython-310.pyc
ADDED
Binary file (4.46 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/__pycache__/winterm.cpython-310.pyc
ADDED
Binary file (5.16 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/ansi.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
'''
|
3 |
+
This module generates ANSI character codes to printing colors to terminals.
|
4 |
+
See: http://en.wikipedia.org/wiki/ANSI_escape_code
|
5 |
+
'''
|
6 |
+
|
7 |
+
CSI = '\033['
|
8 |
+
OSC = '\033]'
|
9 |
+
BEL = '\a'
|
10 |
+
|
11 |
+
|
12 |
+
def code_to_chars(code):
|
13 |
+
return CSI + str(code) + 'm'
|
14 |
+
|
15 |
+
def set_title(title):
|
16 |
+
return OSC + '2;' + title + BEL
|
17 |
+
|
18 |
+
def clear_screen(mode=2):
|
19 |
+
return CSI + str(mode) + 'J'
|
20 |
+
|
21 |
+
def clear_line(mode=2):
|
22 |
+
return CSI + str(mode) + 'K'
|
23 |
+
|
24 |
+
|
25 |
+
class AnsiCodes(object):
|
26 |
+
def __init__(self):
|
27 |
+
# the subclasses declare class attributes which are numbers.
|
28 |
+
# Upon instantiation we define instance attributes, which are the same
|
29 |
+
# as the class attributes but wrapped with the ANSI escape sequence
|
30 |
+
for name in dir(self):
|
31 |
+
if not name.startswith('_'):
|
32 |
+
value = getattr(self, name)
|
33 |
+
setattr(self, name, code_to_chars(value))
|
34 |
+
|
35 |
+
|
36 |
+
class AnsiCursor(object):
|
37 |
+
def UP(self, n=1):
|
38 |
+
return CSI + str(n) + 'A'
|
39 |
+
def DOWN(self, n=1):
|
40 |
+
return CSI + str(n) + 'B'
|
41 |
+
def FORWARD(self, n=1):
|
42 |
+
return CSI + str(n) + 'C'
|
43 |
+
def BACK(self, n=1):
|
44 |
+
return CSI + str(n) + 'D'
|
45 |
+
def POS(self, x=1, y=1):
|
46 |
+
return CSI + str(y) + ';' + str(x) + 'H'
|
47 |
+
|
48 |
+
|
49 |
+
class AnsiFore(AnsiCodes):
|
50 |
+
BLACK = 30
|
51 |
+
RED = 31
|
52 |
+
GREEN = 32
|
53 |
+
YELLOW = 33
|
54 |
+
BLUE = 34
|
55 |
+
MAGENTA = 35
|
56 |
+
CYAN = 36
|
57 |
+
WHITE = 37
|
58 |
+
RESET = 39
|
59 |
+
|
60 |
+
# These are fairly well supported, but not part of the standard.
|
61 |
+
LIGHTBLACK_EX = 90
|
62 |
+
LIGHTRED_EX = 91
|
63 |
+
LIGHTGREEN_EX = 92
|
64 |
+
LIGHTYELLOW_EX = 93
|
65 |
+
LIGHTBLUE_EX = 94
|
66 |
+
LIGHTMAGENTA_EX = 95
|
67 |
+
LIGHTCYAN_EX = 96
|
68 |
+
LIGHTWHITE_EX = 97
|
69 |
+
|
70 |
+
|
71 |
+
class AnsiBack(AnsiCodes):
|
72 |
+
BLACK = 40
|
73 |
+
RED = 41
|
74 |
+
GREEN = 42
|
75 |
+
YELLOW = 43
|
76 |
+
BLUE = 44
|
77 |
+
MAGENTA = 45
|
78 |
+
CYAN = 46
|
79 |
+
WHITE = 47
|
80 |
+
RESET = 49
|
81 |
+
|
82 |
+
# These are fairly well supported, but not part of the standard.
|
83 |
+
LIGHTBLACK_EX = 100
|
84 |
+
LIGHTRED_EX = 101
|
85 |
+
LIGHTGREEN_EX = 102
|
86 |
+
LIGHTYELLOW_EX = 103
|
87 |
+
LIGHTBLUE_EX = 104
|
88 |
+
LIGHTMAGENTA_EX = 105
|
89 |
+
LIGHTCYAN_EX = 106
|
90 |
+
LIGHTWHITE_EX = 107
|
91 |
+
|
92 |
+
|
93 |
+
class AnsiStyle(AnsiCodes):
|
94 |
+
BRIGHT = 1
|
95 |
+
DIM = 2
|
96 |
+
NORMAL = 22
|
97 |
+
RESET_ALL = 0
|
98 |
+
|
99 |
+
Fore = AnsiFore()
|
100 |
+
Back = AnsiBack()
|
101 |
+
Style = AnsiStyle()
|
102 |
+
Cursor = AnsiCursor()
|
llmeval-env/lib/python3.10/site-packages/colorama/ansitowin32.py
ADDED
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import re
|
3 |
+
import sys
|
4 |
+
import os
|
5 |
+
|
6 |
+
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
|
7 |
+
from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle
|
8 |
+
from .win32 import windll, winapi_test
|
9 |
+
|
10 |
+
|
11 |
+
winterm = None
|
12 |
+
if windll is not None:
|
13 |
+
winterm = WinTerm()
|
14 |
+
|
15 |
+
|
16 |
+
class StreamWrapper(object):
|
17 |
+
'''
|
18 |
+
Wraps a stream (such as stdout), acting as a transparent proxy for all
|
19 |
+
attribute access apart from method 'write()', which is delegated to our
|
20 |
+
Converter instance.
|
21 |
+
'''
|
22 |
+
def __init__(self, wrapped, converter):
|
23 |
+
# double-underscore everything to prevent clashes with names of
|
24 |
+
# attributes on the wrapped stream object.
|
25 |
+
self.__wrapped = wrapped
|
26 |
+
self.__convertor = converter
|
27 |
+
|
28 |
+
def __getattr__(self, name):
|
29 |
+
return getattr(self.__wrapped, name)
|
30 |
+
|
31 |
+
def __enter__(self, *args, **kwargs):
|
32 |
+
# special method lookup bypasses __getattr__/__getattribute__, see
|
33 |
+
# https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit
|
34 |
+
# thus, contextlib magic methods are not proxied via __getattr__
|
35 |
+
return self.__wrapped.__enter__(*args, **kwargs)
|
36 |
+
|
37 |
+
def __exit__(self, *args, **kwargs):
|
38 |
+
return self.__wrapped.__exit__(*args, **kwargs)
|
39 |
+
|
40 |
+
def __setstate__(self, state):
|
41 |
+
self.__dict__ = state
|
42 |
+
|
43 |
+
def __getstate__(self):
|
44 |
+
return self.__dict__
|
45 |
+
|
46 |
+
def write(self, text):
|
47 |
+
self.__convertor.write(text)
|
48 |
+
|
49 |
+
def isatty(self):
|
50 |
+
stream = self.__wrapped
|
51 |
+
if 'PYCHARM_HOSTED' in os.environ:
|
52 |
+
if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
|
53 |
+
return True
|
54 |
+
try:
|
55 |
+
stream_isatty = stream.isatty
|
56 |
+
except AttributeError:
|
57 |
+
return False
|
58 |
+
else:
|
59 |
+
return stream_isatty()
|
60 |
+
|
61 |
+
@property
|
62 |
+
def closed(self):
|
63 |
+
stream = self.__wrapped
|
64 |
+
try:
|
65 |
+
return stream.closed
|
66 |
+
# AttributeError in the case that the stream doesn't support being closed
|
67 |
+
# ValueError for the case that the stream has already been detached when atexit runs
|
68 |
+
except (AttributeError, ValueError):
|
69 |
+
return True
|
70 |
+
|
71 |
+
|
72 |
+
class AnsiToWin32(object):
|
73 |
+
'''
|
74 |
+
Implements a 'write()' method which, on Windows, will strip ANSI character
|
75 |
+
sequences from the text, and if outputting to a tty, will convert them into
|
76 |
+
win32 function calls.
|
77 |
+
'''
|
78 |
+
ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer
|
79 |
+
ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command
|
80 |
+
|
81 |
+
def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
|
82 |
+
# The wrapped stream (normally sys.stdout or sys.stderr)
|
83 |
+
self.wrapped = wrapped
|
84 |
+
|
85 |
+
# should we reset colors to defaults after every .write()
|
86 |
+
self.autoreset = autoreset
|
87 |
+
|
88 |
+
# create the proxy wrapping our output stream
|
89 |
+
self.stream = StreamWrapper(wrapped, self)
|
90 |
+
|
91 |
+
on_windows = os.name == 'nt'
|
92 |
+
# We test if the WinAPI works, because even if we are on Windows
|
93 |
+
# we may be using a terminal that doesn't support the WinAPI
|
94 |
+
# (e.g. Cygwin Terminal). In this case it's up to the terminal
|
95 |
+
# to support the ANSI codes.
|
96 |
+
conversion_supported = on_windows and winapi_test()
|
97 |
+
try:
|
98 |
+
fd = wrapped.fileno()
|
99 |
+
except Exception:
|
100 |
+
fd = -1
|
101 |
+
system_has_native_ansi = not on_windows or enable_vt_processing(fd)
|
102 |
+
have_tty = not self.stream.closed and self.stream.isatty()
|
103 |
+
need_conversion = conversion_supported and not system_has_native_ansi
|
104 |
+
|
105 |
+
# should we strip ANSI sequences from our output?
|
106 |
+
if strip is None:
|
107 |
+
strip = need_conversion or not have_tty
|
108 |
+
self.strip = strip
|
109 |
+
|
110 |
+
# should we should convert ANSI sequences into win32 calls?
|
111 |
+
if convert is None:
|
112 |
+
convert = need_conversion and have_tty
|
113 |
+
self.convert = convert
|
114 |
+
|
115 |
+
# dict of ansi codes to win32 functions and parameters
|
116 |
+
self.win32_calls = self.get_win32_calls()
|
117 |
+
|
118 |
+
# are we wrapping stderr?
|
119 |
+
self.on_stderr = self.wrapped is sys.stderr
|
120 |
+
|
121 |
+
def should_wrap(self):
|
122 |
+
'''
|
123 |
+
True if this class is actually needed. If false, then the output
|
124 |
+
stream will not be affected, nor will win32 calls be issued, so
|
125 |
+
wrapping stdout is not actually required. This will generally be
|
126 |
+
False on non-Windows platforms, unless optional functionality like
|
127 |
+
autoreset has been requested using kwargs to init()
|
128 |
+
'''
|
129 |
+
return self.convert or self.strip or self.autoreset
|
130 |
+
|
131 |
+
def get_win32_calls(self):
|
132 |
+
if self.convert and winterm:
|
133 |
+
return {
|
134 |
+
AnsiStyle.RESET_ALL: (winterm.reset_all, ),
|
135 |
+
AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),
|
136 |
+
AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),
|
137 |
+
AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),
|
138 |
+
AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),
|
139 |
+
AnsiFore.RED: (winterm.fore, WinColor.RED),
|
140 |
+
AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),
|
141 |
+
AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),
|
142 |
+
AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),
|
143 |
+
AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),
|
144 |
+
AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),
|
145 |
+
AnsiFore.WHITE: (winterm.fore, WinColor.GREY),
|
146 |
+
AnsiFore.RESET: (winterm.fore, ),
|
147 |
+
AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),
|
148 |
+
AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),
|
149 |
+
AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),
|
150 |
+
AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),
|
151 |
+
AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),
|
152 |
+
AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),
|
153 |
+
AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),
|
154 |
+
AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),
|
155 |
+
AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
|
156 |
+
AnsiBack.RED: (winterm.back, WinColor.RED),
|
157 |
+
AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
|
158 |
+
AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
|
159 |
+
AnsiBack.BLUE: (winterm.back, WinColor.BLUE),
|
160 |
+
AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
|
161 |
+
AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
|
162 |
+
AnsiBack.WHITE: (winterm.back, WinColor.GREY),
|
163 |
+
AnsiBack.RESET: (winterm.back, ),
|
164 |
+
AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),
|
165 |
+
AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),
|
166 |
+
AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),
|
167 |
+
AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),
|
168 |
+
AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),
|
169 |
+
AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),
|
170 |
+
AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),
|
171 |
+
AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),
|
172 |
+
}
|
173 |
+
return dict()
|
174 |
+
|
175 |
+
def write(self, text):
|
176 |
+
if self.strip or self.convert:
|
177 |
+
self.write_and_convert(text)
|
178 |
+
else:
|
179 |
+
self.wrapped.write(text)
|
180 |
+
self.wrapped.flush()
|
181 |
+
if self.autoreset:
|
182 |
+
self.reset_all()
|
183 |
+
|
184 |
+
|
185 |
+
def reset_all(self):
|
186 |
+
if self.convert:
|
187 |
+
self.call_win32('m', (0,))
|
188 |
+
elif not self.strip and not self.stream.closed:
|
189 |
+
self.wrapped.write(Style.RESET_ALL)
|
190 |
+
|
191 |
+
|
192 |
+
def write_and_convert(self, text):
|
193 |
+
'''
|
194 |
+
Write the given text to our wrapped stream, stripping any ANSI
|
195 |
+
sequences from the text, and optionally converting them into win32
|
196 |
+
calls.
|
197 |
+
'''
|
198 |
+
cursor = 0
|
199 |
+
text = self.convert_osc(text)
|
200 |
+
for match in self.ANSI_CSI_RE.finditer(text):
|
201 |
+
start, end = match.span()
|
202 |
+
self.write_plain_text(text, cursor, start)
|
203 |
+
self.convert_ansi(*match.groups())
|
204 |
+
cursor = end
|
205 |
+
self.write_plain_text(text, cursor, len(text))
|
206 |
+
|
207 |
+
|
208 |
+
def write_plain_text(self, text, start, end):
|
209 |
+
if start < end:
|
210 |
+
self.wrapped.write(text[start:end])
|
211 |
+
self.wrapped.flush()
|
212 |
+
|
213 |
+
|
214 |
+
def convert_ansi(self, paramstring, command):
|
215 |
+
if self.convert:
|
216 |
+
params = self.extract_params(command, paramstring)
|
217 |
+
self.call_win32(command, params)
|
218 |
+
|
219 |
+
|
220 |
+
def extract_params(self, command, paramstring):
|
221 |
+
if command in 'Hf':
|
222 |
+
params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';'))
|
223 |
+
while len(params) < 2:
|
224 |
+
# defaults:
|
225 |
+
params = params + (1,)
|
226 |
+
else:
|
227 |
+
params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)
|
228 |
+
if len(params) == 0:
|
229 |
+
# defaults:
|
230 |
+
if command in 'JKm':
|
231 |
+
params = (0,)
|
232 |
+
elif command in 'ABCD':
|
233 |
+
params = (1,)
|
234 |
+
|
235 |
+
return params
|
236 |
+
|
237 |
+
|
238 |
+
def call_win32(self, command, params):
|
239 |
+
if command == 'm':
|
240 |
+
for param in params:
|
241 |
+
if param in self.win32_calls:
|
242 |
+
func_args = self.win32_calls[param]
|
243 |
+
func = func_args[0]
|
244 |
+
args = func_args[1:]
|
245 |
+
kwargs = dict(on_stderr=self.on_stderr)
|
246 |
+
func(*args, **kwargs)
|
247 |
+
elif command in 'J':
|
248 |
+
winterm.erase_screen(params[0], on_stderr=self.on_stderr)
|
249 |
+
elif command in 'K':
|
250 |
+
winterm.erase_line(params[0], on_stderr=self.on_stderr)
|
251 |
+
elif command in 'Hf': # cursor position - absolute
|
252 |
+
winterm.set_cursor_position(params, on_stderr=self.on_stderr)
|
253 |
+
elif command in 'ABCD': # cursor position - relative
|
254 |
+
n = params[0]
|
255 |
+
# A - up, B - down, C - forward, D - back
|
256 |
+
x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command]
|
257 |
+
winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)
|
258 |
+
|
259 |
+
|
260 |
+
def convert_osc(self, text):
|
261 |
+
for match in self.ANSI_OSC_RE.finditer(text):
|
262 |
+
start, end = match.span()
|
263 |
+
text = text[:start] + text[end:]
|
264 |
+
paramstring, command = match.groups()
|
265 |
+
if command == BEL:
|
266 |
+
if paramstring.count(";") == 1:
|
267 |
+
params = paramstring.split(";")
|
268 |
+
# 0 - change title and icon (we will only change title)
|
269 |
+
# 1 - change icon (we don't support this)
|
270 |
+
# 2 - change title
|
271 |
+
if params[0] in '02':
|
272 |
+
winterm.set_title(params[1])
|
273 |
+
return text
|
274 |
+
|
275 |
+
|
276 |
+
def flush(self):
|
277 |
+
self.wrapped.flush()
|
llmeval-env/lib/python3.10/site-packages/colorama/initialise.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import atexit
|
3 |
+
import contextlib
|
4 |
+
import sys
|
5 |
+
|
6 |
+
from .ansitowin32 import AnsiToWin32
|
7 |
+
|
8 |
+
|
9 |
+
def _wipe_internal_state_for_tests():
|
10 |
+
global orig_stdout, orig_stderr
|
11 |
+
orig_stdout = None
|
12 |
+
orig_stderr = None
|
13 |
+
|
14 |
+
global wrapped_stdout, wrapped_stderr
|
15 |
+
wrapped_stdout = None
|
16 |
+
wrapped_stderr = None
|
17 |
+
|
18 |
+
global atexit_done
|
19 |
+
atexit_done = False
|
20 |
+
|
21 |
+
global fixed_windows_console
|
22 |
+
fixed_windows_console = False
|
23 |
+
|
24 |
+
try:
|
25 |
+
# no-op if it wasn't registered
|
26 |
+
atexit.unregister(reset_all)
|
27 |
+
except AttributeError:
|
28 |
+
# python 2: no atexit.unregister. Oh well, we did our best.
|
29 |
+
pass
|
30 |
+
|
31 |
+
|
32 |
+
def reset_all():
|
33 |
+
if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
|
34 |
+
AnsiToWin32(orig_stdout).reset_all()
|
35 |
+
|
36 |
+
|
37 |
+
def init(autoreset=False, convert=None, strip=None, wrap=True):
|
38 |
+
|
39 |
+
if not wrap and any([autoreset, convert, strip]):
|
40 |
+
raise ValueError('wrap=False conflicts with any other arg=True')
|
41 |
+
|
42 |
+
global wrapped_stdout, wrapped_stderr
|
43 |
+
global orig_stdout, orig_stderr
|
44 |
+
|
45 |
+
orig_stdout = sys.stdout
|
46 |
+
orig_stderr = sys.stderr
|
47 |
+
|
48 |
+
if sys.stdout is None:
|
49 |
+
wrapped_stdout = None
|
50 |
+
else:
|
51 |
+
sys.stdout = wrapped_stdout = \
|
52 |
+
wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
|
53 |
+
if sys.stderr is None:
|
54 |
+
wrapped_stderr = None
|
55 |
+
else:
|
56 |
+
sys.stderr = wrapped_stderr = \
|
57 |
+
wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
|
58 |
+
|
59 |
+
global atexit_done
|
60 |
+
if not atexit_done:
|
61 |
+
atexit.register(reset_all)
|
62 |
+
atexit_done = True
|
63 |
+
|
64 |
+
|
65 |
+
def deinit():
|
66 |
+
if orig_stdout is not None:
|
67 |
+
sys.stdout = orig_stdout
|
68 |
+
if orig_stderr is not None:
|
69 |
+
sys.stderr = orig_stderr
|
70 |
+
|
71 |
+
|
72 |
+
def just_fix_windows_console():
|
73 |
+
global fixed_windows_console
|
74 |
+
|
75 |
+
if sys.platform != "win32":
|
76 |
+
return
|
77 |
+
if fixed_windows_console:
|
78 |
+
return
|
79 |
+
if wrapped_stdout is not None or wrapped_stderr is not None:
|
80 |
+
# Someone already ran init() and it did stuff, so we won't second-guess them
|
81 |
+
return
|
82 |
+
|
83 |
+
# On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the
|
84 |
+
# native ANSI support in the console as a side-effect. We only need to actually
|
85 |
+
# replace sys.stdout/stderr if we're in the old-style conversion mode.
|
86 |
+
new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False)
|
87 |
+
if new_stdout.convert:
|
88 |
+
sys.stdout = new_stdout
|
89 |
+
new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False)
|
90 |
+
if new_stderr.convert:
|
91 |
+
sys.stderr = new_stderr
|
92 |
+
|
93 |
+
fixed_windows_console = True
|
94 |
+
|
95 |
+
@contextlib.contextmanager
|
96 |
+
def colorama_text(*args, **kwargs):
|
97 |
+
init(*args, **kwargs)
|
98 |
+
try:
|
99 |
+
yield
|
100 |
+
finally:
|
101 |
+
deinit()
|
102 |
+
|
103 |
+
|
104 |
+
def reinit():
|
105 |
+
if wrapped_stdout is not None:
|
106 |
+
sys.stdout = wrapped_stdout
|
107 |
+
if wrapped_stderr is not None:
|
108 |
+
sys.stderr = wrapped_stderr
|
109 |
+
|
110 |
+
|
111 |
+
def wrap_stream(stream, convert, strip, autoreset, wrap):
|
112 |
+
if wrap:
|
113 |
+
wrapper = AnsiToWin32(stream,
|
114 |
+
convert=convert, strip=strip, autoreset=autoreset)
|
115 |
+
if wrapper.should_wrap():
|
116 |
+
stream = wrapper.stream
|
117 |
+
return stream
|
118 |
+
|
119 |
+
|
120 |
+
# Use this for initial setup as well, to reduce code duplication
|
121 |
+
_wipe_internal_state_for_tests()
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (187 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/ansi_test.cpython-310.pyc
ADDED
Binary file (2.28 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-310.pyc
ADDED
Binary file (11.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/initialise_test.cpython-310.pyc
ADDED
Binary file (6.89 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/isatty_test.cpython-310.pyc
ADDED
Binary file (2.68 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (1.59 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/__pycache__/winterm_test.cpython-310.pyc
ADDED
Binary file (3.18 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/ansi_test.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import sys
|
3 |
+
from unittest import TestCase, main
|
4 |
+
|
5 |
+
from ..ansi import Back, Fore, Style
|
6 |
+
from ..ansitowin32 import AnsiToWin32
|
7 |
+
|
8 |
+
stdout_orig = sys.stdout
|
9 |
+
stderr_orig = sys.stderr
|
10 |
+
|
11 |
+
|
12 |
+
class AnsiTest(TestCase):
|
13 |
+
|
14 |
+
def setUp(self):
|
15 |
+
# sanity check: stdout should be a file or StringIO object.
|
16 |
+
# It will only be AnsiToWin32 if init() has previously wrapped it
|
17 |
+
self.assertNotEqual(type(sys.stdout), AnsiToWin32)
|
18 |
+
self.assertNotEqual(type(sys.stderr), AnsiToWin32)
|
19 |
+
|
20 |
+
def tearDown(self):
|
21 |
+
sys.stdout = stdout_orig
|
22 |
+
sys.stderr = stderr_orig
|
23 |
+
|
24 |
+
|
25 |
+
def testForeAttributes(self):
|
26 |
+
self.assertEqual(Fore.BLACK, '\033[30m')
|
27 |
+
self.assertEqual(Fore.RED, '\033[31m')
|
28 |
+
self.assertEqual(Fore.GREEN, '\033[32m')
|
29 |
+
self.assertEqual(Fore.YELLOW, '\033[33m')
|
30 |
+
self.assertEqual(Fore.BLUE, '\033[34m')
|
31 |
+
self.assertEqual(Fore.MAGENTA, '\033[35m')
|
32 |
+
self.assertEqual(Fore.CYAN, '\033[36m')
|
33 |
+
self.assertEqual(Fore.WHITE, '\033[37m')
|
34 |
+
self.assertEqual(Fore.RESET, '\033[39m')
|
35 |
+
|
36 |
+
# Check the light, extended versions.
|
37 |
+
self.assertEqual(Fore.LIGHTBLACK_EX, '\033[90m')
|
38 |
+
self.assertEqual(Fore.LIGHTRED_EX, '\033[91m')
|
39 |
+
self.assertEqual(Fore.LIGHTGREEN_EX, '\033[92m')
|
40 |
+
self.assertEqual(Fore.LIGHTYELLOW_EX, '\033[93m')
|
41 |
+
self.assertEqual(Fore.LIGHTBLUE_EX, '\033[94m')
|
42 |
+
self.assertEqual(Fore.LIGHTMAGENTA_EX, '\033[95m')
|
43 |
+
self.assertEqual(Fore.LIGHTCYAN_EX, '\033[96m')
|
44 |
+
self.assertEqual(Fore.LIGHTWHITE_EX, '\033[97m')
|
45 |
+
|
46 |
+
|
47 |
+
def testBackAttributes(self):
|
48 |
+
self.assertEqual(Back.BLACK, '\033[40m')
|
49 |
+
self.assertEqual(Back.RED, '\033[41m')
|
50 |
+
self.assertEqual(Back.GREEN, '\033[42m')
|
51 |
+
self.assertEqual(Back.YELLOW, '\033[43m')
|
52 |
+
self.assertEqual(Back.BLUE, '\033[44m')
|
53 |
+
self.assertEqual(Back.MAGENTA, '\033[45m')
|
54 |
+
self.assertEqual(Back.CYAN, '\033[46m')
|
55 |
+
self.assertEqual(Back.WHITE, '\033[47m')
|
56 |
+
self.assertEqual(Back.RESET, '\033[49m')
|
57 |
+
|
58 |
+
# Check the light, extended versions.
|
59 |
+
self.assertEqual(Back.LIGHTBLACK_EX, '\033[100m')
|
60 |
+
self.assertEqual(Back.LIGHTRED_EX, '\033[101m')
|
61 |
+
self.assertEqual(Back.LIGHTGREEN_EX, '\033[102m')
|
62 |
+
self.assertEqual(Back.LIGHTYELLOW_EX, '\033[103m')
|
63 |
+
self.assertEqual(Back.LIGHTBLUE_EX, '\033[104m')
|
64 |
+
self.assertEqual(Back.LIGHTMAGENTA_EX, '\033[105m')
|
65 |
+
self.assertEqual(Back.LIGHTCYAN_EX, '\033[106m')
|
66 |
+
self.assertEqual(Back.LIGHTWHITE_EX, '\033[107m')
|
67 |
+
|
68 |
+
|
69 |
+
def testStyleAttributes(self):
|
70 |
+
self.assertEqual(Style.DIM, '\033[2m')
|
71 |
+
self.assertEqual(Style.NORMAL, '\033[22m')
|
72 |
+
self.assertEqual(Style.BRIGHT, '\033[1m')
|
73 |
+
|
74 |
+
|
75 |
+
if __name__ == '__main__':
|
76 |
+
main()
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/ansitowin32_test.py
ADDED
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
from io import StringIO, TextIOWrapper
|
3 |
+
from unittest import TestCase, main
|
4 |
+
try:
|
5 |
+
from contextlib import ExitStack
|
6 |
+
except ImportError:
|
7 |
+
# python 2
|
8 |
+
from contextlib2 import ExitStack
|
9 |
+
|
10 |
+
try:
|
11 |
+
from unittest.mock import MagicMock, Mock, patch
|
12 |
+
except ImportError:
|
13 |
+
from mock import MagicMock, Mock, patch
|
14 |
+
|
15 |
+
from ..ansitowin32 import AnsiToWin32, StreamWrapper
|
16 |
+
from ..win32 import ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
17 |
+
from .utils import osname
|
18 |
+
|
19 |
+
|
20 |
+
class StreamWrapperTest(TestCase):
|
21 |
+
|
22 |
+
def testIsAProxy(self):
|
23 |
+
mockStream = Mock()
|
24 |
+
wrapper = StreamWrapper(mockStream, None)
|
25 |
+
self.assertTrue( wrapper.random_attr is mockStream.random_attr )
|
26 |
+
|
27 |
+
def testDelegatesWrite(self):
|
28 |
+
mockStream = Mock()
|
29 |
+
mockConverter = Mock()
|
30 |
+
wrapper = StreamWrapper(mockStream, mockConverter)
|
31 |
+
wrapper.write('hello')
|
32 |
+
self.assertTrue(mockConverter.write.call_args, (('hello',), {}))
|
33 |
+
|
34 |
+
def testDelegatesContext(self):
|
35 |
+
mockConverter = Mock()
|
36 |
+
s = StringIO()
|
37 |
+
with StreamWrapper(s, mockConverter) as fp:
|
38 |
+
fp.write(u'hello')
|
39 |
+
self.assertTrue(s.closed)
|
40 |
+
|
41 |
+
def testProxyNoContextManager(self):
|
42 |
+
mockStream = MagicMock()
|
43 |
+
mockStream.__enter__.side_effect = AttributeError()
|
44 |
+
mockConverter = Mock()
|
45 |
+
with self.assertRaises(AttributeError) as excinfo:
|
46 |
+
with StreamWrapper(mockStream, mockConverter) as wrapper:
|
47 |
+
wrapper.write('hello')
|
48 |
+
|
49 |
+
def test_closed_shouldnt_raise_on_closed_stream(self):
|
50 |
+
stream = StringIO()
|
51 |
+
stream.close()
|
52 |
+
wrapper = StreamWrapper(stream, None)
|
53 |
+
self.assertEqual(wrapper.closed, True)
|
54 |
+
|
55 |
+
def test_closed_shouldnt_raise_on_detached_stream(self):
|
56 |
+
stream = TextIOWrapper(StringIO())
|
57 |
+
stream.detach()
|
58 |
+
wrapper = StreamWrapper(stream, None)
|
59 |
+
self.assertEqual(wrapper.closed, True)
|
60 |
+
|
61 |
+
class AnsiToWin32Test(TestCase):
|
62 |
+
|
63 |
+
def testInit(self):
|
64 |
+
mockStdout = Mock()
|
65 |
+
auto = Mock()
|
66 |
+
stream = AnsiToWin32(mockStdout, autoreset=auto)
|
67 |
+
self.assertEqual(stream.wrapped, mockStdout)
|
68 |
+
self.assertEqual(stream.autoreset, auto)
|
69 |
+
|
70 |
+
@patch('colorama.ansitowin32.winterm', None)
|
71 |
+
@patch('colorama.ansitowin32.winapi_test', lambda *_: True)
|
72 |
+
def testStripIsTrueOnWindows(self):
|
73 |
+
with osname('nt'):
|
74 |
+
mockStdout = Mock()
|
75 |
+
stream = AnsiToWin32(mockStdout)
|
76 |
+
self.assertTrue(stream.strip)
|
77 |
+
|
78 |
+
def testStripIsFalseOffWindows(self):
|
79 |
+
with osname('posix'):
|
80 |
+
mockStdout = Mock(closed=False)
|
81 |
+
stream = AnsiToWin32(mockStdout)
|
82 |
+
self.assertFalse(stream.strip)
|
83 |
+
|
84 |
+
def testWriteStripsAnsi(self):
|
85 |
+
mockStdout = Mock()
|
86 |
+
stream = AnsiToWin32(mockStdout)
|
87 |
+
stream.wrapped = Mock()
|
88 |
+
stream.write_and_convert = Mock()
|
89 |
+
stream.strip = True
|
90 |
+
|
91 |
+
stream.write('abc')
|
92 |
+
|
93 |
+
self.assertFalse(stream.wrapped.write.called)
|
94 |
+
self.assertEqual(stream.write_and_convert.call_args, (('abc',), {}))
|
95 |
+
|
96 |
+
def testWriteDoesNotStripAnsi(self):
|
97 |
+
mockStdout = Mock()
|
98 |
+
stream = AnsiToWin32(mockStdout)
|
99 |
+
stream.wrapped = Mock()
|
100 |
+
stream.write_and_convert = Mock()
|
101 |
+
stream.strip = False
|
102 |
+
stream.convert = False
|
103 |
+
|
104 |
+
stream.write('abc')
|
105 |
+
|
106 |
+
self.assertFalse(stream.write_and_convert.called)
|
107 |
+
self.assertEqual(stream.wrapped.write.call_args, (('abc',), {}))
|
108 |
+
|
109 |
+
def assert_autoresets(self, convert, autoreset=True):
|
110 |
+
stream = AnsiToWin32(Mock())
|
111 |
+
stream.convert = convert
|
112 |
+
stream.reset_all = Mock()
|
113 |
+
stream.autoreset = autoreset
|
114 |
+
stream.winterm = Mock()
|
115 |
+
|
116 |
+
stream.write('abc')
|
117 |
+
|
118 |
+
self.assertEqual(stream.reset_all.called, autoreset)
|
119 |
+
|
120 |
+
def testWriteAutoresets(self):
|
121 |
+
self.assert_autoresets(convert=True)
|
122 |
+
self.assert_autoresets(convert=False)
|
123 |
+
self.assert_autoresets(convert=True, autoreset=False)
|
124 |
+
self.assert_autoresets(convert=False, autoreset=False)
|
125 |
+
|
126 |
+
def testWriteAndConvertWritesPlainText(self):
|
127 |
+
stream = AnsiToWin32(Mock())
|
128 |
+
stream.write_and_convert( 'abc' )
|
129 |
+
self.assertEqual( stream.wrapped.write.call_args, (('abc',), {}) )
|
130 |
+
|
131 |
+
def testWriteAndConvertStripsAllValidAnsi(self):
|
132 |
+
stream = AnsiToWin32(Mock())
|
133 |
+
stream.call_win32 = Mock()
|
134 |
+
data = [
|
135 |
+
'abc\033[mdef',
|
136 |
+
'abc\033[0mdef',
|
137 |
+
'abc\033[2mdef',
|
138 |
+
'abc\033[02mdef',
|
139 |
+
'abc\033[002mdef',
|
140 |
+
'abc\033[40mdef',
|
141 |
+
'abc\033[040mdef',
|
142 |
+
'abc\033[0;1mdef',
|
143 |
+
'abc\033[40;50mdef',
|
144 |
+
'abc\033[50;30;40mdef',
|
145 |
+
'abc\033[Adef',
|
146 |
+
'abc\033[0Gdef',
|
147 |
+
'abc\033[1;20;128Hdef',
|
148 |
+
]
|
149 |
+
for datum in data:
|
150 |
+
stream.wrapped.write.reset_mock()
|
151 |
+
stream.write_and_convert( datum )
|
152 |
+
self.assertEqual(
|
153 |
+
[args[0] for args in stream.wrapped.write.call_args_list],
|
154 |
+
[ ('abc',), ('def',) ]
|
155 |
+
)
|
156 |
+
|
157 |
+
def testWriteAndConvertSkipsEmptySnippets(self):
|
158 |
+
stream = AnsiToWin32(Mock())
|
159 |
+
stream.call_win32 = Mock()
|
160 |
+
stream.write_and_convert( '\033[40m\033[41m' )
|
161 |
+
self.assertFalse( stream.wrapped.write.called )
|
162 |
+
|
163 |
+
def testWriteAndConvertCallsWin32WithParamsAndCommand(self):
|
164 |
+
stream = AnsiToWin32(Mock())
|
165 |
+
stream.convert = True
|
166 |
+
stream.call_win32 = Mock()
|
167 |
+
stream.extract_params = Mock(return_value='params')
|
168 |
+
data = {
|
169 |
+
'abc\033[adef': ('a', 'params'),
|
170 |
+
'abc\033[;;bdef': ('b', 'params'),
|
171 |
+
'abc\033[0cdef': ('c', 'params'),
|
172 |
+
'abc\033[;;0;;Gdef': ('G', 'params'),
|
173 |
+
'abc\033[1;20;128Hdef': ('H', 'params'),
|
174 |
+
}
|
175 |
+
for datum, expected in data.items():
|
176 |
+
stream.call_win32.reset_mock()
|
177 |
+
stream.write_and_convert( datum )
|
178 |
+
self.assertEqual( stream.call_win32.call_args[0], expected )
|
179 |
+
|
180 |
+
def test_reset_all_shouldnt_raise_on_closed_orig_stdout(self):
|
181 |
+
stream = StringIO()
|
182 |
+
converter = AnsiToWin32(stream)
|
183 |
+
stream.close()
|
184 |
+
|
185 |
+
converter.reset_all()
|
186 |
+
|
187 |
+
def test_wrap_shouldnt_raise_on_closed_orig_stdout(self):
|
188 |
+
stream = StringIO()
|
189 |
+
stream.close()
|
190 |
+
with \
|
191 |
+
patch("colorama.ansitowin32.os.name", "nt"), \
|
192 |
+
patch("colorama.ansitowin32.winapi_test", lambda: True):
|
193 |
+
converter = AnsiToWin32(stream)
|
194 |
+
self.assertTrue(converter.strip)
|
195 |
+
self.assertFalse(converter.convert)
|
196 |
+
|
197 |
+
def test_wrap_shouldnt_raise_on_missing_closed_attr(self):
|
198 |
+
with \
|
199 |
+
patch("colorama.ansitowin32.os.name", "nt"), \
|
200 |
+
patch("colorama.ansitowin32.winapi_test", lambda: True):
|
201 |
+
converter = AnsiToWin32(object())
|
202 |
+
self.assertTrue(converter.strip)
|
203 |
+
self.assertFalse(converter.convert)
|
204 |
+
|
205 |
+
def testExtractParams(self):
|
206 |
+
stream = AnsiToWin32(Mock())
|
207 |
+
data = {
|
208 |
+
'': (0,),
|
209 |
+
';;': (0,),
|
210 |
+
'2': (2,),
|
211 |
+
';;002;;': (2,),
|
212 |
+
'0;1': (0, 1),
|
213 |
+
';;003;;456;;': (3, 456),
|
214 |
+
'11;22;33;44;55': (11, 22, 33, 44, 55),
|
215 |
+
}
|
216 |
+
for datum, expected in data.items():
|
217 |
+
self.assertEqual(stream.extract_params('m', datum), expected)
|
218 |
+
|
219 |
+
def testCallWin32UsesLookup(self):
|
220 |
+
listener = Mock()
|
221 |
+
stream = AnsiToWin32(listener)
|
222 |
+
stream.win32_calls = {
|
223 |
+
1: (lambda *_, **__: listener(11),),
|
224 |
+
2: (lambda *_, **__: listener(22),),
|
225 |
+
3: (lambda *_, **__: listener(33),),
|
226 |
+
}
|
227 |
+
stream.call_win32('m', (3, 1, 99, 2))
|
228 |
+
self.assertEqual(
|
229 |
+
[a[0][0] for a in listener.call_args_list],
|
230 |
+
[33, 11, 22] )
|
231 |
+
|
232 |
+
def test_osc_codes(self):
|
233 |
+
mockStdout = Mock()
|
234 |
+
stream = AnsiToWin32(mockStdout, convert=True)
|
235 |
+
with patch('colorama.ansitowin32.winterm') as winterm:
|
236 |
+
data = [
|
237 |
+
'\033]0\x07', # missing arguments
|
238 |
+
'\033]0;foo\x08', # wrong OSC command
|
239 |
+
'\033]0;colorama_test_title\x07', # should work
|
240 |
+
'\033]1;colorama_test_title\x07', # wrong set command
|
241 |
+
'\033]2;colorama_test_title\x07', # should work
|
242 |
+
'\033]' + ';' * 64 + '\x08', # see issue #247
|
243 |
+
]
|
244 |
+
for code in data:
|
245 |
+
stream.write(code)
|
246 |
+
self.assertEqual(winterm.set_title.call_count, 2)
|
247 |
+
|
248 |
+
def test_native_windows_ansi(self):
|
249 |
+
with ExitStack() as stack:
|
250 |
+
def p(a, b):
|
251 |
+
stack.enter_context(patch(a, b, create=True))
|
252 |
+
# Pretend to be on Windows
|
253 |
+
p("colorama.ansitowin32.os.name", "nt")
|
254 |
+
p("colorama.ansitowin32.winapi_test", lambda: True)
|
255 |
+
p("colorama.win32.winapi_test", lambda: True)
|
256 |
+
p("colorama.winterm.win32.windll", "non-None")
|
257 |
+
p("colorama.winterm.get_osfhandle", lambda _: 1234)
|
258 |
+
|
259 |
+
# Pretend that our mock stream has native ANSI support
|
260 |
+
p(
|
261 |
+
"colorama.winterm.win32.GetConsoleMode",
|
262 |
+
lambda _: ENABLE_VIRTUAL_TERMINAL_PROCESSING,
|
263 |
+
)
|
264 |
+
SetConsoleMode = Mock()
|
265 |
+
p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode)
|
266 |
+
|
267 |
+
stdout = Mock()
|
268 |
+
stdout.closed = False
|
269 |
+
stdout.isatty.return_value = True
|
270 |
+
stdout.fileno.return_value = 1
|
271 |
+
|
272 |
+
# Our fake console says it has native vt support, so AnsiToWin32 should
|
273 |
+
# enable that support and do nothing else.
|
274 |
+
stream = AnsiToWin32(stdout)
|
275 |
+
SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING)
|
276 |
+
self.assertFalse(stream.strip)
|
277 |
+
self.assertFalse(stream.convert)
|
278 |
+
self.assertFalse(stream.should_wrap())
|
279 |
+
|
280 |
+
# Now let's pretend we're on an old Windows console, that doesn't have
|
281 |
+
# native ANSI support.
|
282 |
+
p("colorama.winterm.win32.GetConsoleMode", lambda _: 0)
|
283 |
+
SetConsoleMode = Mock()
|
284 |
+
p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode)
|
285 |
+
|
286 |
+
stream = AnsiToWin32(stdout)
|
287 |
+
SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING)
|
288 |
+
self.assertTrue(stream.strip)
|
289 |
+
self.assertTrue(stream.convert)
|
290 |
+
self.assertTrue(stream.should_wrap())
|
291 |
+
|
292 |
+
|
293 |
+
if __name__ == '__main__':
|
294 |
+
main()
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/initialise_test.py
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import sys
|
3 |
+
from unittest import TestCase, main, skipUnless
|
4 |
+
|
5 |
+
try:
|
6 |
+
from unittest.mock import patch, Mock
|
7 |
+
except ImportError:
|
8 |
+
from mock import patch, Mock
|
9 |
+
|
10 |
+
from ..ansitowin32 import StreamWrapper
|
11 |
+
from ..initialise import init, just_fix_windows_console, _wipe_internal_state_for_tests
|
12 |
+
from .utils import osname, replace_by
|
13 |
+
|
14 |
+
orig_stdout = sys.stdout
|
15 |
+
orig_stderr = sys.stderr
|
16 |
+
|
17 |
+
|
18 |
+
class InitTest(TestCase):
|
19 |
+
|
20 |
+
@skipUnless(sys.stdout.isatty(), "sys.stdout is not a tty")
|
21 |
+
def setUp(self):
|
22 |
+
# sanity check
|
23 |
+
self.assertNotWrapped()
|
24 |
+
|
25 |
+
def tearDown(self):
|
26 |
+
_wipe_internal_state_for_tests()
|
27 |
+
sys.stdout = orig_stdout
|
28 |
+
sys.stderr = orig_stderr
|
29 |
+
|
30 |
+
def assertWrapped(self):
|
31 |
+
self.assertIsNot(sys.stdout, orig_stdout, 'stdout should be wrapped')
|
32 |
+
self.assertIsNot(sys.stderr, orig_stderr, 'stderr should be wrapped')
|
33 |
+
self.assertTrue(isinstance(sys.stdout, StreamWrapper),
|
34 |
+
'bad stdout wrapper')
|
35 |
+
self.assertTrue(isinstance(sys.stderr, StreamWrapper),
|
36 |
+
'bad stderr wrapper')
|
37 |
+
|
38 |
+
def assertNotWrapped(self):
|
39 |
+
self.assertIs(sys.stdout, orig_stdout, 'stdout should not be wrapped')
|
40 |
+
self.assertIs(sys.stderr, orig_stderr, 'stderr should not be wrapped')
|
41 |
+
|
42 |
+
@patch('colorama.initialise.reset_all')
|
43 |
+
@patch('colorama.ansitowin32.winapi_test', lambda *_: True)
|
44 |
+
@patch('colorama.ansitowin32.enable_vt_processing', lambda *_: False)
|
45 |
+
def testInitWrapsOnWindows(self, _):
|
46 |
+
with osname("nt"):
|
47 |
+
init()
|
48 |
+
self.assertWrapped()
|
49 |
+
|
50 |
+
@patch('colorama.initialise.reset_all')
|
51 |
+
@patch('colorama.ansitowin32.winapi_test', lambda *_: False)
|
52 |
+
def testInitDoesntWrapOnEmulatedWindows(self, _):
|
53 |
+
with osname("nt"):
|
54 |
+
init()
|
55 |
+
self.assertNotWrapped()
|
56 |
+
|
57 |
+
def testInitDoesntWrapOnNonWindows(self):
|
58 |
+
with osname("posix"):
|
59 |
+
init()
|
60 |
+
self.assertNotWrapped()
|
61 |
+
|
62 |
+
def testInitDoesntWrapIfNone(self):
|
63 |
+
with replace_by(None):
|
64 |
+
init()
|
65 |
+
# We can't use assertNotWrapped here because replace_by(None)
|
66 |
+
# changes stdout/stderr already.
|
67 |
+
self.assertIsNone(sys.stdout)
|
68 |
+
self.assertIsNone(sys.stderr)
|
69 |
+
|
70 |
+
def testInitAutoresetOnWrapsOnAllPlatforms(self):
|
71 |
+
with osname("posix"):
|
72 |
+
init(autoreset=True)
|
73 |
+
self.assertWrapped()
|
74 |
+
|
75 |
+
def testInitWrapOffDoesntWrapOnWindows(self):
|
76 |
+
with osname("nt"):
|
77 |
+
init(wrap=False)
|
78 |
+
self.assertNotWrapped()
|
79 |
+
|
80 |
+
def testInitWrapOffIncompatibleWithAutoresetOn(self):
|
81 |
+
self.assertRaises(ValueError, lambda: init(autoreset=True, wrap=False))
|
82 |
+
|
83 |
+
@patch('colorama.win32.SetConsoleTextAttribute')
|
84 |
+
@patch('colorama.initialise.AnsiToWin32')
|
85 |
+
def testAutoResetPassedOn(self, mockATW32, _):
|
86 |
+
with osname("nt"):
|
87 |
+
init(autoreset=True)
|
88 |
+
self.assertEqual(len(mockATW32.call_args_list), 2)
|
89 |
+
self.assertEqual(mockATW32.call_args_list[1][1]['autoreset'], True)
|
90 |
+
self.assertEqual(mockATW32.call_args_list[0][1]['autoreset'], True)
|
91 |
+
|
92 |
+
@patch('colorama.initialise.AnsiToWin32')
|
93 |
+
def testAutoResetChangeable(self, mockATW32):
|
94 |
+
with osname("nt"):
|
95 |
+
init()
|
96 |
+
|
97 |
+
init(autoreset=True)
|
98 |
+
self.assertEqual(len(mockATW32.call_args_list), 4)
|
99 |
+
self.assertEqual(mockATW32.call_args_list[2][1]['autoreset'], True)
|
100 |
+
self.assertEqual(mockATW32.call_args_list[3][1]['autoreset'], True)
|
101 |
+
|
102 |
+
init()
|
103 |
+
self.assertEqual(len(mockATW32.call_args_list), 6)
|
104 |
+
self.assertEqual(
|
105 |
+
mockATW32.call_args_list[4][1]['autoreset'], False)
|
106 |
+
self.assertEqual(
|
107 |
+
mockATW32.call_args_list[5][1]['autoreset'], False)
|
108 |
+
|
109 |
+
|
110 |
+
@patch('colorama.initialise.atexit.register')
|
111 |
+
def testAtexitRegisteredOnlyOnce(self, mockRegister):
|
112 |
+
init()
|
113 |
+
self.assertTrue(mockRegister.called)
|
114 |
+
mockRegister.reset_mock()
|
115 |
+
init()
|
116 |
+
self.assertFalse(mockRegister.called)
|
117 |
+
|
118 |
+
|
119 |
+
class JustFixWindowsConsoleTest(TestCase):
|
120 |
+
def _reset(self):
|
121 |
+
_wipe_internal_state_for_tests()
|
122 |
+
sys.stdout = orig_stdout
|
123 |
+
sys.stderr = orig_stderr
|
124 |
+
|
125 |
+
def tearDown(self):
|
126 |
+
self._reset()
|
127 |
+
|
128 |
+
@patch("colorama.ansitowin32.winapi_test", lambda: True)
|
129 |
+
def testJustFixWindowsConsole(self):
|
130 |
+
if sys.platform != "win32":
|
131 |
+
# just_fix_windows_console should be a no-op
|
132 |
+
just_fix_windows_console()
|
133 |
+
self.assertIs(sys.stdout, orig_stdout)
|
134 |
+
self.assertIs(sys.stderr, orig_stderr)
|
135 |
+
else:
|
136 |
+
def fake_std():
|
137 |
+
# Emulate stdout=not a tty, stderr=tty
|
138 |
+
# to check that we handle both cases correctly
|
139 |
+
stdout = Mock()
|
140 |
+
stdout.closed = False
|
141 |
+
stdout.isatty.return_value = False
|
142 |
+
stdout.fileno.return_value = 1
|
143 |
+
sys.stdout = stdout
|
144 |
+
|
145 |
+
stderr = Mock()
|
146 |
+
stderr.closed = False
|
147 |
+
stderr.isatty.return_value = True
|
148 |
+
stderr.fileno.return_value = 2
|
149 |
+
sys.stderr = stderr
|
150 |
+
|
151 |
+
for native_ansi in [False, True]:
|
152 |
+
with patch(
|
153 |
+
'colorama.ansitowin32.enable_vt_processing',
|
154 |
+
lambda *_: native_ansi
|
155 |
+
):
|
156 |
+
self._reset()
|
157 |
+
fake_std()
|
158 |
+
|
159 |
+
# Regular single-call test
|
160 |
+
prev_stdout = sys.stdout
|
161 |
+
prev_stderr = sys.stderr
|
162 |
+
just_fix_windows_console()
|
163 |
+
self.assertIs(sys.stdout, prev_stdout)
|
164 |
+
if native_ansi:
|
165 |
+
self.assertIs(sys.stderr, prev_stderr)
|
166 |
+
else:
|
167 |
+
self.assertIsNot(sys.stderr, prev_stderr)
|
168 |
+
|
169 |
+
# second call without resetting is always a no-op
|
170 |
+
prev_stdout = sys.stdout
|
171 |
+
prev_stderr = sys.stderr
|
172 |
+
just_fix_windows_console()
|
173 |
+
self.assertIs(sys.stdout, prev_stdout)
|
174 |
+
self.assertIs(sys.stderr, prev_stderr)
|
175 |
+
|
176 |
+
self._reset()
|
177 |
+
fake_std()
|
178 |
+
|
179 |
+
# If init() runs first, just_fix_windows_console should be a no-op
|
180 |
+
init()
|
181 |
+
prev_stdout = sys.stdout
|
182 |
+
prev_stderr = sys.stderr
|
183 |
+
just_fix_windows_console()
|
184 |
+
self.assertIs(prev_stdout, sys.stdout)
|
185 |
+
self.assertIs(prev_stderr, sys.stderr)
|
186 |
+
|
187 |
+
|
188 |
+
if __name__ == '__main__':
|
189 |
+
main()
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/isatty_test.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import sys
|
3 |
+
from unittest import TestCase, main
|
4 |
+
|
5 |
+
from ..ansitowin32 import StreamWrapper, AnsiToWin32
|
6 |
+
from .utils import pycharm, replace_by, replace_original_by, StreamTTY, StreamNonTTY
|
7 |
+
|
8 |
+
|
9 |
+
def is_a_tty(stream):
|
10 |
+
return StreamWrapper(stream, None).isatty()
|
11 |
+
|
12 |
+
class IsattyTest(TestCase):
|
13 |
+
|
14 |
+
def test_TTY(self):
|
15 |
+
tty = StreamTTY()
|
16 |
+
self.assertTrue(is_a_tty(tty))
|
17 |
+
with pycharm():
|
18 |
+
self.assertTrue(is_a_tty(tty))
|
19 |
+
|
20 |
+
def test_nonTTY(self):
|
21 |
+
non_tty = StreamNonTTY()
|
22 |
+
self.assertFalse(is_a_tty(non_tty))
|
23 |
+
with pycharm():
|
24 |
+
self.assertFalse(is_a_tty(non_tty))
|
25 |
+
|
26 |
+
def test_withPycharm(self):
|
27 |
+
with pycharm():
|
28 |
+
self.assertTrue(is_a_tty(sys.stderr))
|
29 |
+
self.assertTrue(is_a_tty(sys.stdout))
|
30 |
+
|
31 |
+
def test_withPycharmTTYOverride(self):
|
32 |
+
tty = StreamTTY()
|
33 |
+
with pycharm(), replace_by(tty):
|
34 |
+
self.assertTrue(is_a_tty(tty))
|
35 |
+
|
36 |
+
def test_withPycharmNonTTYOverride(self):
|
37 |
+
non_tty = StreamNonTTY()
|
38 |
+
with pycharm(), replace_by(non_tty):
|
39 |
+
self.assertFalse(is_a_tty(non_tty))
|
40 |
+
|
41 |
+
def test_withPycharmNoneOverride(self):
|
42 |
+
with pycharm():
|
43 |
+
with replace_by(None), replace_original_by(None):
|
44 |
+
self.assertFalse(is_a_tty(None))
|
45 |
+
self.assertFalse(is_a_tty(StreamNonTTY()))
|
46 |
+
self.assertTrue(is_a_tty(StreamTTY()))
|
47 |
+
|
48 |
+
def test_withPycharmStreamWrapped(self):
|
49 |
+
with pycharm():
|
50 |
+
self.assertTrue(AnsiToWin32(StreamTTY()).stream.isatty())
|
51 |
+
self.assertFalse(AnsiToWin32(StreamNonTTY()).stream.isatty())
|
52 |
+
self.assertTrue(AnsiToWin32(sys.stdout).stream.isatty())
|
53 |
+
self.assertTrue(AnsiToWin32(sys.stderr).stream.isatty())
|
54 |
+
|
55 |
+
|
56 |
+
if __name__ == '__main__':
|
57 |
+
main()
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/utils.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
from contextlib import contextmanager
|
3 |
+
from io import StringIO
|
4 |
+
import sys
|
5 |
+
import os
|
6 |
+
|
7 |
+
|
8 |
+
class StreamTTY(StringIO):
|
9 |
+
def isatty(self):
|
10 |
+
return True
|
11 |
+
|
12 |
+
class StreamNonTTY(StringIO):
|
13 |
+
def isatty(self):
|
14 |
+
return False
|
15 |
+
|
16 |
+
@contextmanager
|
17 |
+
def osname(name):
|
18 |
+
orig = os.name
|
19 |
+
os.name = name
|
20 |
+
yield
|
21 |
+
os.name = orig
|
22 |
+
|
23 |
+
@contextmanager
|
24 |
+
def replace_by(stream):
|
25 |
+
orig_stdout = sys.stdout
|
26 |
+
orig_stderr = sys.stderr
|
27 |
+
sys.stdout = stream
|
28 |
+
sys.stderr = stream
|
29 |
+
yield
|
30 |
+
sys.stdout = orig_stdout
|
31 |
+
sys.stderr = orig_stderr
|
32 |
+
|
33 |
+
@contextmanager
|
34 |
+
def replace_original_by(stream):
|
35 |
+
orig_stdout = sys.__stdout__
|
36 |
+
orig_stderr = sys.__stderr__
|
37 |
+
sys.__stdout__ = stream
|
38 |
+
sys.__stderr__ = stream
|
39 |
+
yield
|
40 |
+
sys.__stdout__ = orig_stdout
|
41 |
+
sys.__stderr__ = orig_stderr
|
42 |
+
|
43 |
+
@contextmanager
|
44 |
+
def pycharm():
|
45 |
+
os.environ["PYCHARM_HOSTED"] = "1"
|
46 |
+
non_tty = StreamNonTTY()
|
47 |
+
with replace_by(non_tty), replace_original_by(non_tty):
|
48 |
+
yield
|
49 |
+
del os.environ["PYCHARM_HOSTED"]
|
llmeval-env/lib/python3.10/site-packages/colorama/tests/winterm_test.py
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import sys
|
3 |
+
from unittest import TestCase, main, skipUnless
|
4 |
+
|
5 |
+
try:
|
6 |
+
from unittest.mock import Mock, patch
|
7 |
+
except ImportError:
|
8 |
+
from mock import Mock, patch
|
9 |
+
|
10 |
+
from ..winterm import WinColor, WinStyle, WinTerm
|
11 |
+
|
12 |
+
|
13 |
+
class WinTermTest(TestCase):
|
14 |
+
|
15 |
+
@patch('colorama.winterm.win32')
|
16 |
+
def testInit(self, mockWin32):
|
17 |
+
mockAttr = Mock()
|
18 |
+
mockAttr.wAttributes = 7 + 6 * 16 + 8
|
19 |
+
mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
|
20 |
+
term = WinTerm()
|
21 |
+
self.assertEqual(term._fore, 7)
|
22 |
+
self.assertEqual(term._back, 6)
|
23 |
+
self.assertEqual(term._style, 8)
|
24 |
+
|
25 |
+
@skipUnless(sys.platform.startswith("win"), "requires Windows")
|
26 |
+
def testGetAttrs(self):
|
27 |
+
term = WinTerm()
|
28 |
+
|
29 |
+
term._fore = 0
|
30 |
+
term._back = 0
|
31 |
+
term._style = 0
|
32 |
+
self.assertEqual(term.get_attrs(), 0)
|
33 |
+
|
34 |
+
term._fore = WinColor.YELLOW
|
35 |
+
self.assertEqual(term.get_attrs(), WinColor.YELLOW)
|
36 |
+
|
37 |
+
term._back = WinColor.MAGENTA
|
38 |
+
self.assertEqual(
|
39 |
+
term.get_attrs(),
|
40 |
+
WinColor.YELLOW + WinColor.MAGENTA * 16)
|
41 |
+
|
42 |
+
term._style = WinStyle.BRIGHT
|
43 |
+
self.assertEqual(
|
44 |
+
term.get_attrs(),
|
45 |
+
WinColor.YELLOW + WinColor.MAGENTA * 16 + WinStyle.BRIGHT)
|
46 |
+
|
47 |
+
@patch('colorama.winterm.win32')
|
48 |
+
def testResetAll(self, mockWin32):
|
49 |
+
mockAttr = Mock()
|
50 |
+
mockAttr.wAttributes = 1 + 2 * 16 + 8
|
51 |
+
mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
|
52 |
+
term = WinTerm()
|
53 |
+
|
54 |
+
term.set_console = Mock()
|
55 |
+
term._fore = -1
|
56 |
+
term._back = -1
|
57 |
+
term._style = -1
|
58 |
+
|
59 |
+
term.reset_all()
|
60 |
+
|
61 |
+
self.assertEqual(term._fore, 1)
|
62 |
+
self.assertEqual(term._back, 2)
|
63 |
+
self.assertEqual(term._style, 8)
|
64 |
+
self.assertEqual(term.set_console.called, True)
|
65 |
+
|
66 |
+
@skipUnless(sys.platform.startswith("win"), "requires Windows")
|
67 |
+
def testFore(self):
|
68 |
+
term = WinTerm()
|
69 |
+
term.set_console = Mock()
|
70 |
+
term._fore = 0
|
71 |
+
|
72 |
+
term.fore(5)
|
73 |
+
|
74 |
+
self.assertEqual(term._fore, 5)
|
75 |
+
self.assertEqual(term.set_console.called, True)
|
76 |
+
|
77 |
+
@skipUnless(sys.platform.startswith("win"), "requires Windows")
|
78 |
+
def testBack(self):
|
79 |
+
term = WinTerm()
|
80 |
+
term.set_console = Mock()
|
81 |
+
term._back = 0
|
82 |
+
|
83 |
+
term.back(5)
|
84 |
+
|
85 |
+
self.assertEqual(term._back, 5)
|
86 |
+
self.assertEqual(term.set_console.called, True)
|
87 |
+
|
88 |
+
@skipUnless(sys.platform.startswith("win"), "requires Windows")
|
89 |
+
def testStyle(self):
|
90 |
+
term = WinTerm()
|
91 |
+
term.set_console = Mock()
|
92 |
+
term._style = 0
|
93 |
+
|
94 |
+
term.style(22)
|
95 |
+
|
96 |
+
self.assertEqual(term._style, 22)
|
97 |
+
self.assertEqual(term.set_console.called, True)
|
98 |
+
|
99 |
+
@patch('colorama.winterm.win32')
|
100 |
+
def testSetConsole(self, mockWin32):
|
101 |
+
mockAttr = Mock()
|
102 |
+
mockAttr.wAttributes = 0
|
103 |
+
mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
|
104 |
+
term = WinTerm()
|
105 |
+
term.windll = Mock()
|
106 |
+
|
107 |
+
term.set_console()
|
108 |
+
|
109 |
+
self.assertEqual(
|
110 |
+
mockWin32.SetConsoleTextAttribute.call_args,
|
111 |
+
((mockWin32.STDOUT, term.get_attrs()), {})
|
112 |
+
)
|
113 |
+
|
114 |
+
@patch('colorama.winterm.win32')
|
115 |
+
def testSetConsoleOnStderr(self, mockWin32):
|
116 |
+
mockAttr = Mock()
|
117 |
+
mockAttr.wAttributes = 0
|
118 |
+
mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
|
119 |
+
term = WinTerm()
|
120 |
+
term.windll = Mock()
|
121 |
+
|
122 |
+
term.set_console(on_stderr=True)
|
123 |
+
|
124 |
+
self.assertEqual(
|
125 |
+
mockWin32.SetConsoleTextAttribute.call_args,
|
126 |
+
((mockWin32.STDERR, term.get_attrs()), {})
|
127 |
+
)
|
128 |
+
|
129 |
+
|
130 |
+
if __name__ == '__main__':
|
131 |
+
main()
|
llmeval-env/lib/python3.10/site-packages/colorama/win32.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
|
3 |
+
# from winbase.h
|
4 |
+
STDOUT = -11
|
5 |
+
STDERR = -12
|
6 |
+
|
7 |
+
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
|
8 |
+
|
9 |
+
try:
|
10 |
+
import ctypes
|
11 |
+
from ctypes import LibraryLoader
|
12 |
+
windll = LibraryLoader(ctypes.WinDLL)
|
13 |
+
from ctypes import wintypes
|
14 |
+
except (AttributeError, ImportError):
|
15 |
+
windll = None
|
16 |
+
SetConsoleTextAttribute = lambda *_: None
|
17 |
+
winapi_test = lambda *_: None
|
18 |
+
else:
|
19 |
+
from ctypes import byref, Structure, c_char, POINTER
|
20 |
+
|
21 |
+
COORD = wintypes._COORD
|
22 |
+
|
23 |
+
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
|
24 |
+
"""struct in wincon.h."""
|
25 |
+
_fields_ = [
|
26 |
+
("dwSize", COORD),
|
27 |
+
("dwCursorPosition", COORD),
|
28 |
+
("wAttributes", wintypes.WORD),
|
29 |
+
("srWindow", wintypes.SMALL_RECT),
|
30 |
+
("dwMaximumWindowSize", COORD),
|
31 |
+
]
|
32 |
+
def __str__(self):
|
33 |
+
return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (
|
34 |
+
self.dwSize.Y, self.dwSize.X
|
35 |
+
, self.dwCursorPosition.Y, self.dwCursorPosition.X
|
36 |
+
, self.wAttributes
|
37 |
+
, self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right
|
38 |
+
, self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X
|
39 |
+
)
|
40 |
+
|
41 |
+
_GetStdHandle = windll.kernel32.GetStdHandle
|
42 |
+
_GetStdHandle.argtypes = [
|
43 |
+
wintypes.DWORD,
|
44 |
+
]
|
45 |
+
_GetStdHandle.restype = wintypes.HANDLE
|
46 |
+
|
47 |
+
_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
|
48 |
+
_GetConsoleScreenBufferInfo.argtypes = [
|
49 |
+
wintypes.HANDLE,
|
50 |
+
POINTER(CONSOLE_SCREEN_BUFFER_INFO),
|
51 |
+
]
|
52 |
+
_GetConsoleScreenBufferInfo.restype = wintypes.BOOL
|
53 |
+
|
54 |
+
_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
|
55 |
+
_SetConsoleTextAttribute.argtypes = [
|
56 |
+
wintypes.HANDLE,
|
57 |
+
wintypes.WORD,
|
58 |
+
]
|
59 |
+
_SetConsoleTextAttribute.restype = wintypes.BOOL
|
60 |
+
|
61 |
+
_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition
|
62 |
+
_SetConsoleCursorPosition.argtypes = [
|
63 |
+
wintypes.HANDLE,
|
64 |
+
COORD,
|
65 |
+
]
|
66 |
+
_SetConsoleCursorPosition.restype = wintypes.BOOL
|
67 |
+
|
68 |
+
_FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA
|
69 |
+
_FillConsoleOutputCharacterA.argtypes = [
|
70 |
+
wintypes.HANDLE,
|
71 |
+
c_char,
|
72 |
+
wintypes.DWORD,
|
73 |
+
COORD,
|
74 |
+
POINTER(wintypes.DWORD),
|
75 |
+
]
|
76 |
+
_FillConsoleOutputCharacterA.restype = wintypes.BOOL
|
77 |
+
|
78 |
+
_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
|
79 |
+
_FillConsoleOutputAttribute.argtypes = [
|
80 |
+
wintypes.HANDLE,
|
81 |
+
wintypes.WORD,
|
82 |
+
wintypes.DWORD,
|
83 |
+
COORD,
|
84 |
+
POINTER(wintypes.DWORD),
|
85 |
+
]
|
86 |
+
_FillConsoleOutputAttribute.restype = wintypes.BOOL
|
87 |
+
|
88 |
+
_SetConsoleTitleW = windll.kernel32.SetConsoleTitleW
|
89 |
+
_SetConsoleTitleW.argtypes = [
|
90 |
+
wintypes.LPCWSTR
|
91 |
+
]
|
92 |
+
_SetConsoleTitleW.restype = wintypes.BOOL
|
93 |
+
|
94 |
+
_GetConsoleMode = windll.kernel32.GetConsoleMode
|
95 |
+
_GetConsoleMode.argtypes = [
|
96 |
+
wintypes.HANDLE,
|
97 |
+
POINTER(wintypes.DWORD)
|
98 |
+
]
|
99 |
+
_GetConsoleMode.restype = wintypes.BOOL
|
100 |
+
|
101 |
+
_SetConsoleMode = windll.kernel32.SetConsoleMode
|
102 |
+
_SetConsoleMode.argtypes = [
|
103 |
+
wintypes.HANDLE,
|
104 |
+
wintypes.DWORD
|
105 |
+
]
|
106 |
+
_SetConsoleMode.restype = wintypes.BOOL
|
107 |
+
|
108 |
+
def _winapi_test(handle):
|
109 |
+
csbi = CONSOLE_SCREEN_BUFFER_INFO()
|
110 |
+
success = _GetConsoleScreenBufferInfo(
|
111 |
+
handle, byref(csbi))
|
112 |
+
return bool(success)
|
113 |
+
|
114 |
+
def winapi_test():
|
115 |
+
return any(_winapi_test(h) for h in
|
116 |
+
(_GetStdHandle(STDOUT), _GetStdHandle(STDERR)))
|
117 |
+
|
118 |
+
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
|
119 |
+
handle = _GetStdHandle(stream_id)
|
120 |
+
csbi = CONSOLE_SCREEN_BUFFER_INFO()
|
121 |
+
success = _GetConsoleScreenBufferInfo(
|
122 |
+
handle, byref(csbi))
|
123 |
+
return csbi
|
124 |
+
|
125 |
+
def SetConsoleTextAttribute(stream_id, attrs):
|
126 |
+
handle = _GetStdHandle(stream_id)
|
127 |
+
return _SetConsoleTextAttribute(handle, attrs)
|
128 |
+
|
129 |
+
def SetConsoleCursorPosition(stream_id, position, adjust=True):
|
130 |
+
position = COORD(*position)
|
131 |
+
# If the position is out of range, do nothing.
|
132 |
+
if position.Y <= 0 or position.X <= 0:
|
133 |
+
return
|
134 |
+
# Adjust for Windows' SetConsoleCursorPosition:
|
135 |
+
# 1. being 0-based, while ANSI is 1-based.
|
136 |
+
# 2. expecting (x,y), while ANSI uses (y,x).
|
137 |
+
adjusted_position = COORD(position.Y - 1, position.X - 1)
|
138 |
+
if adjust:
|
139 |
+
# Adjust for viewport's scroll position
|
140 |
+
sr = GetConsoleScreenBufferInfo(STDOUT).srWindow
|
141 |
+
adjusted_position.Y += sr.Top
|
142 |
+
adjusted_position.X += sr.Left
|
143 |
+
# Resume normal processing
|
144 |
+
handle = _GetStdHandle(stream_id)
|
145 |
+
return _SetConsoleCursorPosition(handle, adjusted_position)
|
146 |
+
|
147 |
+
def FillConsoleOutputCharacter(stream_id, char, length, start):
|
148 |
+
handle = _GetStdHandle(stream_id)
|
149 |
+
char = c_char(char.encode())
|
150 |
+
length = wintypes.DWORD(length)
|
151 |
+
num_written = wintypes.DWORD(0)
|
152 |
+
# Note that this is hard-coded for ANSI (vs wide) bytes.
|
153 |
+
success = _FillConsoleOutputCharacterA(
|
154 |
+
handle, char, length, start, byref(num_written))
|
155 |
+
return num_written.value
|
156 |
+
|
157 |
+
def FillConsoleOutputAttribute(stream_id, attr, length, start):
|
158 |
+
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
|
159 |
+
handle = _GetStdHandle(stream_id)
|
160 |
+
attribute = wintypes.WORD(attr)
|
161 |
+
length = wintypes.DWORD(length)
|
162 |
+
num_written = wintypes.DWORD(0)
|
163 |
+
# Note that this is hard-coded for ANSI (vs wide) bytes.
|
164 |
+
return _FillConsoleOutputAttribute(
|
165 |
+
handle, attribute, length, start, byref(num_written))
|
166 |
+
|
167 |
+
def SetConsoleTitle(title):
|
168 |
+
return _SetConsoleTitleW(title)
|
169 |
+
|
170 |
+
def GetConsoleMode(handle):
|
171 |
+
mode = wintypes.DWORD()
|
172 |
+
success = _GetConsoleMode(handle, byref(mode))
|
173 |
+
if not success:
|
174 |
+
raise ctypes.WinError()
|
175 |
+
return mode.value
|
176 |
+
|
177 |
+
def SetConsoleMode(handle, mode):
|
178 |
+
success = _SetConsoleMode(handle, mode)
|
179 |
+
if not success:
|
180 |
+
raise ctypes.WinError()
|
llmeval-env/lib/python3.10/site-packages/colorama/winterm.py
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
try:
|
3 |
+
from msvcrt import get_osfhandle
|
4 |
+
except ImportError:
|
5 |
+
def get_osfhandle(_):
|
6 |
+
raise OSError("This isn't windows!")
|
7 |
+
|
8 |
+
|
9 |
+
from . import win32
|
10 |
+
|
11 |
+
# from wincon.h
|
12 |
+
class WinColor(object):
|
13 |
+
BLACK = 0
|
14 |
+
BLUE = 1
|
15 |
+
GREEN = 2
|
16 |
+
CYAN = 3
|
17 |
+
RED = 4
|
18 |
+
MAGENTA = 5
|
19 |
+
YELLOW = 6
|
20 |
+
GREY = 7
|
21 |
+
|
22 |
+
# from wincon.h
|
23 |
+
class WinStyle(object):
|
24 |
+
NORMAL = 0x00 # dim text, dim background
|
25 |
+
BRIGHT = 0x08 # bright text, dim background
|
26 |
+
BRIGHT_BACKGROUND = 0x80 # dim text, bright background
|
27 |
+
|
28 |
+
class WinTerm(object):
|
29 |
+
|
30 |
+
def __init__(self):
|
31 |
+
self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
|
32 |
+
self.set_attrs(self._default)
|
33 |
+
self._default_fore = self._fore
|
34 |
+
self._default_back = self._back
|
35 |
+
self._default_style = self._style
|
36 |
+
# In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style.
|
37 |
+
# So that LIGHT_EX colors and BRIGHT style do not clobber each other,
|
38 |
+
# we track them separately, since LIGHT_EX is overwritten by Fore/Back
|
39 |
+
# and BRIGHT is overwritten by Style codes.
|
40 |
+
self._light = 0
|
41 |
+
|
42 |
+
def get_attrs(self):
|
43 |
+
return self._fore + self._back * 16 + (self._style | self._light)
|
44 |
+
|
45 |
+
def set_attrs(self, value):
|
46 |
+
self._fore = value & 7
|
47 |
+
self._back = (value >> 4) & 7
|
48 |
+
self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND)
|
49 |
+
|
50 |
+
def reset_all(self, on_stderr=None):
|
51 |
+
self.set_attrs(self._default)
|
52 |
+
self.set_console(attrs=self._default)
|
53 |
+
self._light = 0
|
54 |
+
|
55 |
+
def fore(self, fore=None, light=False, on_stderr=False):
|
56 |
+
if fore is None:
|
57 |
+
fore = self._default_fore
|
58 |
+
self._fore = fore
|
59 |
+
# Emulate LIGHT_EX with BRIGHT Style
|
60 |
+
if light:
|
61 |
+
self._light |= WinStyle.BRIGHT
|
62 |
+
else:
|
63 |
+
self._light &= ~WinStyle.BRIGHT
|
64 |
+
self.set_console(on_stderr=on_stderr)
|
65 |
+
|
66 |
+
def back(self, back=None, light=False, on_stderr=False):
|
67 |
+
if back is None:
|
68 |
+
back = self._default_back
|
69 |
+
self._back = back
|
70 |
+
# Emulate LIGHT_EX with BRIGHT_BACKGROUND Style
|
71 |
+
if light:
|
72 |
+
self._light |= WinStyle.BRIGHT_BACKGROUND
|
73 |
+
else:
|
74 |
+
self._light &= ~WinStyle.BRIGHT_BACKGROUND
|
75 |
+
self.set_console(on_stderr=on_stderr)
|
76 |
+
|
77 |
+
def style(self, style=None, on_stderr=False):
|
78 |
+
if style is None:
|
79 |
+
style = self._default_style
|
80 |
+
self._style = style
|
81 |
+
self.set_console(on_stderr=on_stderr)
|
82 |
+
|
83 |
+
def set_console(self, attrs=None, on_stderr=False):
|
84 |
+
if attrs is None:
|
85 |
+
attrs = self.get_attrs()
|
86 |
+
handle = win32.STDOUT
|
87 |
+
if on_stderr:
|
88 |
+
handle = win32.STDERR
|
89 |
+
win32.SetConsoleTextAttribute(handle, attrs)
|
90 |
+
|
91 |
+
def get_position(self, handle):
|
92 |
+
position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition
|
93 |
+
# Because Windows coordinates are 0-based,
|
94 |
+
# and win32.SetConsoleCursorPosition expects 1-based.
|
95 |
+
position.X += 1
|
96 |
+
position.Y += 1
|
97 |
+
return position
|
98 |
+
|
99 |
+
def set_cursor_position(self, position=None, on_stderr=False):
|
100 |
+
if position is None:
|
101 |
+
# I'm not currently tracking the position, so there is no default.
|
102 |
+
# position = self.get_position()
|
103 |
+
return
|
104 |
+
handle = win32.STDOUT
|
105 |
+
if on_stderr:
|
106 |
+
handle = win32.STDERR
|
107 |
+
win32.SetConsoleCursorPosition(handle, position)
|
108 |
+
|
109 |
+
def cursor_adjust(self, x, y, on_stderr=False):
|
110 |
+
handle = win32.STDOUT
|
111 |
+
if on_stderr:
|
112 |
+
handle = win32.STDERR
|
113 |
+
position = self.get_position(handle)
|
114 |
+
adjusted_position = (position.Y + y, position.X + x)
|
115 |
+
win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False)
|
116 |
+
|
117 |
+
def erase_screen(self, mode=0, on_stderr=False):
|
118 |
+
# 0 should clear from the cursor to the end of the screen.
|
119 |
+
# 1 should clear from the cursor to the beginning of the screen.
|
120 |
+
# 2 should clear the entire screen, and move cursor to (1,1)
|
121 |
+
handle = win32.STDOUT
|
122 |
+
if on_stderr:
|
123 |
+
handle = win32.STDERR
|
124 |
+
csbi = win32.GetConsoleScreenBufferInfo(handle)
|
125 |
+
# get the number of character cells in the current buffer
|
126 |
+
cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y
|
127 |
+
# get number of character cells before current cursor position
|
128 |
+
cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X
|
129 |
+
if mode == 0:
|
130 |
+
from_coord = csbi.dwCursorPosition
|
131 |
+
cells_to_erase = cells_in_screen - cells_before_cursor
|
132 |
+
elif mode == 1:
|
133 |
+
from_coord = win32.COORD(0, 0)
|
134 |
+
cells_to_erase = cells_before_cursor
|
135 |
+
elif mode == 2:
|
136 |
+
from_coord = win32.COORD(0, 0)
|
137 |
+
cells_to_erase = cells_in_screen
|
138 |
+
else:
|
139 |
+
# invalid mode
|
140 |
+
return
|
141 |
+
# fill the entire screen with blanks
|
142 |
+
win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
|
143 |
+
# now set the buffer's attributes accordingly
|
144 |
+
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
|
145 |
+
if mode == 2:
|
146 |
+
# put the cursor where needed
|
147 |
+
win32.SetConsoleCursorPosition(handle, (1, 1))
|
148 |
+
|
149 |
+
def erase_line(self, mode=0, on_stderr=False):
|
150 |
+
# 0 should clear from the cursor to the end of the line.
|
151 |
+
# 1 should clear from the cursor to the beginning of the line.
|
152 |
+
# 2 should clear the entire line.
|
153 |
+
handle = win32.STDOUT
|
154 |
+
if on_stderr:
|
155 |
+
handle = win32.STDERR
|
156 |
+
csbi = win32.GetConsoleScreenBufferInfo(handle)
|
157 |
+
if mode == 0:
|
158 |
+
from_coord = csbi.dwCursorPosition
|
159 |
+
cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X
|
160 |
+
elif mode == 1:
|
161 |
+
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
|
162 |
+
cells_to_erase = csbi.dwCursorPosition.X
|
163 |
+
elif mode == 2:
|
164 |
+
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
|
165 |
+
cells_to_erase = csbi.dwSize.X
|
166 |
+
else:
|
167 |
+
# invalid mode
|
168 |
+
return
|
169 |
+
# fill the entire screen with blanks
|
170 |
+
win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
|
171 |
+
# now set the buffer's attributes accordingly
|
172 |
+
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
|
173 |
+
|
174 |
+
def set_title(self, title):
|
175 |
+
win32.SetConsoleTitle(title)
|
176 |
+
|
177 |
+
|
178 |
+
def enable_vt_processing(fd):
|
179 |
+
if win32.windll is None or not win32.winapi_test():
|
180 |
+
return False
|
181 |
+
|
182 |
+
try:
|
183 |
+
handle = get_osfhandle(fd)
|
184 |
+
mode = win32.GetConsoleMode(handle)
|
185 |
+
win32.SetConsoleMode(
|
186 |
+
handle,
|
187 |
+
mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING,
|
188 |
+
)
|
189 |
+
|
190 |
+
mode = win32.GetConsoleMode(handle)
|
191 |
+
if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING:
|
192 |
+
return True
|
193 |
+
# Can get TypeError in testsuite where 'fd' is a Mock()
|
194 |
+
except (OSError, TypeError):
|
195 |
+
return False
|
llmeval-env/lib/python3.10/site-packages/jsonlines/__init__.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Module for the jsonlines data format.
|
3 |
+
"""
|
4 |
+
|
5 |
+
# expose only public api
|
6 |
+
from .jsonlines import (
|
7 |
+
Error,
|
8 |
+
InvalidLineError,
|
9 |
+
Reader,
|
10 |
+
Writer,
|
11 |
+
open,
|
12 |
+
)
|
13 |
+
|
14 |
+
__all__ = [
|
15 |
+
"Error",
|
16 |
+
"InvalidLineError",
|
17 |
+
"Reader",
|
18 |
+
"Writer",
|
19 |
+
"open",
|
20 |
+
]
|
llmeval-env/lib/python3.10/site-packages/jsonlines/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (372 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/jsonlines/__pycache__/jsonlines.cpython-310.pyc
ADDED
Binary file (17 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/jsonlines/jsonlines.py
ADDED
@@ -0,0 +1,665 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
jsonlines implementation
|
3 |
+
"""
|
4 |
+
|
5 |
+
import builtins
|
6 |
+
import codecs
|
7 |
+
import enum
|
8 |
+
import io
|
9 |
+
import json
|
10 |
+
import os
|
11 |
+
import types
|
12 |
+
import typing
|
13 |
+
from typing import (
|
14 |
+
Any,
|
15 |
+
Callable,
|
16 |
+
Dict,
|
17 |
+
Iterable,
|
18 |
+
Iterator,
|
19 |
+
List,
|
20 |
+
Literal,
|
21 |
+
Optional,
|
22 |
+
Tuple,
|
23 |
+
Type,
|
24 |
+
TypeVar,
|
25 |
+
Union,
|
26 |
+
cast,
|
27 |
+
overload,
|
28 |
+
)
|
29 |
+
|
30 |
+
import attr
|
31 |
+
|
32 |
+
orjson: Optional[types.ModuleType]
|
33 |
+
try:
|
34 |
+
import orjson
|
35 |
+
except ImportError:
|
36 |
+
orjson = None
|
37 |
+
|
38 |
+
ujson: Optional[types.ModuleType]
|
39 |
+
try:
|
40 |
+
import ujson
|
41 |
+
except ImportError:
|
42 |
+
ujson = None
|
43 |
+
|
44 |
+
|
45 |
+
VALID_TYPES = {
|
46 |
+
bool,
|
47 |
+
dict,
|
48 |
+
float,
|
49 |
+
int,
|
50 |
+
list,
|
51 |
+
str,
|
52 |
+
}
|
53 |
+
|
54 |
+
# Characters to skip at the beginning of a line. Note: at most one such
|
55 |
+
# character is skipped per line.
|
56 |
+
SKIPPABLE_SINGLE_INITIAL_CHARS = (
|
57 |
+
"\x1e", # RFC7464 text sequence
|
58 |
+
codecs.BOM_UTF8.decode(),
|
59 |
+
)
|
60 |
+
|
61 |
+
|
62 |
+
class DumpsResultConversion(enum.Enum):
|
63 |
+
LeaveAsIs = enum.auto()
|
64 |
+
EncodeToBytes = enum.auto()
|
65 |
+
DecodeToString = enum.auto()
|
66 |
+
|
67 |
+
|
68 |
+
# https://docs.python.org/3/library/functions.html#open
|
69 |
+
Openable = Union[str, bytes, int, os.PathLike]
|
70 |
+
|
71 |
+
LoadsCallable = Callable[[Union[str, bytes]], Any]
|
72 |
+
DumpsCallable = Callable[[Any], Union[str, bytes]]
|
73 |
+
|
74 |
+
# Currently, JSON structures cannot be typed properly:
|
75 |
+
# - https://github.com/python/typing/issues/182
|
76 |
+
# - https://github.com/python/mypy/issues/731
|
77 |
+
JSONCollection = Union[Dict[str, Any], List[Any]]
|
78 |
+
JSONScalar = Union[bool, float, int, str]
|
79 |
+
JSONValue = Union[JSONCollection, JSONScalar]
|
80 |
+
TJSONValue = TypeVar("TJSONValue", bound=JSONValue)
|
81 |
+
|
82 |
+
TRW = TypeVar("TRW", bound="ReaderWriterBase")
|
83 |
+
|
84 |
+
# Default to using the fastest JSON library for reading, falling back to the
|
85 |
+
# standard library (always available) if none are installed.
|
86 |
+
if orjson is not None:
|
87 |
+
default_loads = orjson.loads
|
88 |
+
elif ujson is not None:
|
89 |
+
default_loads = ujson.loads
|
90 |
+
else:
|
91 |
+
default_loads = json.loads
|
92 |
+
|
93 |
+
|
94 |
+
# For writing, use the stdlib. Other packages may be faster but their behaviour
|
95 |
+
# (supported types etc.) and output (whitespace etc.) are not the same as the
|
96 |
+
# stdlib json module, so this should be opt-in via the ‘dumps=’ arg.
|
97 |
+
def default_dumps(obj: Any) -> str:
|
98 |
+
"""
|
99 |
+
Fake ``dumps()`` function to use as a default marker.
|
100 |
+
"""
|
101 |
+
raise NotImplementedError # pragma: no cover
|
102 |
+
|
103 |
+
|
104 |
+
@attr.s(auto_exc=True, auto_attribs=True)
|
105 |
+
class Error(Exception):
|
106 |
+
"""
|
107 |
+
Base error class.
|
108 |
+
"""
|
109 |
+
|
110 |
+
message: str
|
111 |
+
|
112 |
+
|
113 |
+
@attr.s(auto_exc=True, auto_attribs=True, init=False)
|
114 |
+
class InvalidLineError(Error, ValueError):
|
115 |
+
"""
|
116 |
+
Error raised when an invalid line is encountered.
|
117 |
+
|
118 |
+
This happens when the line does not contain valid JSON, or if a
|
119 |
+
specific data type has been requested, and the line contained a
|
120 |
+
different data type.
|
121 |
+
|
122 |
+
The original line itself is stored on the exception instance as the
|
123 |
+
``.line`` attribute, and the line number as ``.lineno``.
|
124 |
+
|
125 |
+
This class subclasses both ``jsonlines.Error`` and the built-in
|
126 |
+
``ValueError``.
|
127 |
+
"""
|
128 |
+
|
129 |
+
#: The invalid line
|
130 |
+
line: Union[str, bytes]
|
131 |
+
|
132 |
+
#: The line number
|
133 |
+
lineno: int
|
134 |
+
|
135 |
+
def __init__(self, message: str, line: Union[str, bytes], lineno: int) -> None:
|
136 |
+
self.line = line.rstrip()
|
137 |
+
self.lineno = lineno
|
138 |
+
super().__init__(f"{message} (line {lineno})")
|
139 |
+
|
140 |
+
|
141 |
+
@attr.s(auto_attribs=True, repr=False)
|
142 |
+
class ReaderWriterBase:
|
143 |
+
"""
|
144 |
+
Base class with shared behaviour for both the reader and writer.
|
145 |
+
"""
|
146 |
+
|
147 |
+
_fp: Union[typing.IO[str], typing.IO[bytes], None] = attr.ib(
|
148 |
+
default=None, init=False
|
149 |
+
)
|
150 |
+
_closed: bool = attr.ib(default=False, init=False)
|
151 |
+
_should_close_fp: bool = attr.ib(default=False, init=False)
|
152 |
+
|
153 |
+
def close(self) -> None:
|
154 |
+
"""
|
155 |
+
Close this reader/writer.
|
156 |
+
|
157 |
+
This closes the underlying file if that file has been opened by
|
158 |
+
this reader/writer. When an already opened file-like object was
|
159 |
+
provided, the caller is responsible for closing it.
|
160 |
+
"""
|
161 |
+
if self._closed:
|
162 |
+
return
|
163 |
+
self._closed = True
|
164 |
+
if self._fp is not None and self._should_close_fp:
|
165 |
+
self._fp.close()
|
166 |
+
|
167 |
+
def __repr__(self) -> str:
|
168 |
+
cls_name = type(self).__name__
|
169 |
+
wrapped = self._repr_for_wrapped()
|
170 |
+
return f"<jsonlines.{cls_name} at 0x{id(self):x} wrapping {wrapped}>"
|
171 |
+
|
172 |
+
def _repr_for_wrapped(self) -> str:
|
173 |
+
raise NotImplementedError # pragma: no cover
|
174 |
+
|
175 |
+
def __enter__(self: TRW) -> TRW:
|
176 |
+
return self
|
177 |
+
|
178 |
+
def __exit__(
|
179 |
+
self,
|
180 |
+
exc_type: Optional[Type[BaseException]],
|
181 |
+
exc_val: Optional[BaseException],
|
182 |
+
exc_tb: Optional[types.TracebackType],
|
183 |
+
) -> None:
|
184 |
+
self.close()
|
185 |
+
|
186 |
+
|
187 |
+
@attr.s(auto_attribs=True, repr=False)
|
188 |
+
class Reader(ReaderWriterBase):
|
189 |
+
"""
|
190 |
+
Reader for the jsonlines format.
|
191 |
+
|
192 |
+
The first argument must be an iterable that yields JSON encoded
|
193 |
+
strings. Usually this will be a readable file-like object, such as
|
194 |
+
an open file or an ``io.TextIO`` instance, but it can also be
|
195 |
+
something else as long as it yields strings when iterated over.
|
196 |
+
|
197 |
+
Instances are iterable and can be used as a context manager.
|
198 |
+
|
199 |
+
The `loads` argument can be used to replace the standard json
|
200 |
+
decoder. If specified, it must be a callable that accepts a
|
201 |
+
(unicode) string and returns the decoded object.
|
202 |
+
|
203 |
+
:param file_or_iterable: file-like object or iterable yielding lines as
|
204 |
+
strings
|
205 |
+
:param loads: custom json decoder callable
|
206 |
+
"""
|
207 |
+
|
208 |
+
_file_or_iterable: Union[
|
209 |
+
typing.IO[str], typing.IO[bytes], Iterable[Union[str, bytes]]
|
210 |
+
]
|
211 |
+
_line_iter: Iterator[Tuple[int, Union[bytes, str]]] = attr.ib(init=False)
|
212 |
+
_loads: LoadsCallable = attr.ib(default=default_loads, kw_only=True)
|
213 |
+
|
214 |
+
def __attrs_post_init__(self) -> None:
|
215 |
+
if isinstance(self._file_or_iterable, io.IOBase):
|
216 |
+
self._fp = cast(
|
217 |
+
Union[typing.IO[str], typing.IO[bytes]],
|
218 |
+
self._file_or_iterable,
|
219 |
+
)
|
220 |
+
|
221 |
+
self._line_iter = enumerate(self._file_or_iterable, 1)
|
222 |
+
|
223 |
+
# No type specified, None not allowed
|
224 |
+
@overload
|
225 |
+
def read(
|
226 |
+
self,
|
227 |
+
*,
|
228 |
+
type: Literal[None] = ...,
|
229 |
+
allow_none: Literal[False] = ...,
|
230 |
+
skip_empty: bool = ...,
|
231 |
+
) -> JSONValue:
|
232 |
+
... # pragma: no cover
|
233 |
+
|
234 |
+
# No type specified, None allowed
|
235 |
+
@overload
|
236 |
+
def read(
|
237 |
+
self,
|
238 |
+
*,
|
239 |
+
type: Literal[None] = ...,
|
240 |
+
allow_none: Literal[True],
|
241 |
+
skip_empty: bool = ...,
|
242 |
+
) -> Optional[JSONValue]:
|
243 |
+
... # pragma: no cover
|
244 |
+
|
245 |
+
# Type specified, None not allowed
|
246 |
+
@overload
|
247 |
+
def read(
|
248 |
+
self,
|
249 |
+
*,
|
250 |
+
type: Type[TJSONValue],
|
251 |
+
allow_none: Literal[False] = ...,
|
252 |
+
skip_empty: bool = ...,
|
253 |
+
) -> TJSONValue:
|
254 |
+
... # pragma: no cover
|
255 |
+
|
256 |
+
# Type specified, None allowed
|
257 |
+
@overload
|
258 |
+
def read(
|
259 |
+
self,
|
260 |
+
*,
|
261 |
+
type: Type[TJSONValue],
|
262 |
+
allow_none: Literal[True],
|
263 |
+
skip_empty: bool = ...,
|
264 |
+
) -> Optional[TJSONValue]:
|
265 |
+
... # pragma: no cover
|
266 |
+
|
267 |
+
# Generic definition
|
268 |
+
@overload
|
269 |
+
def read(
|
270 |
+
self,
|
271 |
+
*,
|
272 |
+
type: Optional[Type[Any]] = ...,
|
273 |
+
allow_none: bool = ...,
|
274 |
+
skip_empty: bool = ...,
|
275 |
+
) -> Optional[JSONValue]:
|
276 |
+
... # pragma: no cover
|
277 |
+
|
278 |
+
def read(
|
279 |
+
self,
|
280 |
+
*,
|
281 |
+
type: Optional[Type[Any]] = None,
|
282 |
+
allow_none: bool = False,
|
283 |
+
skip_empty: bool = False,
|
284 |
+
) -> Optional[JSONValue]:
|
285 |
+
"""
|
286 |
+
Read and decode a line.
|
287 |
+
|
288 |
+
The optional `type` argument specifies the expected data type.
|
289 |
+
Supported types are ``dict``, ``list``, ``str``, ``int``,
|
290 |
+
``float``, and ``bool``. When specified, non-conforming lines
|
291 |
+
result in :py:exc:`InvalidLineError`.
|
292 |
+
|
293 |
+
By default, input lines containing ``null`` (in JSON) are
|
294 |
+
considered invalid, and will cause :py:exc:`InvalidLineError`.
|
295 |
+
The `allow_none` argument can be used to change this behaviour,
|
296 |
+
in which case ``None`` will be returned instead.
|
297 |
+
|
298 |
+
If `skip_empty` is set to ``True``, empty lines and lines
|
299 |
+
containing only whitespace are silently skipped.
|
300 |
+
"""
|
301 |
+
if self._closed:
|
302 |
+
raise RuntimeError("reader is closed")
|
303 |
+
if type is not None and type not in VALID_TYPES:
|
304 |
+
raise ValueError("invalid type specified")
|
305 |
+
|
306 |
+
try:
|
307 |
+
lineno, line = next(self._line_iter)
|
308 |
+
while skip_empty and not line.rstrip():
|
309 |
+
lineno, line = next(self._line_iter)
|
310 |
+
except StopIteration:
|
311 |
+
raise EOFError from None
|
312 |
+
|
313 |
+
if isinstance(line, bytes):
|
314 |
+
try:
|
315 |
+
line = line.decode("utf-8")
|
316 |
+
except UnicodeDecodeError as orig_exc:
|
317 |
+
exc = InvalidLineError(
|
318 |
+
f"line is not valid utf-8: {orig_exc}", line, lineno
|
319 |
+
)
|
320 |
+
raise exc from orig_exc
|
321 |
+
|
322 |
+
if line.startswith(SKIPPABLE_SINGLE_INITIAL_CHARS):
|
323 |
+
line = line[1:]
|
324 |
+
|
325 |
+
try:
|
326 |
+
value: JSONValue = self._loads(line)
|
327 |
+
except ValueError as orig_exc:
|
328 |
+
exc = InvalidLineError(
|
329 |
+
f"line contains invalid json: {orig_exc}", line, lineno
|
330 |
+
)
|
331 |
+
raise exc from orig_exc
|
332 |
+
|
333 |
+
if value is None:
|
334 |
+
if allow_none:
|
335 |
+
return None
|
336 |
+
raise InvalidLineError("line contains null value", line, lineno)
|
337 |
+
|
338 |
+
if type is not None:
|
339 |
+
valid = isinstance(value, type)
|
340 |
+
if type is int and isinstance(value, bool):
|
341 |
+
# isinstance() is not sufficient, since bool is an int subclass
|
342 |
+
valid = False
|
343 |
+
if not valid:
|
344 |
+
raise InvalidLineError(
|
345 |
+
"line does not match requested type", line, lineno
|
346 |
+
)
|
347 |
+
|
348 |
+
return value
|
349 |
+
|
350 |
+
# No type specified, None not allowed
|
351 |
+
@overload
|
352 |
+
def iter(
|
353 |
+
self,
|
354 |
+
*,
|
355 |
+
type: Literal[None] = ...,
|
356 |
+
allow_none: Literal[False] = ...,
|
357 |
+
skip_empty: bool = ...,
|
358 |
+
skip_invalid: bool = ...,
|
359 |
+
) -> Iterator[JSONValue]:
|
360 |
+
... # pragma: no cover
|
361 |
+
|
362 |
+
# No type specified, None allowed
|
363 |
+
@overload
|
364 |
+
def iter(
|
365 |
+
self,
|
366 |
+
*,
|
367 |
+
type: Literal[None] = ...,
|
368 |
+
allow_none: Literal[True],
|
369 |
+
skip_empty: bool = ...,
|
370 |
+
skip_invalid: bool = ...,
|
371 |
+
) -> Iterator[JSONValue]:
|
372 |
+
... # pragma: no cover
|
373 |
+
|
374 |
+
# Type specified, None not allowed
|
375 |
+
@overload
|
376 |
+
def iter(
|
377 |
+
self,
|
378 |
+
*,
|
379 |
+
type: Type[TJSONValue],
|
380 |
+
allow_none: Literal[False] = ...,
|
381 |
+
skip_empty: bool = ...,
|
382 |
+
skip_invalid: bool = ...,
|
383 |
+
) -> Iterator[TJSONValue]:
|
384 |
+
... # pragma: no cover
|
385 |
+
|
386 |
+
# Type specified, None allowed
|
387 |
+
@overload
|
388 |
+
def iter(
|
389 |
+
self,
|
390 |
+
*,
|
391 |
+
type: Type[TJSONValue],
|
392 |
+
allow_none: Literal[True],
|
393 |
+
skip_empty: bool = ...,
|
394 |
+
skip_invalid: bool = ...,
|
395 |
+
) -> Iterator[Optional[TJSONValue]]:
|
396 |
+
... # pragma: no cover
|
397 |
+
|
398 |
+
# Generic definition
|
399 |
+
@overload
|
400 |
+
def iter(
|
401 |
+
self,
|
402 |
+
*,
|
403 |
+
type: Optional[Type[TJSONValue]] = ...,
|
404 |
+
allow_none: bool = ...,
|
405 |
+
skip_empty: bool = ...,
|
406 |
+
skip_invalid: bool = ...,
|
407 |
+
) -> Iterator[Optional[TJSONValue]]:
|
408 |
+
... # pragma: no cover
|
409 |
+
|
410 |
+
def iter(
|
411 |
+
self,
|
412 |
+
type: Optional[Type[Any]] = None,
|
413 |
+
allow_none: bool = False,
|
414 |
+
skip_empty: bool = False,
|
415 |
+
skip_invalid: bool = False,
|
416 |
+
) -> Iterator[Optional[JSONValue]]:
|
417 |
+
"""
|
418 |
+
Iterate over all lines.
|
419 |
+
|
420 |
+
This is the iterator equivalent to repeatedly calling
|
421 |
+
:py:meth:`~Reader.read()`. If no arguments are specified, this
|
422 |
+
is the same as directly iterating over this :py:class:`Reader`
|
423 |
+
instance.
|
424 |
+
|
425 |
+
When `skip_invalid` is set to ``True``, invalid lines will be
|
426 |
+
silently ignored.
|
427 |
+
|
428 |
+
See :py:meth:`~Reader.read()` for a description of the other
|
429 |
+
arguments.
|
430 |
+
"""
|
431 |
+
try:
|
432 |
+
while True:
|
433 |
+
try:
|
434 |
+
yield self.read(
|
435 |
+
type=type, allow_none=allow_none, skip_empty=skip_empty
|
436 |
+
)
|
437 |
+
except InvalidLineError:
|
438 |
+
if not skip_invalid:
|
439 |
+
raise
|
440 |
+
except EOFError:
|
441 |
+
pass
|
442 |
+
|
443 |
+
def __iter__(self) -> Iterator[Any]:
|
444 |
+
"""
|
445 |
+
See :py:meth:`~Reader.iter()`.
|
446 |
+
"""
|
447 |
+
return self.iter()
|
448 |
+
|
449 |
+
def _repr_for_wrapped(self) -> str:
|
450 |
+
if self._fp is not None:
|
451 |
+
return repr_for_fp(self._fp)
|
452 |
+
class_name = type(self._file_or_iterable).__name__
|
453 |
+
return f"<{class_name} at 0x{id(self._file_or_iterable):x}>"
|
454 |
+
|
455 |
+
|
456 |
+
@attr.s(auto_attribs=True, repr=False)
|
457 |
+
class Writer(ReaderWriterBase):
|
458 |
+
"""
|
459 |
+
Writer for the jsonlines format.
|
460 |
+
|
461 |
+
Instances can be used as a context manager.
|
462 |
+
|
463 |
+
The `fp` argument must be a file-like object with a ``.write()``
|
464 |
+
method accepting either text (unicode) or bytes.
|
465 |
+
|
466 |
+
The `compact` argument can be used to to produce smaller output.
|
467 |
+
|
468 |
+
The `sort_keys` argument can be used to sort keys in json objects,
|
469 |
+
and will produce deterministic output.
|
470 |
+
|
471 |
+
For more control, provide a a custom encoder callable using the
|
472 |
+
`dumps` argument. The callable must produce (unicode) string output.
|
473 |
+
If specified, the `compact` and `sort` arguments will be ignored.
|
474 |
+
|
475 |
+
When the `flush` argument is set to ``True``, the writer will call
|
476 |
+
``fp.flush()`` after each written line.
|
477 |
+
|
478 |
+
:param fp: writable file-like object
|
479 |
+
:param compact: whether to use a compact output format
|
480 |
+
:param sort_keys: whether to sort object keys
|
481 |
+
:param dumps: custom encoder callable
|
482 |
+
:param flush: whether to flush the file-like object after writing each line
|
483 |
+
"""
|
484 |
+
|
485 |
+
_fp: Union[typing.IO[str], typing.IO[bytes]] = attr.ib(default=None)
|
486 |
+
_fp_is_binary: bool = attr.ib(default=False, init=False)
|
487 |
+
_compact: bool = attr.ib(default=False, kw_only=True)
|
488 |
+
_sort_keys: bool = attr.ib(default=False, kw_only=True)
|
489 |
+
_flush: bool = attr.ib(default=False, kw_only=True)
|
490 |
+
_dumps: DumpsCallable = attr.ib(default=default_dumps, kw_only=True)
|
491 |
+
_dumps_result_conversion: DumpsResultConversion = attr.ib(
|
492 |
+
default=DumpsResultConversion.LeaveAsIs, init=False
|
493 |
+
)
|
494 |
+
|
495 |
+
def __attrs_post_init__(self) -> None:
|
496 |
+
if isinstance(self._fp, io.TextIOBase):
|
497 |
+
self._fp_is_binary = False
|
498 |
+
elif isinstance(self._fp, io.IOBase):
|
499 |
+
self._fp_is_binary = True
|
500 |
+
else:
|
501 |
+
try:
|
502 |
+
self._fp.write("") # type: ignore[call-overload]
|
503 |
+
except TypeError:
|
504 |
+
self._fp_is_binary = True
|
505 |
+
else:
|
506 |
+
self._fp_is_binary = False
|
507 |
+
|
508 |
+
if self._dumps is default_dumps:
|
509 |
+
self._dumps = json.JSONEncoder(
|
510 |
+
ensure_ascii=False,
|
511 |
+
separators=(",", ":") if self._compact else (", ", ": "),
|
512 |
+
sort_keys=self._sort_keys,
|
513 |
+
).encode
|
514 |
+
|
515 |
+
# Detect if str-to-bytes conversion (or vice versa) is needed for the
|
516 |
+
# combination of this file-like object and the used dumps() callable.
|
517 |
+
# This avoids checking this for each .write(). Note that this
|
518 |
+
# deliberately does not support ‘dynamic’ return types that depend on
|
519 |
+
# input and dump options, like simplejson on Python 2 in some cases.
|
520 |
+
sample_dumps_result = self._dumps({})
|
521 |
+
if isinstance(sample_dumps_result, str) and self._fp_is_binary:
|
522 |
+
self._dumps_result_conversion = DumpsResultConversion.EncodeToBytes
|
523 |
+
elif isinstance(sample_dumps_result, bytes) and not self._fp_is_binary:
|
524 |
+
self._dumps_result_conversion = DumpsResultConversion.DecodeToString
|
525 |
+
|
526 |
+
def write(self, obj: Any) -> int:
|
527 |
+
"""
|
528 |
+
Encode and write a single object.
|
529 |
+
|
530 |
+
:param obj: the object to encode and write
|
531 |
+
:return: number of characters or bytes written
|
532 |
+
"""
|
533 |
+
if self._closed:
|
534 |
+
raise RuntimeError("writer is closed")
|
535 |
+
|
536 |
+
line = self._dumps(obj)
|
537 |
+
|
538 |
+
# This handles either str or bytes, but the type checker does not know
|
539 |
+
# that this code always passes the right type of arguments.
|
540 |
+
if self._dumps_result_conversion == DumpsResultConversion.EncodeToBytes:
|
541 |
+
line = line.encode() # type: ignore[union-attr]
|
542 |
+
elif self._dumps_result_conversion == DumpsResultConversion.DecodeToString:
|
543 |
+
line = line.decode() # type: ignore[union-attr]
|
544 |
+
|
545 |
+
fp = self._fp
|
546 |
+
fp.write(line) # type: ignore[arg-type]
|
547 |
+
fp.write(b"\n" if self._fp_is_binary else "\n") # type: ignore[call-overload]
|
548 |
+
|
549 |
+
if self._flush:
|
550 |
+
fp.flush()
|
551 |
+
|
552 |
+
return len(line) + 1 # including newline
|
553 |
+
|
554 |
+
def write_all(self, iterable: Iterable[Any]) -> int:
|
555 |
+
"""
|
556 |
+
Encode and write multiple objects.
|
557 |
+
|
558 |
+
:param iterable: an iterable of objects
|
559 |
+
:return: number of characters or bytes written
|
560 |
+
"""
|
561 |
+
return sum(self.write(obj) for obj in iterable)
|
562 |
+
|
563 |
+
def _repr_for_wrapped(self) -> str:
|
564 |
+
return repr_for_fp(self._fp)
|
565 |
+
|
566 |
+
|
567 |
+
@overload
|
568 |
+
def open(
|
569 |
+
file: Openable,
|
570 |
+
mode: Literal["r"] = ...,
|
571 |
+
*,
|
572 |
+
loads: Optional[LoadsCallable] = ...,
|
573 |
+
) -> Reader:
|
574 |
+
... # pragma: no cover
|
575 |
+
|
576 |
+
|
577 |
+
@overload
|
578 |
+
def open(
|
579 |
+
file: Openable,
|
580 |
+
mode: Literal["w", "a", "x"],
|
581 |
+
*,
|
582 |
+
dumps: Optional[DumpsCallable] = ...,
|
583 |
+
compact: Optional[bool] = ...,
|
584 |
+
sort_keys: Optional[bool] = ...,
|
585 |
+
flush: Optional[bool] = ...,
|
586 |
+
) -> Writer:
|
587 |
+
... # pragma: no cover
|
588 |
+
|
589 |
+
|
590 |
+
@overload
|
591 |
+
def open(
|
592 |
+
file: Openable,
|
593 |
+
mode: str = ...,
|
594 |
+
*,
|
595 |
+
loads: Optional[LoadsCallable] = ...,
|
596 |
+
dumps: Optional[DumpsCallable] = ...,
|
597 |
+
compact: Optional[bool] = ...,
|
598 |
+
sort_keys: Optional[bool] = ...,
|
599 |
+
flush: Optional[bool] = ...,
|
600 |
+
) -> Union[Reader, Writer]:
|
601 |
+
... # pragma: no cover
|
602 |
+
|
603 |
+
|
604 |
+
def open(
|
605 |
+
file: Openable,
|
606 |
+
mode: str = "r",
|
607 |
+
*,
|
608 |
+
loads: Optional[LoadsCallable] = None,
|
609 |
+
dumps: Optional[DumpsCallable] = None,
|
610 |
+
compact: Optional[bool] = None,
|
611 |
+
sort_keys: Optional[bool] = None,
|
612 |
+
flush: Optional[bool] = None,
|
613 |
+
) -> Union[Reader, Writer]:
|
614 |
+
"""
|
615 |
+
Open a jsonlines file for reading or writing.
|
616 |
+
|
617 |
+
This is a convenience function to open a file and wrap it in either a
|
618 |
+
:py:class:`Reader` or :py:class:`Writer` instance, depending on the
|
619 |
+
specified `mode`.
|
620 |
+
|
621 |
+
Additional keyword arguments will be passed on to the reader and writer;
|
622 |
+
see their documentation for available options.
|
623 |
+
|
624 |
+
The resulting reader or writer must be closed after use by the
|
625 |
+
caller, which will also close the opened file. This can be done by
|
626 |
+
calling ``.close()``, but the easiest way to ensure proper resource
|
627 |
+
finalisation is to use a ``with`` block (context manager), e.g.
|
628 |
+
|
629 |
+
::
|
630 |
+
|
631 |
+
with jsonlines.open('out.jsonl', mode='w') as writer:
|
632 |
+
writer.write(...)
|
633 |
+
|
634 |
+
:param file: name or ‘path-like object’ of the file to open
|
635 |
+
:param mode: whether to open the file for reading (``r``),
|
636 |
+
writing (``w``), appending (``a``), or exclusive creation (``x``).
|
637 |
+
"""
|
638 |
+
if mode not in {"r", "w", "a", "x"}:
|
639 |
+
raise ValueError("'mode' must be either 'r', 'w', 'a', or 'x'")
|
640 |
+
|
641 |
+
cls = Reader if mode == "r" else Writer
|
642 |
+
encoding = "utf-8-sig" if mode == "r" else "utf-8"
|
643 |
+
fp = builtins.open(file, mode=mode + "t", encoding=encoding)
|
644 |
+
kwargs = dict(
|
645 |
+
loads=loads,
|
646 |
+
dumps=dumps,
|
647 |
+
compact=compact,
|
648 |
+
sort_keys=sort_keys,
|
649 |
+
flush=flush,
|
650 |
+
)
|
651 |
+
kwargs = {key: value for key, value in kwargs.items() if value is not None}
|
652 |
+
instance: Union[Reader, Writer] = cls(fp, **kwargs)
|
653 |
+
instance._should_close_fp = True
|
654 |
+
return instance
|
655 |
+
|
656 |
+
|
657 |
+
def repr_for_fp(fp: typing.IO[Any]) -> str:
|
658 |
+
"""
|
659 |
+
Helper to make a useful repr() for a file-like object.
|
660 |
+
"""
|
661 |
+
name = getattr(fp, "name", None)
|
662 |
+
if name is not None:
|
663 |
+
return repr(name)
|
664 |
+
else:
|
665 |
+
return repr(fp)
|
llmeval-env/lib/python3.10/site-packages/jsonlines/py.typed
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/psutil/_psbsd.py
ADDED
@@ -0,0 +1,977 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""FreeBSD, OpenBSD and NetBSD platforms implementation."""
|
6 |
+
|
7 |
+
import contextlib
|
8 |
+
import errno
|
9 |
+
import functools
|
10 |
+
import os
|
11 |
+
from collections import defaultdict
|
12 |
+
from collections import namedtuple
|
13 |
+
from xml.etree import ElementTree
|
14 |
+
|
15 |
+
from . import _common
|
16 |
+
from . import _psposix
|
17 |
+
from . import _psutil_bsd as cext
|
18 |
+
from . import _psutil_posix as cext_posix
|
19 |
+
from ._common import FREEBSD
|
20 |
+
from ._common import NETBSD
|
21 |
+
from ._common import OPENBSD
|
22 |
+
from ._common import AccessDenied
|
23 |
+
from ._common import NoSuchProcess
|
24 |
+
from ._common import ZombieProcess
|
25 |
+
from ._common import conn_tmap
|
26 |
+
from ._common import conn_to_ntuple
|
27 |
+
from ._common import debug
|
28 |
+
from ._common import memoize
|
29 |
+
from ._common import memoize_when_activated
|
30 |
+
from ._common import usage_percent
|
31 |
+
from ._compat import FileNotFoundError
|
32 |
+
from ._compat import PermissionError
|
33 |
+
from ._compat import ProcessLookupError
|
34 |
+
from ._compat import which
|
35 |
+
|
36 |
+
|
37 |
+
__extra__all__ = []
|
38 |
+
|
39 |
+
|
40 |
+
# =====================================================================
|
41 |
+
# --- globals
|
42 |
+
# =====================================================================
|
43 |
+
|
44 |
+
|
45 |
+
if FREEBSD:
|
46 |
+
PROC_STATUSES = {
|
47 |
+
cext.SIDL: _common.STATUS_IDLE,
|
48 |
+
cext.SRUN: _common.STATUS_RUNNING,
|
49 |
+
cext.SSLEEP: _common.STATUS_SLEEPING,
|
50 |
+
cext.SSTOP: _common.STATUS_STOPPED,
|
51 |
+
cext.SZOMB: _common.STATUS_ZOMBIE,
|
52 |
+
cext.SWAIT: _common.STATUS_WAITING,
|
53 |
+
cext.SLOCK: _common.STATUS_LOCKED,
|
54 |
+
}
|
55 |
+
elif OPENBSD:
|
56 |
+
PROC_STATUSES = {
|
57 |
+
cext.SIDL: _common.STATUS_IDLE,
|
58 |
+
cext.SSLEEP: _common.STATUS_SLEEPING,
|
59 |
+
cext.SSTOP: _common.STATUS_STOPPED,
|
60 |
+
# According to /usr/include/sys/proc.h SZOMB is unused.
|
61 |
+
# test_zombie_process() shows that SDEAD is the right
|
62 |
+
# equivalent. Also it appears there's no equivalent of
|
63 |
+
# psutil.STATUS_DEAD. SDEAD really means STATUS_ZOMBIE.
|
64 |
+
# cext.SZOMB: _common.STATUS_ZOMBIE,
|
65 |
+
cext.SDEAD: _common.STATUS_ZOMBIE,
|
66 |
+
cext.SZOMB: _common.STATUS_ZOMBIE,
|
67 |
+
# From http://www.eecs.harvard.edu/~margo/cs161/videos/proc.h.txt
|
68 |
+
# OpenBSD has SRUN and SONPROC: SRUN indicates that a process
|
69 |
+
# is runnable but *not* yet running, i.e. is on a run queue.
|
70 |
+
# SONPROC indicates that the process is actually executing on
|
71 |
+
# a CPU, i.e. it is no longer on a run queue.
|
72 |
+
# As such we'll map SRUN to STATUS_WAKING and SONPROC to
|
73 |
+
# STATUS_RUNNING
|
74 |
+
cext.SRUN: _common.STATUS_WAKING,
|
75 |
+
cext.SONPROC: _common.STATUS_RUNNING,
|
76 |
+
}
|
77 |
+
elif NETBSD:
|
78 |
+
PROC_STATUSES = {
|
79 |
+
cext.SIDL: _common.STATUS_IDLE,
|
80 |
+
cext.SSLEEP: _common.STATUS_SLEEPING,
|
81 |
+
cext.SSTOP: _common.STATUS_STOPPED,
|
82 |
+
cext.SZOMB: _common.STATUS_ZOMBIE,
|
83 |
+
cext.SRUN: _common.STATUS_WAKING,
|
84 |
+
cext.SONPROC: _common.STATUS_RUNNING,
|
85 |
+
}
|
86 |
+
|
87 |
+
TCP_STATUSES = {
|
88 |
+
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
|
89 |
+
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
|
90 |
+
cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
|
91 |
+
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
|
92 |
+
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
|
93 |
+
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
|
94 |
+
cext.TCPS_CLOSED: _common.CONN_CLOSE,
|
95 |
+
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
96 |
+
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
|
97 |
+
cext.TCPS_LISTEN: _common.CONN_LISTEN,
|
98 |
+
cext.TCPS_CLOSING: _common.CONN_CLOSING,
|
99 |
+
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
100 |
+
}
|
101 |
+
|
102 |
+
PAGESIZE = cext_posix.getpagesize()
|
103 |
+
AF_LINK = cext_posix.AF_LINK
|
104 |
+
|
105 |
+
HAS_PER_CPU_TIMES = hasattr(cext, "per_cpu_times")
|
106 |
+
HAS_PROC_NUM_THREADS = hasattr(cext, "proc_num_threads")
|
107 |
+
HAS_PROC_OPEN_FILES = hasattr(cext, 'proc_open_files')
|
108 |
+
HAS_PROC_NUM_FDS = hasattr(cext, 'proc_num_fds')
|
109 |
+
|
110 |
+
kinfo_proc_map = dict(
|
111 |
+
ppid=0,
|
112 |
+
status=1,
|
113 |
+
real_uid=2,
|
114 |
+
effective_uid=3,
|
115 |
+
saved_uid=4,
|
116 |
+
real_gid=5,
|
117 |
+
effective_gid=6,
|
118 |
+
saved_gid=7,
|
119 |
+
ttynr=8,
|
120 |
+
create_time=9,
|
121 |
+
ctx_switches_vol=10,
|
122 |
+
ctx_switches_unvol=11,
|
123 |
+
read_io_count=12,
|
124 |
+
write_io_count=13,
|
125 |
+
user_time=14,
|
126 |
+
sys_time=15,
|
127 |
+
ch_user_time=16,
|
128 |
+
ch_sys_time=17,
|
129 |
+
rss=18,
|
130 |
+
vms=19,
|
131 |
+
memtext=20,
|
132 |
+
memdata=21,
|
133 |
+
memstack=22,
|
134 |
+
cpunum=23,
|
135 |
+
name=24,
|
136 |
+
)
|
137 |
+
|
138 |
+
|
139 |
+
# =====================================================================
|
140 |
+
# --- named tuples
|
141 |
+
# =====================================================================
|
142 |
+
|
143 |
+
|
144 |
+
# fmt: off
|
145 |
+
# psutil.virtual_memory()
|
146 |
+
svmem = namedtuple(
|
147 |
+
'svmem', ['total', 'available', 'percent', 'used', 'free',
|
148 |
+
'active', 'inactive', 'buffers', 'cached', 'shared', 'wired'])
|
149 |
+
# psutil.cpu_times()
|
150 |
+
scputimes = namedtuple(
|
151 |
+
'scputimes', ['user', 'nice', 'system', 'idle', 'irq'])
|
152 |
+
# psutil.Process.memory_info()
|
153 |
+
pmem = namedtuple('pmem', ['rss', 'vms', 'text', 'data', 'stack'])
|
154 |
+
# psutil.Process.memory_full_info()
|
155 |
+
pfullmem = pmem
|
156 |
+
# psutil.Process.cpu_times()
|
157 |
+
pcputimes = namedtuple('pcputimes',
|
158 |
+
['user', 'system', 'children_user', 'children_system'])
|
159 |
+
# psutil.Process.memory_maps(grouped=True)
|
160 |
+
pmmap_grouped = namedtuple(
|
161 |
+
'pmmap_grouped', 'path rss, private, ref_count, shadow_count')
|
162 |
+
# psutil.Process.memory_maps(grouped=False)
|
163 |
+
pmmap_ext = namedtuple(
|
164 |
+
'pmmap_ext', 'addr, perms path rss, private, ref_count, shadow_count')
|
165 |
+
# psutil.disk_io_counters()
|
166 |
+
if FREEBSD:
|
167 |
+
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
|
168 |
+
'read_bytes', 'write_bytes',
|
169 |
+
'read_time', 'write_time',
|
170 |
+
'busy_time'])
|
171 |
+
else:
|
172 |
+
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
|
173 |
+
'read_bytes', 'write_bytes'])
|
174 |
+
# fmt: on
|
175 |
+
|
176 |
+
|
177 |
+
# =====================================================================
|
178 |
+
# --- memory
|
179 |
+
# =====================================================================
|
180 |
+
|
181 |
+
|
182 |
+
def virtual_memory():
|
183 |
+
mem = cext.virtual_mem()
|
184 |
+
if NETBSD:
|
185 |
+
total, free, active, inactive, wired, cached = mem
|
186 |
+
# On NetBSD buffers and shared mem is determined via /proc.
|
187 |
+
# The C ext set them to 0.
|
188 |
+
with open('/proc/meminfo', 'rb') as f:
|
189 |
+
for line in f:
|
190 |
+
if line.startswith(b'Buffers:'):
|
191 |
+
buffers = int(line.split()[1]) * 1024
|
192 |
+
elif line.startswith(b'MemShared:'):
|
193 |
+
shared = int(line.split()[1]) * 1024
|
194 |
+
# Before avail was calculated as (inactive + cached + free),
|
195 |
+
# same as zabbix, but it turned out it could exceed total (see
|
196 |
+
# #2233), so zabbix seems to be wrong. Htop calculates it
|
197 |
+
# differently, and the used value seem more realistic, so let's
|
198 |
+
# match htop.
|
199 |
+
# https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162 # noqa
|
200 |
+
# https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135 # noqa
|
201 |
+
used = active + wired
|
202 |
+
avail = total - used
|
203 |
+
else:
|
204 |
+
total, free, active, inactive, wired, cached, buffers, shared = mem
|
205 |
+
# matches freebsd-memory CLI:
|
206 |
+
# * https://people.freebsd.org/~rse/dist/freebsd-memory
|
207 |
+
# * https://www.cyberciti.biz/files/scripts/freebsd-memory.pl.txt
|
208 |
+
# matches zabbix:
|
209 |
+
# * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143 # noqa
|
210 |
+
avail = inactive + cached + free
|
211 |
+
used = active + wired + cached
|
212 |
+
|
213 |
+
percent = usage_percent((total - avail), total, round_=1)
|
214 |
+
return svmem(
|
215 |
+
total,
|
216 |
+
avail,
|
217 |
+
percent,
|
218 |
+
used,
|
219 |
+
free,
|
220 |
+
active,
|
221 |
+
inactive,
|
222 |
+
buffers,
|
223 |
+
cached,
|
224 |
+
shared,
|
225 |
+
wired,
|
226 |
+
)
|
227 |
+
|
228 |
+
|
229 |
+
def swap_memory():
|
230 |
+
"""System swap memory as (total, used, free, sin, sout) namedtuple."""
|
231 |
+
total, used, free, sin, sout = cext.swap_mem()
|
232 |
+
percent = usage_percent(used, total, round_=1)
|
233 |
+
return _common.sswap(total, used, free, percent, sin, sout)
|
234 |
+
|
235 |
+
|
236 |
+
# =====================================================================
|
237 |
+
# --- CPU
|
238 |
+
# =====================================================================
|
239 |
+
|
240 |
+
|
241 |
+
def cpu_times():
|
242 |
+
"""Return system per-CPU times as a namedtuple."""
|
243 |
+
user, nice, system, idle, irq = cext.cpu_times()
|
244 |
+
return scputimes(user, nice, system, idle, irq)
|
245 |
+
|
246 |
+
|
247 |
+
if HAS_PER_CPU_TIMES:
|
248 |
+
|
249 |
+
def per_cpu_times():
|
250 |
+
"""Return system CPU times as a namedtuple."""
|
251 |
+
ret = []
|
252 |
+
for cpu_t in cext.per_cpu_times():
|
253 |
+
user, nice, system, idle, irq = cpu_t
|
254 |
+
item = scputimes(user, nice, system, idle, irq)
|
255 |
+
ret.append(item)
|
256 |
+
return ret
|
257 |
+
|
258 |
+
else:
|
259 |
+
# XXX
|
260 |
+
# Ok, this is very dirty.
|
261 |
+
# On FreeBSD < 8 we cannot gather per-cpu information, see:
|
262 |
+
# https://github.com/giampaolo/psutil/issues/226
|
263 |
+
# If num cpus > 1, on first call we return single cpu times to avoid a
|
264 |
+
# crash at psutil import time.
|
265 |
+
# Next calls will fail with NotImplementedError
|
266 |
+
def per_cpu_times():
|
267 |
+
"""Return system CPU times as a namedtuple."""
|
268 |
+
if cpu_count_logical() == 1:
|
269 |
+
return [cpu_times()]
|
270 |
+
if per_cpu_times.__called__:
|
271 |
+
msg = "supported only starting from FreeBSD 8"
|
272 |
+
raise NotImplementedError(msg)
|
273 |
+
per_cpu_times.__called__ = True
|
274 |
+
return [cpu_times()]
|
275 |
+
|
276 |
+
per_cpu_times.__called__ = False
|
277 |
+
|
278 |
+
|
279 |
+
def cpu_count_logical():
|
280 |
+
"""Return the number of logical CPUs in the system."""
|
281 |
+
return cext.cpu_count_logical()
|
282 |
+
|
283 |
+
|
284 |
+
if OPENBSD or NETBSD:
|
285 |
+
|
286 |
+
def cpu_count_cores():
|
287 |
+
# OpenBSD and NetBSD do not implement this.
|
288 |
+
return 1 if cpu_count_logical() == 1 else None
|
289 |
+
|
290 |
+
else:
|
291 |
+
|
292 |
+
def cpu_count_cores():
|
293 |
+
"""Return the number of CPU cores in the system."""
|
294 |
+
# From the C module we'll get an XML string similar to this:
|
295 |
+
# http://manpages.ubuntu.com/manpages/precise/man4/smp.4freebsd.html
|
296 |
+
# We may get None in case "sysctl kern.sched.topology_spec"
|
297 |
+
# is not supported on this BSD version, in which case we'll mimic
|
298 |
+
# os.cpu_count() and return None.
|
299 |
+
ret = None
|
300 |
+
s = cext.cpu_topology()
|
301 |
+
if s is not None:
|
302 |
+
# get rid of padding chars appended at the end of the string
|
303 |
+
index = s.rfind("</groups>")
|
304 |
+
if index != -1:
|
305 |
+
s = s[: index + 9]
|
306 |
+
root = ElementTree.fromstring(s)
|
307 |
+
try:
|
308 |
+
ret = len(root.findall('group/children/group/cpu')) or None
|
309 |
+
finally:
|
310 |
+
# needed otherwise it will memleak
|
311 |
+
root.clear()
|
312 |
+
if not ret:
|
313 |
+
# If logical CPUs == 1 it's obvious we' have only 1 core.
|
314 |
+
if cpu_count_logical() == 1:
|
315 |
+
return 1
|
316 |
+
return ret
|
317 |
+
|
318 |
+
|
319 |
+
def cpu_stats():
|
320 |
+
"""Return various CPU stats as a named tuple."""
|
321 |
+
if FREEBSD:
|
322 |
+
# Note: the C ext is returning some metrics we are not exposing:
|
323 |
+
# traps.
|
324 |
+
ctxsw, intrs, soft_intrs, syscalls, traps = cext.cpu_stats()
|
325 |
+
elif NETBSD:
|
326 |
+
# XXX
|
327 |
+
# Note about intrs: the C extension returns 0. intrs
|
328 |
+
# can be determined via /proc/stat; it has the same value as
|
329 |
+
# soft_intrs thought so the kernel is faking it (?).
|
330 |
+
#
|
331 |
+
# Note about syscalls: the C extension always sets it to 0 (?).
|
332 |
+
#
|
333 |
+
# Note: the C ext is returning some metrics we are not exposing:
|
334 |
+
# traps, faults and forks.
|
335 |
+
ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = (
|
336 |
+
cext.cpu_stats()
|
337 |
+
)
|
338 |
+
with open('/proc/stat', 'rb') as f:
|
339 |
+
for line in f:
|
340 |
+
if line.startswith(b'intr'):
|
341 |
+
intrs = int(line.split()[1])
|
342 |
+
elif OPENBSD:
|
343 |
+
# Note: the C ext is returning some metrics we are not exposing:
|
344 |
+
# traps, faults and forks.
|
345 |
+
ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = (
|
346 |
+
cext.cpu_stats()
|
347 |
+
)
|
348 |
+
return _common.scpustats(ctxsw, intrs, soft_intrs, syscalls)
|
349 |
+
|
350 |
+
|
351 |
+
if FREEBSD:
|
352 |
+
|
353 |
+
def cpu_freq():
|
354 |
+
"""Return frequency metrics for CPUs. As of Dec 2018 only
|
355 |
+
CPU 0 appears to be supported by FreeBSD and all other cores
|
356 |
+
match the frequency of CPU 0.
|
357 |
+
"""
|
358 |
+
ret = []
|
359 |
+
num_cpus = cpu_count_logical()
|
360 |
+
for cpu in range(num_cpus):
|
361 |
+
try:
|
362 |
+
current, available_freq = cext.cpu_freq(cpu)
|
363 |
+
except NotImplementedError:
|
364 |
+
continue
|
365 |
+
if available_freq:
|
366 |
+
try:
|
367 |
+
min_freq = int(available_freq.split(" ")[-1].split("/")[0])
|
368 |
+
except (IndexError, ValueError):
|
369 |
+
min_freq = None
|
370 |
+
try:
|
371 |
+
max_freq = int(available_freq.split(" ")[0].split("/")[0])
|
372 |
+
except (IndexError, ValueError):
|
373 |
+
max_freq = None
|
374 |
+
ret.append(_common.scpufreq(current, min_freq, max_freq))
|
375 |
+
return ret
|
376 |
+
|
377 |
+
elif OPENBSD:
|
378 |
+
|
379 |
+
def cpu_freq():
|
380 |
+
curr = float(cext.cpu_freq())
|
381 |
+
return [_common.scpufreq(curr, 0.0, 0.0)]
|
382 |
+
|
383 |
+
|
384 |
+
# =====================================================================
|
385 |
+
# --- disks
|
386 |
+
# =====================================================================
|
387 |
+
|
388 |
+
|
389 |
+
def disk_partitions(all=False):
|
390 |
+
"""Return mounted disk partitions as a list of namedtuples.
|
391 |
+
'all' argument is ignored, see:
|
392 |
+
https://github.com/giampaolo/psutil/issues/906.
|
393 |
+
"""
|
394 |
+
retlist = []
|
395 |
+
partitions = cext.disk_partitions()
|
396 |
+
for partition in partitions:
|
397 |
+
device, mountpoint, fstype, opts = partition
|
398 |
+
maxfile = maxpath = None # set later
|
399 |
+
ntuple = _common.sdiskpart(
|
400 |
+
device, mountpoint, fstype, opts, maxfile, maxpath
|
401 |
+
)
|
402 |
+
retlist.append(ntuple)
|
403 |
+
return retlist
|
404 |
+
|
405 |
+
|
406 |
+
disk_usage = _psposix.disk_usage
|
407 |
+
disk_io_counters = cext.disk_io_counters
|
408 |
+
|
409 |
+
|
410 |
+
# =====================================================================
|
411 |
+
# --- network
|
412 |
+
# =====================================================================
|
413 |
+
|
414 |
+
|
415 |
+
net_io_counters = cext.net_io_counters
|
416 |
+
net_if_addrs = cext_posix.net_if_addrs
|
417 |
+
|
418 |
+
|
419 |
+
def net_if_stats():
|
420 |
+
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
421 |
+
names = net_io_counters().keys()
|
422 |
+
ret = {}
|
423 |
+
for name in names:
|
424 |
+
try:
|
425 |
+
mtu = cext_posix.net_if_mtu(name)
|
426 |
+
flags = cext_posix.net_if_flags(name)
|
427 |
+
duplex, speed = cext_posix.net_if_duplex_speed(name)
|
428 |
+
except OSError as err:
|
429 |
+
# https://github.com/giampaolo/psutil/issues/1279
|
430 |
+
if err.errno != errno.ENODEV:
|
431 |
+
raise
|
432 |
+
else:
|
433 |
+
if hasattr(_common, 'NicDuplex'):
|
434 |
+
duplex = _common.NicDuplex(duplex)
|
435 |
+
output_flags = ','.join(flags)
|
436 |
+
isup = 'running' in flags
|
437 |
+
ret[name] = _common.snicstats(
|
438 |
+
isup, duplex, speed, mtu, output_flags
|
439 |
+
)
|
440 |
+
return ret
|
441 |
+
|
442 |
+
|
443 |
+
def net_connections(kind):
|
444 |
+
"""System-wide network connections."""
|
445 |
+
if kind not in _common.conn_tmap:
|
446 |
+
raise ValueError(
|
447 |
+
"invalid %r kind argument; choose between %s"
|
448 |
+
% (kind, ', '.join([repr(x) for x in conn_tmap]))
|
449 |
+
)
|
450 |
+
families, types = conn_tmap[kind]
|
451 |
+
ret = set()
|
452 |
+
|
453 |
+
if OPENBSD:
|
454 |
+
rawlist = cext.net_connections(-1, families, types)
|
455 |
+
elif NETBSD:
|
456 |
+
rawlist = cext.net_connections(-1, kind)
|
457 |
+
else: # FreeBSD
|
458 |
+
rawlist = cext.net_connections(families, types)
|
459 |
+
|
460 |
+
for item in rawlist:
|
461 |
+
fd, fam, type, laddr, raddr, status, pid = item
|
462 |
+
nt = conn_to_ntuple(
|
463 |
+
fd, fam, type, laddr, raddr, status, TCP_STATUSES, pid
|
464 |
+
)
|
465 |
+
ret.add(nt)
|
466 |
+
return list(ret)
|
467 |
+
|
468 |
+
|
469 |
+
# =====================================================================
|
470 |
+
# --- sensors
|
471 |
+
# =====================================================================
|
472 |
+
|
473 |
+
|
474 |
+
if FREEBSD:
|
475 |
+
|
476 |
+
def sensors_battery():
|
477 |
+
"""Return battery info."""
|
478 |
+
try:
|
479 |
+
percent, minsleft, power_plugged = cext.sensors_battery()
|
480 |
+
except NotImplementedError:
|
481 |
+
# See: https://github.com/giampaolo/psutil/issues/1074
|
482 |
+
return None
|
483 |
+
power_plugged = power_plugged == 1
|
484 |
+
if power_plugged:
|
485 |
+
secsleft = _common.POWER_TIME_UNLIMITED
|
486 |
+
elif minsleft == -1:
|
487 |
+
secsleft = _common.POWER_TIME_UNKNOWN
|
488 |
+
else:
|
489 |
+
secsleft = minsleft * 60
|
490 |
+
return _common.sbattery(percent, secsleft, power_plugged)
|
491 |
+
|
492 |
+
def sensors_temperatures():
|
493 |
+
"""Return CPU cores temperatures if available, else an empty dict."""
|
494 |
+
ret = defaultdict(list)
|
495 |
+
num_cpus = cpu_count_logical()
|
496 |
+
for cpu in range(num_cpus):
|
497 |
+
try:
|
498 |
+
current, high = cext.sensors_cpu_temperature(cpu)
|
499 |
+
if high <= 0:
|
500 |
+
high = None
|
501 |
+
name = "Core %s" % cpu
|
502 |
+
ret["coretemp"].append(
|
503 |
+
_common.shwtemp(name, current, high, high)
|
504 |
+
)
|
505 |
+
except NotImplementedError:
|
506 |
+
pass
|
507 |
+
|
508 |
+
return ret
|
509 |
+
|
510 |
+
|
511 |
+
# =====================================================================
|
512 |
+
# --- other system functions
|
513 |
+
# =====================================================================
|
514 |
+
|
515 |
+
|
516 |
+
def boot_time():
|
517 |
+
"""The system boot time expressed in seconds since the epoch."""
|
518 |
+
return cext.boot_time()
|
519 |
+
|
520 |
+
|
521 |
+
def users():
|
522 |
+
"""Return currently connected users as a list of namedtuples."""
|
523 |
+
retlist = []
|
524 |
+
rawlist = cext.users()
|
525 |
+
for item in rawlist:
|
526 |
+
user, tty, hostname, tstamp, pid = item
|
527 |
+
if pid == -1:
|
528 |
+
assert OPENBSD
|
529 |
+
pid = None
|
530 |
+
if tty == '~':
|
531 |
+
continue # reboot or shutdown
|
532 |
+
nt = _common.suser(user, tty or None, hostname, tstamp, pid)
|
533 |
+
retlist.append(nt)
|
534 |
+
return retlist
|
535 |
+
|
536 |
+
|
537 |
+
# =====================================================================
|
538 |
+
# --- processes
|
539 |
+
# =====================================================================
|
540 |
+
|
541 |
+
|
542 |
+
@memoize
|
543 |
+
def _pid_0_exists():
|
544 |
+
try:
|
545 |
+
Process(0).name()
|
546 |
+
except NoSuchProcess:
|
547 |
+
return False
|
548 |
+
except AccessDenied:
|
549 |
+
return True
|
550 |
+
else:
|
551 |
+
return True
|
552 |
+
|
553 |
+
|
554 |
+
def pids():
|
555 |
+
"""Returns a list of PIDs currently running on the system."""
|
556 |
+
ret = cext.pids()
|
557 |
+
if OPENBSD and (0 not in ret) and _pid_0_exists():
|
558 |
+
# On OpenBSD the kernel does not return PID 0 (neither does
|
559 |
+
# ps) but it's actually querable (Process(0) will succeed).
|
560 |
+
ret.insert(0, 0)
|
561 |
+
return ret
|
562 |
+
|
563 |
+
|
564 |
+
if OPENBSD or NETBSD:
|
565 |
+
|
566 |
+
def pid_exists(pid):
|
567 |
+
"""Return True if pid exists."""
|
568 |
+
exists = _psposix.pid_exists(pid)
|
569 |
+
if not exists:
|
570 |
+
# We do this because _psposix.pid_exists() lies in case of
|
571 |
+
# zombie processes.
|
572 |
+
return pid in pids()
|
573 |
+
else:
|
574 |
+
return True
|
575 |
+
|
576 |
+
else:
|
577 |
+
pid_exists = _psposix.pid_exists
|
578 |
+
|
579 |
+
|
580 |
+
def is_zombie(pid):
|
581 |
+
try:
|
582 |
+
st = cext.proc_oneshot_info(pid)[kinfo_proc_map['status']]
|
583 |
+
return PROC_STATUSES.get(st) == _common.STATUS_ZOMBIE
|
584 |
+
except OSError:
|
585 |
+
return False
|
586 |
+
|
587 |
+
|
588 |
+
def wrap_exceptions(fun):
|
589 |
+
"""Decorator which translates bare OSError exceptions into
|
590 |
+
NoSuchProcess and AccessDenied.
|
591 |
+
"""
|
592 |
+
|
593 |
+
@functools.wraps(fun)
|
594 |
+
def wrapper(self, *args, **kwargs):
|
595 |
+
try:
|
596 |
+
return fun(self, *args, **kwargs)
|
597 |
+
except ProcessLookupError:
|
598 |
+
if is_zombie(self.pid):
|
599 |
+
raise ZombieProcess(self.pid, self._name, self._ppid)
|
600 |
+
else:
|
601 |
+
raise NoSuchProcess(self.pid, self._name)
|
602 |
+
except PermissionError:
|
603 |
+
raise AccessDenied(self.pid, self._name)
|
604 |
+
except OSError:
|
605 |
+
if self.pid == 0:
|
606 |
+
if 0 in pids():
|
607 |
+
raise AccessDenied(self.pid, self._name)
|
608 |
+
else:
|
609 |
+
raise
|
610 |
+
raise
|
611 |
+
|
612 |
+
return wrapper
|
613 |
+
|
614 |
+
|
615 |
+
@contextlib.contextmanager
|
616 |
+
def wrap_exceptions_procfs(inst):
|
617 |
+
"""Same as above, for routines relying on reading /proc fs."""
|
618 |
+
try:
|
619 |
+
yield
|
620 |
+
except (ProcessLookupError, FileNotFoundError):
|
621 |
+
# ENOENT (no such file or directory) gets raised on open().
|
622 |
+
# ESRCH (no such process) can get raised on read() if
|
623 |
+
# process is gone in meantime.
|
624 |
+
if is_zombie(inst.pid):
|
625 |
+
raise ZombieProcess(inst.pid, inst._name, inst._ppid)
|
626 |
+
else:
|
627 |
+
raise NoSuchProcess(inst.pid, inst._name)
|
628 |
+
except PermissionError:
|
629 |
+
raise AccessDenied(inst.pid, inst._name)
|
630 |
+
|
631 |
+
|
632 |
+
class Process:
|
633 |
+
"""Wrapper class around underlying C implementation."""
|
634 |
+
|
635 |
+
__slots__ = ["pid", "_name", "_ppid", "_cache"]
|
636 |
+
|
637 |
+
def __init__(self, pid):
|
638 |
+
self.pid = pid
|
639 |
+
self._name = None
|
640 |
+
self._ppid = None
|
641 |
+
|
642 |
+
def _assert_alive(self):
|
643 |
+
"""Raise NSP if the process disappeared on us."""
|
644 |
+
# For those C function who do not raise NSP, possibly returning
|
645 |
+
# incorrect or incomplete result.
|
646 |
+
cext.proc_name(self.pid)
|
647 |
+
|
648 |
+
@wrap_exceptions
|
649 |
+
@memoize_when_activated
|
650 |
+
def oneshot(self):
|
651 |
+
"""Retrieves multiple process info in one shot as a raw tuple."""
|
652 |
+
ret = cext.proc_oneshot_info(self.pid)
|
653 |
+
assert len(ret) == len(kinfo_proc_map)
|
654 |
+
return ret
|
655 |
+
|
656 |
+
def oneshot_enter(self):
|
657 |
+
self.oneshot.cache_activate(self)
|
658 |
+
|
659 |
+
def oneshot_exit(self):
|
660 |
+
self.oneshot.cache_deactivate(self)
|
661 |
+
|
662 |
+
@wrap_exceptions
|
663 |
+
def name(self):
|
664 |
+
name = self.oneshot()[kinfo_proc_map['name']]
|
665 |
+
return name if name is not None else cext.proc_name(self.pid)
|
666 |
+
|
667 |
+
@wrap_exceptions
|
668 |
+
def exe(self):
|
669 |
+
if FREEBSD:
|
670 |
+
if self.pid == 0:
|
671 |
+
return '' # else NSP
|
672 |
+
return cext.proc_exe(self.pid)
|
673 |
+
elif NETBSD:
|
674 |
+
if self.pid == 0:
|
675 |
+
# /proc/0 dir exists but /proc/0/exe doesn't
|
676 |
+
return ""
|
677 |
+
with wrap_exceptions_procfs(self):
|
678 |
+
return os.readlink("/proc/%s/exe" % self.pid)
|
679 |
+
else:
|
680 |
+
# OpenBSD: exe cannot be determined; references:
|
681 |
+
# https://chromium.googlesource.com/chromium/src/base/+/
|
682 |
+
# master/base_paths_posix.cc
|
683 |
+
# We try our best guess by using which against the first
|
684 |
+
# cmdline arg (may return None).
|
685 |
+
cmdline = self.cmdline()
|
686 |
+
if cmdline:
|
687 |
+
return which(cmdline[0]) or ""
|
688 |
+
else:
|
689 |
+
return ""
|
690 |
+
|
691 |
+
@wrap_exceptions
|
692 |
+
def cmdline(self):
|
693 |
+
if OPENBSD and self.pid == 0:
|
694 |
+
return [] # ...else it crashes
|
695 |
+
elif NETBSD:
|
696 |
+
# XXX - most of the times the underlying sysctl() call on
|
697 |
+
# NetBSD and OpenBSD returns a truncated string. Also
|
698 |
+
# /proc/pid/cmdline behaves the same so it looks like this
|
699 |
+
# is a kernel bug.
|
700 |
+
try:
|
701 |
+
return cext.proc_cmdline(self.pid)
|
702 |
+
except OSError as err:
|
703 |
+
if err.errno == errno.EINVAL:
|
704 |
+
if is_zombie(self.pid):
|
705 |
+
raise ZombieProcess(self.pid, self._name, self._ppid)
|
706 |
+
elif not pid_exists(self.pid):
|
707 |
+
raise NoSuchProcess(self.pid, self._name, self._ppid)
|
708 |
+
else:
|
709 |
+
# XXX: this happens with unicode tests. It means the C
|
710 |
+
# routine is unable to decode invalid unicode chars.
|
711 |
+
debug("ignoring %r and returning an empty list" % err)
|
712 |
+
return []
|
713 |
+
else:
|
714 |
+
raise
|
715 |
+
else:
|
716 |
+
return cext.proc_cmdline(self.pid)
|
717 |
+
|
718 |
+
@wrap_exceptions
|
719 |
+
def environ(self):
|
720 |
+
return cext.proc_environ(self.pid)
|
721 |
+
|
722 |
+
@wrap_exceptions
|
723 |
+
def terminal(self):
|
724 |
+
tty_nr = self.oneshot()[kinfo_proc_map['ttynr']]
|
725 |
+
tmap = _psposix.get_terminal_map()
|
726 |
+
try:
|
727 |
+
return tmap[tty_nr]
|
728 |
+
except KeyError:
|
729 |
+
return None
|
730 |
+
|
731 |
+
@wrap_exceptions
|
732 |
+
def ppid(self):
|
733 |
+
self._ppid = self.oneshot()[kinfo_proc_map['ppid']]
|
734 |
+
return self._ppid
|
735 |
+
|
736 |
+
@wrap_exceptions
|
737 |
+
def uids(self):
|
738 |
+
rawtuple = self.oneshot()
|
739 |
+
return _common.puids(
|
740 |
+
rawtuple[kinfo_proc_map['real_uid']],
|
741 |
+
rawtuple[kinfo_proc_map['effective_uid']],
|
742 |
+
rawtuple[kinfo_proc_map['saved_uid']],
|
743 |
+
)
|
744 |
+
|
745 |
+
@wrap_exceptions
|
746 |
+
def gids(self):
|
747 |
+
rawtuple = self.oneshot()
|
748 |
+
return _common.pgids(
|
749 |
+
rawtuple[kinfo_proc_map['real_gid']],
|
750 |
+
rawtuple[kinfo_proc_map['effective_gid']],
|
751 |
+
rawtuple[kinfo_proc_map['saved_gid']],
|
752 |
+
)
|
753 |
+
|
754 |
+
@wrap_exceptions
|
755 |
+
def cpu_times(self):
|
756 |
+
rawtuple = self.oneshot()
|
757 |
+
return _common.pcputimes(
|
758 |
+
rawtuple[kinfo_proc_map['user_time']],
|
759 |
+
rawtuple[kinfo_proc_map['sys_time']],
|
760 |
+
rawtuple[kinfo_proc_map['ch_user_time']],
|
761 |
+
rawtuple[kinfo_proc_map['ch_sys_time']],
|
762 |
+
)
|
763 |
+
|
764 |
+
if FREEBSD:
|
765 |
+
|
766 |
+
@wrap_exceptions
|
767 |
+
def cpu_num(self):
|
768 |
+
return self.oneshot()[kinfo_proc_map['cpunum']]
|
769 |
+
|
770 |
+
@wrap_exceptions
|
771 |
+
def memory_info(self):
|
772 |
+
rawtuple = self.oneshot()
|
773 |
+
return pmem(
|
774 |
+
rawtuple[kinfo_proc_map['rss']],
|
775 |
+
rawtuple[kinfo_proc_map['vms']],
|
776 |
+
rawtuple[kinfo_proc_map['memtext']],
|
777 |
+
rawtuple[kinfo_proc_map['memdata']],
|
778 |
+
rawtuple[kinfo_proc_map['memstack']],
|
779 |
+
)
|
780 |
+
|
781 |
+
memory_full_info = memory_info
|
782 |
+
|
783 |
+
@wrap_exceptions
|
784 |
+
def create_time(self):
|
785 |
+
return self.oneshot()[kinfo_proc_map['create_time']]
|
786 |
+
|
787 |
+
@wrap_exceptions
|
788 |
+
def num_threads(self):
|
789 |
+
if HAS_PROC_NUM_THREADS:
|
790 |
+
# FreeBSD
|
791 |
+
return cext.proc_num_threads(self.pid)
|
792 |
+
else:
|
793 |
+
return len(self.threads())
|
794 |
+
|
795 |
+
@wrap_exceptions
|
796 |
+
def num_ctx_switches(self):
|
797 |
+
rawtuple = self.oneshot()
|
798 |
+
return _common.pctxsw(
|
799 |
+
rawtuple[kinfo_proc_map['ctx_switches_vol']],
|
800 |
+
rawtuple[kinfo_proc_map['ctx_switches_unvol']],
|
801 |
+
)
|
802 |
+
|
803 |
+
@wrap_exceptions
|
804 |
+
def threads(self):
|
805 |
+
# Note: on OpenSBD this (/dev/mem) requires root access.
|
806 |
+
rawlist = cext.proc_threads(self.pid)
|
807 |
+
retlist = []
|
808 |
+
for thread_id, utime, stime in rawlist:
|
809 |
+
ntuple = _common.pthread(thread_id, utime, stime)
|
810 |
+
retlist.append(ntuple)
|
811 |
+
if OPENBSD:
|
812 |
+
self._assert_alive()
|
813 |
+
return retlist
|
814 |
+
|
815 |
+
@wrap_exceptions
|
816 |
+
def connections(self, kind='inet'):
|
817 |
+
if kind not in conn_tmap:
|
818 |
+
raise ValueError(
|
819 |
+
"invalid %r kind argument; choose between %s"
|
820 |
+
% (kind, ', '.join([repr(x) for x in conn_tmap]))
|
821 |
+
)
|
822 |
+
families, types = conn_tmap[kind]
|
823 |
+
ret = []
|
824 |
+
|
825 |
+
if NETBSD:
|
826 |
+
rawlist = cext.net_connections(self.pid, kind)
|
827 |
+
elif OPENBSD:
|
828 |
+
rawlist = cext.net_connections(self.pid, families, types)
|
829 |
+
else:
|
830 |
+
rawlist = cext.proc_connections(self.pid, families, types)
|
831 |
+
|
832 |
+
for item in rawlist:
|
833 |
+
fd, fam, type, laddr, raddr, status = item[:6]
|
834 |
+
if FREEBSD:
|
835 |
+
if (fam not in families) or (type not in types):
|
836 |
+
continue
|
837 |
+
nt = conn_to_ntuple(
|
838 |
+
fd, fam, type, laddr, raddr, status, TCP_STATUSES
|
839 |
+
)
|
840 |
+
ret.append(nt)
|
841 |
+
|
842 |
+
self._assert_alive()
|
843 |
+
return ret
|
844 |
+
|
845 |
+
@wrap_exceptions
|
846 |
+
def wait(self, timeout=None):
|
847 |
+
return _psposix.wait_pid(self.pid, timeout, self._name)
|
848 |
+
|
849 |
+
@wrap_exceptions
|
850 |
+
def nice_get(self):
|
851 |
+
return cext_posix.getpriority(self.pid)
|
852 |
+
|
853 |
+
@wrap_exceptions
|
854 |
+
def nice_set(self, value):
|
855 |
+
return cext_posix.setpriority(self.pid, value)
|
856 |
+
|
857 |
+
@wrap_exceptions
|
858 |
+
def status(self):
|
859 |
+
code = self.oneshot()[kinfo_proc_map['status']]
|
860 |
+
# XXX is '?' legit? (we're not supposed to return it anyway)
|
861 |
+
return PROC_STATUSES.get(code, '?')
|
862 |
+
|
863 |
+
@wrap_exceptions
|
864 |
+
def io_counters(self):
|
865 |
+
rawtuple = self.oneshot()
|
866 |
+
return _common.pio(
|
867 |
+
rawtuple[kinfo_proc_map['read_io_count']],
|
868 |
+
rawtuple[kinfo_proc_map['write_io_count']],
|
869 |
+
-1,
|
870 |
+
-1,
|
871 |
+
)
|
872 |
+
|
873 |
+
@wrap_exceptions
|
874 |
+
def cwd(self):
|
875 |
+
"""Return process current working directory."""
|
876 |
+
# sometimes we get an empty string, in which case we turn
|
877 |
+
# it into None
|
878 |
+
if OPENBSD and self.pid == 0:
|
879 |
+
return "" # ...else it would raise EINVAL
|
880 |
+
elif NETBSD or HAS_PROC_OPEN_FILES:
|
881 |
+
# FreeBSD < 8 does not support functions based on
|
882 |
+
# kinfo_getfile() and kinfo_getvmmap()
|
883 |
+
return cext.proc_cwd(self.pid)
|
884 |
+
else:
|
885 |
+
raise NotImplementedError(
|
886 |
+
"supported only starting from FreeBSD 8" if FREEBSD else ""
|
887 |
+
)
|
888 |
+
|
889 |
+
nt_mmap_grouped = namedtuple(
|
890 |
+
'mmap', 'path rss, private, ref_count, shadow_count'
|
891 |
+
)
|
892 |
+
nt_mmap_ext = namedtuple(
|
893 |
+
'mmap', 'addr, perms path rss, private, ref_count, shadow_count'
|
894 |
+
)
|
895 |
+
|
896 |
+
def _not_implemented(self):
|
897 |
+
raise NotImplementedError
|
898 |
+
|
899 |
+
# FreeBSD < 8 does not support functions based on kinfo_getfile()
|
900 |
+
# and kinfo_getvmmap()
|
901 |
+
if HAS_PROC_OPEN_FILES:
|
902 |
+
|
903 |
+
@wrap_exceptions
|
904 |
+
def open_files(self):
|
905 |
+
"""Return files opened by process as a list of namedtuples."""
|
906 |
+
rawlist = cext.proc_open_files(self.pid)
|
907 |
+
return [_common.popenfile(path, fd) for path, fd in rawlist]
|
908 |
+
|
909 |
+
else:
|
910 |
+
open_files = _not_implemented
|
911 |
+
|
912 |
+
# FreeBSD < 8 does not support functions based on kinfo_getfile()
|
913 |
+
# and kinfo_getvmmap()
|
914 |
+
if HAS_PROC_NUM_FDS:
|
915 |
+
|
916 |
+
@wrap_exceptions
|
917 |
+
def num_fds(self):
|
918 |
+
"""Return the number of file descriptors opened by this process."""
|
919 |
+
ret = cext.proc_num_fds(self.pid)
|
920 |
+
if NETBSD:
|
921 |
+
self._assert_alive()
|
922 |
+
return ret
|
923 |
+
|
924 |
+
else:
|
925 |
+
num_fds = _not_implemented
|
926 |
+
|
927 |
+
# --- FreeBSD only APIs
|
928 |
+
|
929 |
+
if FREEBSD:
|
930 |
+
|
931 |
+
@wrap_exceptions
|
932 |
+
def cpu_affinity_get(self):
|
933 |
+
return cext.proc_cpu_affinity_get(self.pid)
|
934 |
+
|
935 |
+
@wrap_exceptions
|
936 |
+
def cpu_affinity_set(self, cpus):
|
937 |
+
# Pre-emptively check if CPUs are valid because the C
|
938 |
+
# function has a weird behavior in case of invalid CPUs,
|
939 |
+
# see: https://github.com/giampaolo/psutil/issues/586
|
940 |
+
allcpus = tuple(range(len(per_cpu_times())))
|
941 |
+
for cpu in cpus:
|
942 |
+
if cpu not in allcpus:
|
943 |
+
raise ValueError(
|
944 |
+
"invalid CPU #%i (choose between %s)" % (cpu, allcpus)
|
945 |
+
)
|
946 |
+
try:
|
947 |
+
cext.proc_cpu_affinity_set(self.pid, cpus)
|
948 |
+
except OSError as err:
|
949 |
+
# 'man cpuset_setaffinity' about EDEADLK:
|
950 |
+
# <<the call would leave a thread without a valid CPU to run
|
951 |
+
# on because the set does not overlap with the thread's
|
952 |
+
# anonymous mask>>
|
953 |
+
if err.errno in (errno.EINVAL, errno.EDEADLK):
|
954 |
+
for cpu in cpus:
|
955 |
+
if cpu not in allcpus:
|
956 |
+
raise ValueError(
|
957 |
+
"invalid CPU #%i (choose between %s)"
|
958 |
+
% (cpu, allcpus)
|
959 |
+
)
|
960 |
+
raise
|
961 |
+
|
962 |
+
@wrap_exceptions
|
963 |
+
def memory_maps(self):
|
964 |
+
return cext.proc_memory_maps(self.pid)
|
965 |
+
|
966 |
+
@wrap_exceptions
|
967 |
+
def rlimit(self, resource, limits=None):
|
968 |
+
if limits is None:
|
969 |
+
return cext.proc_getrlimit(self.pid, resource)
|
970 |
+
else:
|
971 |
+
if len(limits) != 2:
|
972 |
+
raise ValueError(
|
973 |
+
"second argument must be a (soft, hard) tuple, got %s"
|
974 |
+
% repr(limits)
|
975 |
+
)
|
976 |
+
soft, hard = limits
|
977 |
+
return cext.proc_setrlimit(self.pid, resource, soft, hard)
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1e6a38d79d8f9e53a2ce11b68b4153062d4e96ec0b368d02b2e64f1b33c51693
|
3 |
+
size 551
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c26dcbe30cfb39161f305b2b3d43a9b50adc8b368d0749568c47106cbdb20897
|
3 |
+
size 553
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9da09e9a6031d060ec416f639a6bf34989e6c88ce641d10621eb906ba1d8c293
|
3 |
+
size 99
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:35890d08165c804526b48aad462d7ccc09e808bd7975ba604bd612b9608797ac
|
3 |
+
size 319
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdq-42585.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3736e7feb7ad30c68675c2c4e48a9fb262e80308c9083b100ddd0339da1fc282
|
3 |
+
size 348
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jd-61.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a5c7e79aa41ef580838fb9fc1906280f076c47be1741fddd5004ddb500eb57fe
|
3 |
+
size 898
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdf-61.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:33cbd6ae945ba04969370ab35604e9363c87256393493382b5118a89d59386d6
|
3 |
+
size 268
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0bce20aae7fd903796d96d5b3a3677b7058fbc5f3fe0996ee9d491e4ee23d132
|
3 |
+
size 293
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a9f4b9317997df63ed8d2bb073a3906344c0e0be017fd384eaec36ced8b94bae
|
3 |
+
size 330
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdq-61.json.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:424cd47c12a51c7bb8d8169fac80fb5601f152bd78468b241d4b115bf7d22f20
|
3 |
+
size 1121
|
llmeval-env/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/data-v1-dl-61.arff.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:afe4736924606638984e573235191025d419c545d31dc8874c96b72f5ec5db73
|
3 |
+
size 2342
|
llmeval-env/lib/python3.10/site-packages/sqlitedict-2.1.0.egg-info/installed-files.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
../__pycache__/sqlitedict.cpython-310.pyc
|
2 |
+
../sqlitedict.py
|
3 |
+
PKG-INFO
|
4 |
+
SOURCES.txt
|
5 |
+
dependency_links.txt
|
6 |
+
top_level.txt
|
llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .std import TqdmMultiProcessPool
|
llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (238 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__pycache__/logger.cpython-310.pyc
ADDED
Binary file (3.08 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__pycache__/std.cpython-310.pyc
ADDED
Binary file (5.46 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/tqdm_multiprocess/__pycache__/tqdm_multiprocess.cpython-310.pyc
ADDED
Binary file (4.53 kB). View file
|
|