Debian Codegraph @

pypy/module/sys/app.py

raw symbols SCIP
1 # NOT_RPYTHON
2 """
3 The 'sys' module.
4 """
5
6 from _structseq import structseqtype, structseqfield, SimpleNamespace
7 import sys
8 import _imp
9 from __pypy__.os import _get_multiarch
10
11 def excepthook(exctype, value, traceback):
12 """Handle an exception by displaying it with a traceback on sys.stderr."""
13 if not isinstance(value, BaseException):
14 sys.stderr.write("TypeError: print_exception(): Exception expected for "
15 "value, {} found\n".format(type(value).__name__))
16 return
17
18 # Flush stdout as well, both files may refer to the same file
19 try:
20 sys.stdout.flush()
21 except:
22 pass
23
24 try:
25 from traceback import TracebackException
26 from _colorize import can_colorize
27 limit = getattr(sys, 'tracebacklimit', None)
28 format_exc_only = False
29
30 if limit is not None:
31 # ok, this is bizarre, but, the meaning of sys.tracebacklimit is
32 # understood differently in the traceback module than in
33 # PyTraceBack_Print in CPython, see
34 # https://bugs.python.org/issue38197
35 # one is counting from the top, the other from the bottom of the
36 # stack. so reverse polarity here
37 if limit > 0:
38 if limit > sys.maxsize:
39 limit = sys.maxsize
40 limit = -limit
41 else:
42 # the limit is 0 or negative. PyTraceBack_Print does not print
43 # Traceback (most recent call last):
44 # because there is indeed no traceback.
45 # the traceback module don't care
46 traceback = None
47 limit = None
48 format_exc_only = True
49
50 tb_exc = TracebackException(
51 exctype,
52 value,
53 traceback,
54 limit=limit,
55 )
56 tb_exc._colorize = can_colorize()
57 if format_exc_only:
58 line_generator = tb_exc.format_exception_only()
59 else:
60 line_generator = tb_exc.format()
61 for line in line_generator:
62 print(line, file=sys.stderr, end="")
63 except BaseException as e:
64 if not excepthook_failsafe(exctype, value):
65 raise
66
67 def excepthook_failsafe(exctype, value):
68 # This version carefully tries to handle all bad cases (e.g. an
69 # ImportError looking for traceback.py), but may still raise.
70 # If it does, we get "Error calling sys.excepthook" from app_main.py.
71 try:
72 # first try to print the exception's class name
73 stderr = sys.stderr
74 stderr.write(str(getattr(exctype, '__name__', exctype)))
75 # then attempt to get the str() of the exception
76 try:
77 s = str(value)
78 except:
79 s = '<failure of str() on the exception instance>'
80 # then print it
81 if s:
82 stderr.write(': %s\n' % (s,))
83 else:
84 stderr.write('\n')
85 return True # successfully printed at least the class and value
86 except:
87 return False # got an exception again... ignore, report the original
88
89 def breakpointhook(*args, **kwargs):
90 """This hook function is called by built-in breakpoint()."""
91
92 import importlib, os, warnings
93
94 hookname = os.getenv('PYTHONBREAKPOINT')
95 if hookname is None or len(hookname) == 0:
96 hookname = 'pdb.set_trace'
97 elif hookname == '0':
98 return None
99 modname, dot, funcname = hookname.rpartition('.')
100 if dot == '':
101 modname = 'builtins'
102
103 try:
104 module = importlib.import_module(modname)
105 hook = getattr(module, funcname)
106 except:
107 warnings.warn(
108 'Ignoring unimportable $PYTHONBREAKPOINT: "{}"'.format(hookname),
109 RuntimeWarning)
110 return None
111
112 return hook(*args, **kwargs)
113
114 def exit(exitcode=None):
115 """Exit the interpreter by raising SystemExit(exitcode).
116 If the exitcode is omitted or None, it defaults to zero (i.e., success).
117 If the exitcode is numeric, it will be used as the system exit status.
118 If it is another kind of object, it will be printed and the system
119 exit status will be one (i.e., failure)."""
120 # note that we cannot simply use SystemExit(exitcode) here.
121 # in the default branch, we use "raise SystemExit, exitcode",
122 # which leads to an extra de-tupelizing
123 # in normalize_exception, which is exactly like CPython's.
124 if isinstance(exitcode, tuple):
125 raise SystemExit(*exitcode)
126 raise SystemExit(exitcode)
127
128 #import __builtin__
129
130 def callstats():
131 """Not implemented."""
132 return None
133
134 copyright_str = """\
135 Copyright 2003 PyPy development team.
136 All Rights Reserved.
137 For further information, see <https://pypy.org>
138
139 Portions Copyright (c) 2001-2021 Python Software Foundation.
140 All Rights Reserved.
141
142 Portions Copyright (c) 2000 BeOpen.com.
143 All Rights Reserved.
144
145 Portions Copyright (c) 1995-2001 Corporation for National Research Initiatives.
146 All Rights Reserved.
147
148 Portions Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
149 All Rights Reserved.
150 """
151
152 # Keep synchronized with pypy.interpreter.app_main.sys_flags and
153 # pypy.module.cpyext._flags
154
155 # This is tested in test_app_main.py
156 class sysflags(metaclass=structseqtype):
157 name = "sys.flags"
158
159 debug = structseqfield(0)
160 inspect = structseqfield(1)
161 interactive = structseqfield(2)
162 optimize = structseqfield(3)
163 dont_write_bytecode = structseqfield(4)
164 no_user_site = structseqfield(5)
165 no_site = structseqfield(6)
166 ignore_environment = structseqfield(7)
167 verbose = structseqfield(8)
168 bytes_warning = structseqfield(9)
169 quiet = structseqfield(10)
170 hash_randomization = structseqfield(11)
171 isolated = structseqfield(12)
172 dev_mode = structseqfield(13)
173 utf8_mode = structseqfield(14)
174 warn_default_encoding = structseqfield(15)
175 int_max_str_digits = structseqfield(16)
176 safe_path = structseqfield(17)
177
178 # The real flags are set in app_main, which is not used in untranslated tests.
179 # Set reasonable defaults for testing, in particular set utf8_mode to 1
180 # no clue why some have to be a bool, but CPython has tests
181 # for that. Also see default_otions in app_main
182 null_sysflags = sysflags((0,)*13 + (False, 1, 0, -1, False))
183 null__xoptions = {}
184
185 # copied from version.py
186 def tuple2hex(ver):
187 levels = {'alpha': 0xA,
188 'beta': 0xB,
189 'candidate': 0xC,
190 'final': 0xF,
191 }
192 subver = ver[4]
193 if not (0 <= subver <= 9):
194 subver = 0
195 return (ver[0] << 24 |
196 ver[1] << 16 |
197 ver[2] << 8 |
198 levels[ver[3]] << 4 |
199 subver)
200
201 implementation_dict = {
202 'name': 'pypy',
203 'version': sys.pypy_version_info,
204 'hexversion': tuple2hex(sys.pypy_version_info),
205 'cache_tag': _imp.get_tag(),
206 }
207
208 multiarch = _get_multiarch()
209 if multiarch:
210 implementation_dict['_multiarch'] = multiarch
211
212 implementation = SimpleNamespace(**implementation_dict)
213
214
215 def sys_stdout():
216 import sys
217 try:
218 return sys.stdout
219 except AttributeError:
220 raise RuntimeError("lost sys.stdout")
221
222 def print_item_to(x, stream):
223 # give to write() an argument which is either a string or a unicode
224 # (and let it deals itself with unicode handling). The check "is
225 # unicode" should not use isinstance() at app-level, because that
226 # could be fooled by strange objects, so it is done at interp-level.
227 try:
228 stream.write(x)
229 except UnicodeEncodeError:
230 print_unencodable_to(x, stream)
231
232 def print_unencodable_to(x, stream):
233 encoding = stream.encoding
234 encoded = x.encode(encoding, 'backslashreplace')
235 buffer = getattr(stream, 'buffer', None)
236 if buffer is not None:
237 buffer.write(encoded)
238 else:
239 escaped = encoded.decode(encoding, 'strict')
240 stream.write(escaped)
241
242 def print_newline_to(stream):
243 stream.write("\n")
244
245 def displayhook(obj):
246 """Print an object to sys.stdout and also save it in builtins._"""
247 import builtins
248 if obj is not None:
249 builtins._ = obj
250 # NB. this is slightly more complicated in CPython,
251 # see e.g. the difference with >>> print 5,; 8
252 print_item_to(repr(obj), sys_stdout())
253 print_newline_to(sys_stdout())
254
255 __displayhook__ = displayhook # this is exactly like in CPython