Debian Codegraph @

pypy/interpreter/app_main.py

raw symbols SCIP
1 #! /usr/bin/env python3
2 # This is pure Python code that handles the main entry point into "pypy3".
3 # See test/test_app_main.
4
5 # Missing vs CPython: -x
6 USAGE1 = __doc__ = """\
7 Options and arguments (and corresponding environment variables):
8 -b : issue warnings about str(bytes_instance), str(bytearray_instance)
9 and comparing bytes/bytearray with str. (-bb: issue errors)
10 -B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
11 -c cmd : program passed in as string (terminates option list)
12 -d : debug output from parser; also PYTHONDEBUG=x\n\
13 -E : ignore PYTHON* environment variables (such as PYTHONPATH)
14 -h : print this help message and exit (also --help)
15 -i : inspect interactively after running script; forces a prompt even
16 if stdin does not appear to be a terminal; also PYTHONINSPECT=x
17 -I : isolate Python from the user's environment (implies -E and -s)
18 -m mod : run library module as a script (terminates option list)
19 -O : remove assert and __debug__-dependent statements; add .opt-1 before
20 .pyc extension; also PYTHONOPTIMIZE=x
21 -OO : do -O changes and also discard docstrings; add .opt-2 before
22 .pyc extension
23 -P : don't prepend a potentially unsafe path to sys.path; also
24 PYTHONSAFEPATH
25 -q : don't print version and copyright messages on interactive startup
26 -s : don't add user site directory to sys.path; also PYTHONNOUSERSITE
27 -S : don't imply 'import site' on initialization
28 -u : force the binary I/O layers of stdout and stderr to be unbuffered.
29 stdin is always buffered. the text I/O layer will still be
30 line-buffered. see also PYTHONUNBUFFERED=x
31 -v : verbose (trace import statements); also PYTHONVERBOSE=x
32 can be supplied multiple times to increase verbosity
33 -V : print the Python version number and exit (also --version)
34 -W arg : warning control; arg is action:message:category:module:lineno
35 also PYTHONWARNINGS=arg
36 -X opt : set implementation-specific option. The following options are available:
37 (the CPython "showrefcount", "tracemalloc", "showalloccount", and
38 "importtime" options are not available)
39 -X faulthandler: enable faulthandler
40 -X dev: enable PyPy's \"development mode\", introducing additional runtime
41 checks which are too expensive to be enabled by default. Effect of the
42 developer mode:
43 * Add default warning filter, as -W default
44 * Enable the faulthandler module to dump the Python traceback on a crash
45 * Enable asyncio debug mode
46 * Set the dev_mode attribute of sys.flags to True
47 -X utf8: enable UTF-8 mode for operating system interfaces, overriding the default
48 locale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it would
49 otherwise activate automatically)
50 -X pycache_prefix=PATH: enable writing .pyc files to a parallel tree rooted at the
51 given directory instead of to the code tree
52 -X jit-off: turn the JIT off, equivalent to --jit off
53 -X int_max_str_digits=number: limit the size of int<->str conversions.
54 This helps avoid denial of service attacks when parsing untrusted data.
55 The default is sys.int_info.default_max_str_digits. 0 disables.
56 -X disable-remote-debug: disable the remote debugging interface
57
58 --check-hash-based-pycs always|default|never:
59 control how Python invalidates hash-based .pyc files
60 file : program read from script file
61 - : program read from stdin (default; interactive mode if a tty)
62 arg ...: arguments passed to program in sys.argv[1:]
63
64 PyPy options and arguments:
65 --info : print translation information about this PyPy executable
66 """
67 # Missing vs CPython: PYTHONHOME
68 USAGE2 = """
69 Other environment variables:
70 PYTHONSTARTUP: file executed on interactive startup (no default)
71 PYTHONPATH : %r-separated list of directories prefixed to the
72 default module search path. The result is sys.path.
73 PYTHONPLATLIBDIR : override sys.platlibdir.
74 PYTHONCASEOK : ignore case in 'import' statements (Windows).
75 PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
76 PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
77 PYTHONDEVMODE: enable the development mode.
78 PYTHONINTMAXSTRDIGITS: limits the maximum digit characters in an int value
79 when converting from a string and when converting an int back to a str.
80 A value of 0 disables the limit. Conversions to or from bases 2, 4, 8,
81 16, and 32 are never limited.
82 PYPY_IRC_TOPIC: if set to a non-empty value, print a random #pypy IRC
83 topic at startup of interactive mode.
84 PYPYLOG: If set to a non-empty value, enable logging.
85 PYPY_DISABLE_JIT: if set to a non-empty value, disable JIT.
86 PYTHON_DISABLE_REMOTE_DEBUG: if set to a non-empty value, disable the remote debugging interface
87 """
88
89 try:
90 from __pypy__ import hidden_applevel, StdErrPrinter
91 except ImportError:
92 hidden_applevel = lambda f: f
93 StdErrPrinter = None
94 try:
95 from _ast import PyCF_ACCEPT_NULL_BYTES, PyCF_IGNORE_COOKIE
96 except ImportError:
97 PyCF_ACCEPT_NULL_BYTES = PyCF_IGNORE_COOKIE = 0
98 import errno
99 import sys
100
101 try:
102 prepare_shutdown = sys._pypy_prepare_shutdown
103 del sys._pypy_prepare_shutdown
104 except AttributeError:
105 prepare_shutdown = lambda: 0
106
107 _MACOSX = sys.platform == 'darwin'
108 _WIN32 = sys.platform == 'win32'
109
110 DEBUG = False # dump exceptions before calling the except hook
111
112 originalexcepthook = sys.__excepthook__
113
114 def handle_sys_exit(e):
115 # exit if we catch a w_SystemExit
116 exitcode = e.code
117 if exitcode is None:
118 exitcode = 0
119 else:
120 try:
121 exitcode = int(exitcode)
122 except:
123 # not an integer: print it to stderr
124 try:
125 print(exitcode, file=sys.stderr)
126 except:
127 pass # too bad
128 exitcode = 1
129 raise SystemExit(exitcode)
130
131 WE_ARE_TRANSLATED = True # patch to False if we're not really translated
132 IS_WINDOWS = 'nt' in sys.builtin_module_names
133 def get_getenv():
134 try:
135 # we need a version of getenv before we import os
136 from __pypy__.os import real_getenv
137 except ImportError:
138 # dont fail on CPython tests here
139 import os
140 real_getenv = os.getenv
141 return real_getenv
142
143
144 @hidden_applevel
145 def run_toplevel(f, *fargs, **fkwds):
146 """Calls f() and handles all OperationErrors.
147 Intended use is to run the main program or one interactive statement.
148 run_protected() handles details like forwarding exceptions to
149 sys.excepthook(), catching SystemExit, etc.
150 """
151 # don't use try:except: here, otherwise the exception remains
152 # visible in user code. Make sure revdb_stop is a callable, so
153 # that we can call it immediately after finally: below. Doing
154 # so minimizes the number of "blind" lines that we need to go
155 # back from, with "bstep", after we do "continue" in revdb.
156 if '__pypy__' in sys.builtin_module_names:
157 from __pypy__ import revdb_stop
158 else:
159 revdb_stop = None
160 if revdb_stop is None:
161 revdb_stop = lambda: None
162
163 try:
164 # run it
165 try:
166 f(*fargs, **fkwds)
167 finally:
168 revdb_stop()
169 sys.settrace(None)
170 sys.setprofile(None)
171 except SystemExit as e:
172 handle_sys_exit(e)
173 except KeyboardInterrupt as e:
174 # handled a level up
175 raise
176 except BaseException as e:
177 display_exception(e)
178 return False
179 return True # success
180
181 def display_exception(e):
182 etype, evalue, etraceback = type(e), e, e.__traceback__
183 try:
184 # extra debugging info in case the code below goes very wrong
185 if DEBUG and hasattr(sys, 'stderr'):
186 s = getattr(etype, '__name__', repr(etype))
187 print("debug: exception-type: ", s, file=sys.stderr)
188 print("debug: exception-value:", str(evalue), file=sys.stderr)
189 tbentry = etraceback
190 if tbentry:
191 while tbentry.tb_next:
192 tbentry = tbentry.tb_next
193 lineno = tbentry.tb_lineno
194 filename = tbentry.tb_frame.f_code.co_filename
195 print("debug: exception-tb: %s:%d" % (filename, lineno),
196 file=sys.stderr)
197
198 # set the sys.last_xxx attributes
199 sys.last_type = etype
200 sys.last_value = evalue
201 sys.last_traceback = etraceback
202
203 # call sys.excepthook
204 hook = getattr(sys, 'excepthook', originalexcepthook)
205 try:
206 sys.audit("sys.excepthook", hook, etype, evalue, etraceback)
207 except RuntimeError:
208 return
209 except Exception as e:
210 # CPython uses _PyErr_WriteUnraisableMsg("in audit hook", NULL)
211 try:
212 initstdio()
213 import __pypy__
214 __pypy__.writeunraisable("in audit hook", e, None)
215 except Exception as e:
216 # Too bad
217 pass
218 hook(etype, evalue, etraceback)
219 return # done
220
221 except BaseException as e:
222 try:
223 initstdio()
224 stderr = sys.stderr
225 print('Error calling sys.excepthook:', file=stderr)
226 originalexcepthook(type(e), e, e.__traceback__)
227 print(file=stderr)
228 print('Original exception was:', file=stderr)
229 except:
230 pass # too bad
231
232 # we only get here if sys.excepthook didn't do its job
233 originalexcepthook(etype, evalue, etraceback)
234
235
236 # ____________________________________________________________
237 # Option parsing
238
239 def print_info(*args):
240 initstdio()
241 try:
242 options = sys.pypy_translation_info
243 except AttributeError:
244 print('no translation information found', file=sys.stderr)
245 else:
246 optitems = sorted(options.items())
247 current = []
248 for key, value in optitems:
249 group = key.split('.')
250 name = group.pop()
251 n = 0
252 while n < min(len(current), len(group)) and current[n] == group[n]:
253 n += 1
254 while n < len(group):
255 print('%s[%s]' % (' ' * n, group[n]))
256 n += 1
257 print('%s%s = %r' % (' ' * n, name, value))
258 current = group
259 raise SystemExit
260
261 def get_sys_executable():
262 return getattr(sys, 'executable', 'pypy3')
263
264 def print_help(*args):
265 if IS_WINDOWS:
266 pathsep = ';'
267 else:
268 pathsep = ':'
269 initstdio()
270 print('usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...' % (
271 get_sys_executable(),))
272 print(USAGE1, end='')
273 if 'pypyjit' in sys.builtin_module_names:
274 print("--jit options: advanced JIT options: try 'off' or 'help'")
275 print(USAGE2 % (pathsep,), end='')
276 raise SystemExit
277
278 def _print_jit_help():
279 initstdio()
280 try:
281 import pypyjit
282 except ImportError:
283 print("No jit support in %s" % (get_sys_executable(),), file=sys.stderr)
284 return
285 items = sorted(pypyjit.defaults.items())
286 print('Advanced JIT options: a comma-separated list of OPTION=VALUE:')
287 for key, value in items:
288 print()
289 print(' %s=N' % (key,))
290 doc = '%s (default %s)' % (pypyjit.PARAMETER_DOCS[key], value)
291 while len(doc) > 72:
292 i = doc[:74].rfind(' ')
293 if i < 0:
294 i = doc.find(' ')
295 if i < 0:
296 i = len(doc)
297 print(' ' + doc[:i])
298 doc = doc[i+1:]
299 print(' ' + doc)
300 print()
301 print(' off')
302 print(' turn off the JIT')
303 print(' help')
304 print(' print this page')
305 print()
306 print('The "pypyjit" module can be used to control the JIT from inside python')
307
308 def print_version(*args):
309 initstdio()
310 print("Python", sys.version)
311 raise SystemExit
312
313
314 def funroll_loops(*args):
315 print("Vroom vroom, I'm a racecar!")
316
317
318 def set_jit_option(options, jitparam, *args):
319 options['_jitoptions'] = jitparam
320 if jitparam == 'help':
321 _print_jit_help()
322 raise SystemExit
323 if 'pypyjit' not in sys.builtin_module_names:
324 initstdio()
325 print("Warning: No jit support in %s" % (get_sys_executable(),),
326 file=sys.stderr)
327 else:
328 import pypyjit
329 pypyjit.set_param(jitparam)
330
331
332 def disable_remote_debug(options):
333 options['_remote_debug'] = 'off'
334 try:
335 import __pypy__
336 except ImportError:
337 pass
338 else:
339 __pypy__._pypy_disable_remote_debugger = True
340
341
342 class CommandLineError(Exception):
343 pass
344
345 def print_error(msg):
346 print(msg, file=sys.stderr)
347 print('usage: %s [options]' % (get_sys_executable(),), file=sys.stderr)
348 print('Try `%s -h` for more information.' % (get_sys_executable(),), file=sys.stderr)
349
350 def fdopen(fd, mode, bufsize=-1):
351 try:
352 fdopen = file.fdopen
353 except AttributeError: # only on top of CPython, running tests
354 from os import fdopen
355 return fdopen(fd, mode, bufsize)
356
357 # ____________________________________________________________
358 # Main entry point
359
360 def setup_and_fix_paths(ignore_environment=False, **extra):
361 if IS_WINDOWS:
362 pathsep = ';'
363 else:
364 pathsep = ':'
365 getenv = get_getenv()
366 newpath = sys.path[:]
367 del sys.path[:]
368 # first prepend PYTHONPATH
369 readenv = not ignore_environment
370 path = readenv and getenv('PYTHONPATH')
371 if path:
372 sys.path.extend(path.split(pathsep))
373 # then add again the original entries, ignoring duplicates
374 _seen = set()
375 for dir in newpath:
376 if dir not in _seen:
377 sys.path.append(dir)
378 _seen.add(dir)
379
380 def initstdio(encoding=None, unbuffered=False, utf8_mode=False):
381 if hasattr(sys, 'stdin'):
382 return # already initialized
383 if IS_WINDOWS:
384 pathsep = ';'
385 else:
386 pathsep = ':'
387 getenv = get_getenv()
388
389 if StdErrPrinter is not None:
390 sys.stderr = sys.__stderr__ = StdErrPrinter(2)
391
392 # Hack to avoid recursion issues during bootstrapping: pre-import
393 # the utf-8 and latin-1 codecs
394 encerr = None
395 try:
396 import encodings.utf_8
397 import encodings.latin_1
398 except ImportError as e:
399 encerr = e
400
401 try:
402 # Track whether the user explicitly provided a non-empty encoding name.
403 # An explicit encoding suppresses the C/POSIX locale surrogateescape
404 # default (matching CPython behaviour: PYTHONIOENCODING=utf-8 → strict,
405 # but PYTHONIOENCODING=: → surrogateescape in C locale).
406 user_set_encoding = False
407 if encoding and ':' in encoding:
408 enc_part, err_part = encoding.split(':', 1)
409 user_set_encoding = bool(enc_part)
410 encoding = enc_part or 'utf-8'
411 if err_part:
412 errors = err_part
413 elif user_set_encoding:
414 # "utf-8:" — encoding given, no error handler → strict
415 errors = 'strict'
416 else:
417 # ":" — both parts empty → treat as unspecified
418 errors = None
419 elif encoding:
420 user_set_encoding = True
421 errors = None
422 else:
423 errors = None
424 encoding = encoding or None
425 # issue 5034
426 import _locale
427 _locale.setlocale(_locale.LC_CTYPE, "")
428 if _WIN32 and not encoding:
429 encoding = "utf-8"
430 if not encoding:
431 # Use "locale" (Python 3.10+) rather than None so that
432 # TextIOWrapper is never called with encoding=None, which would
433 # trigger EncodingWarning under -X warn_default_encoding.
434 encoding = "locale"
435 if errors is None and not user_set_encoding:
436 if utf8_mode or _locale.setlocale(_locale.LC_CTYPE, None) in ('C', 'POSIX'):
437 errors = 'surrogateescape'
438
439 sys.stderr = sys.__stderr__ = create_stdio(
440 2, True, "<stderr>", encoding, 'backslashreplace', unbuffered)
441 sys.stdout = sys.__stdout__ = create_stdio(
442 1, True, "<stdout>", encoding, errors, unbuffered)
443
444 try:
445 sys.stdin = sys.__stdin__ = create_stdio(
446 0, False, "<stdin>", encoding, errors, unbuffered)
447 except IsADirectoryError:
448 import os
449 print("Python error: <stdin> is a directory, cannot continue",
450 file=sys.stderr)
451 os._exit(1)
452 finally:
453 if encerr:
454 display_exception(encerr)
455 del encerr
456
457 def create_stdio(fd, writing, name, encoding, errors, unbuffered):
458 import _io
459 # stdin is always opened in buffered mode, first because it
460 # shouldn't make a difference in common use cases, second because
461 # TextIOWrapper depends on the presence of a read1() method which
462 # only exists on buffered streams.
463 buffering = 0 if unbuffered and writing else -1
464 mode = 'w' if writing else 'r'
465 try:
466 buf = _io.open(fd, mode + 'b', buffering, closefd=False)
467 except OSError as e:
468 if e.errno != errno.EBADF:
469 raise
470 return None
471
472 # Normalize encoding to the codec's canonical name (e.g. 'latin1' ->
473 # 'iso8859-1'), matching CPython's pylifecycle.c behaviour.
474 # _codecs is a builtin so import is free; encodings.latin_1 etc. are
475 # already imported above in initstdio so the lookup itself is also cheap.
476 if encoding and encoding not in ('utf-8', 'locale'):
477 try:
478 import _codecs
479 encoding = _codecs.lookup(encoding).name
480 except LookupError:
481 pass
482
483 raw = buf.raw if buffering else buf
484 raw.name = name
485 # We normally use newline='\n' below, which turns off any translation.
486 # However, on Windows (independently of -u), then we must enable
487 # the Universal Newline mode (set by newline = None): on input, \r\n
488 # is translated into \n; on output, \n is translated into \r\n.
489 # We must never enable the Universal Newline mode on POSIX: CPython
490 # never interprets '\r\n' in stdin as meaning just '\n', unlike what
491 # it does if you explicitly open a file in text mode.
492 #
493 # Py3.9+: stderr is line buffered even when redirected: bpo-13601
494 newline = None if sys.platform == 'win32' else '\n'
495 stream = _io.TextIOWrapper(buf, encoding, errors, newline=newline,
496 line_buffering=unbuffered or fd == 2 or raw.isatty(),
497 write_through=unbuffered)
498 stream.mode = mode
499 return stream
500
501
502 # Keep synchronized with pypy.module.sys.app.sysflags and
503 # pypy.module.cpyext._flags
504 sys_flags = (
505 "debug",
506 "inspect",
507 "interactive",
508 "optimize",
509 "dont_write_bytecode",
510 "no_user_site",
511 "no_site",
512 "ignore_environment",
513 "verbose",
514 "bytes_warning",
515 "quiet",
516 "hash_randomization",
517 "isolated",
518 "dev_mode",
519 "utf8_mode",
520 "warn_default_encoding",
521 "int_max_str_digits",
522 "safe_path",
523 )
524 # ^^^ Order is significant! Keep in sync with module.sys.app.sysflags
525
526 default_options = dict.fromkeys(
527 sys_flags +
528 ("run_command",
529 "run_module",
530 "run_stdin",
531 "warnoptions",
532 "unbuffered"), 0)
533 default_options["check_hash_based_pycs"] = "default"
534 default_options["dev_mode"] = False # needs to be bool
535 default_options["utf8_mode"] = -1
536 default_options["warn_default_encoding"] = 0
537 default_options["int_max_str_digits"] = -1
538 default_options["safe_path"] = False # needs to be bool
539
540 def simple_option(options, name, iterargv):
541 options[name] += 1
542
543 def isolated_option(options, name, iterargv):
544 options[name] += 1
545 options["no_user_site"] += 1
546 options["ignore_environment"] += 1
547 options["safe_path"] = True
548
549 def c_option(options, runcmd, iterargv):
550 options["run_command"] = runcmd
551 return ['-c'] + list(iterargv)
552
553 def m_option(options, runmodule, iterargv):
554 options["run_module"] = runmodule
555 return ['-m'] + list(iterargv)
556
557 def X_option(options, xoption, iterargv):
558 options["_xoptions"].append(xoption)
559 if xoption == "dev":
560 options["dev_mode"] = True
561 elif xoption.startswith("utf8"):
562 if xoption == "utf8" or xoption == "utf8=1":
563 options["utf8_mode"] = 1
564 elif xoption == "utf8=0":
565 options["utf8_mode"] = 0
566 elif xoption == 'jit-off':
567 set_jit_option(options, 'off')
568 elif xoption == 'disable-remote-debug':
569 disable_remote_debug(options)
570 elif xoption == 'warn_default_encoding':
571 options["warn_default_encoding"] = 1
572
573 def config_init_int_max_str_digits(env_option, x_option, options):
574 maxdigits = -1
575 val = prefix = "unknown"
576 try:
577 if x_option:
578 val = x_option
579 prefix = "-X int_max_str_digits"
580 if val is True:
581 val = "option must have '=N'"
582 raise ValueError("bad option")
583 maxdigits = int(x_option)
584 elif env_option:
585 val = env_option
586 prefix = "PYTHONINTMAXSTRDIGITS"
587 maxdigits = int(env_option)
588 else:
589 return 0
590 except Exception as e:
591 msg = "invalid value '%s' for '%s'\n" % (val, prefix)
592 raise CommandLineError(msg)
593 if not (maxdigits == 0 or maxdigits >= sys.int_info.str_digits_check_threshold):
594 msg = ("Fatal Python error: config_init_int_max_str_digits:"
595 " %s: invalid limit; must be >= %d or 0 for unlimited\n") % (
596 prefix, sys.int_info.str_digits_check_threshold)
597 raise CommandLineError(msg)
598 options['int_max_str_digits'] = maxdigits
599 sys.set_int_max_str_digits(maxdigits)
600
601 def W_option(options, warnoption, iterargv):
602 options["warnoptions"].append(warnoption)
603
604 def end_options(options, _, iterargv):
605 return list(iterargv)
606
607 def ignore_option(*args):
608 pass
609
610 def check_hash_based_pycs(options, value, iterargv):
611 if value not in ("default", "always", "never"):
612 initstdio()
613 print_error("--check-hash-based-pycs must be one of 'default', 'always', or 'never'")
614 raise SystemExit
615 import _imp
616 _imp.check_hash_based_pycs = value
617 options["check_hash_based_pycs"] = value
618
619
620 cmdline_options = {
621 # simple options just increment the counter of the options listed above
622 'b': (simple_option, 'bytes_warning'),
623 'B': (simple_option, 'dont_write_bytecode'),
624 'd': (simple_option, 'debug'),
625 'E': (simple_option, 'ignore_environment'),
626 'I': (isolated_option, 'isolated'),
627 'i': (simple_option, 'interactive'),
628 'O': (simple_option, 'optimize'),
629 'P': (simple_option, 'safe_path'),
630 's': (simple_option, 'no_user_site'),
631 'S': (simple_option, 'no_site'),
632 'u': (simple_option, 'unbuffered'),
633 'v': (simple_option, 'verbose'),
634 'q': (simple_option, 'quiet'),
635 # more complex options
636 'c': (c_option, Ellipsis),
637 '?': (print_help, None),
638 'h': (print_help, None),
639 '--help': (print_help, None),
640 'm': (m_option, Ellipsis),
641 'W': (W_option, Ellipsis),
642 'X': (X_option, Ellipsis),
643 'V': (print_version, None),
644 '--version': (print_version, None),
645 '--info': (print_info, None),
646 '--jit': (set_jit_option, Ellipsis),
647 '-funroll-loops': (funroll_loops, None),
648 '--check-hash-based-pycs': (check_hash_based_pycs, Ellipsis),
649 '--': (end_options, None),
650 'R': (ignore_option, None), # previously hash_randomization
651 }
652
653 def handle_argument(c, options, iterargv, iterarg=iter(())):
654 function, funcarg = cmdline_options[c]
655
656 # If needed, fill in the real argument by taking it from the command line
657 if funcarg is Ellipsis:
658 remaining = list(iterarg)
659 if remaining:
660 funcarg = ''.join(remaining)
661 else:
662 try:
663 funcarg = next(iterargv)
664 except StopIteration:
665 if len(c) == 1:
666 c = '-' + c
667 raise CommandLineError('Argument expected for the %r option' % c)
668
669 return function(options, funcarg, iterargv)
670
671 def parse_env(name, key, options):
672 ''' Modify options inplace if name exists in os.environ
673 '''
674 getenv = get_getenv()
675 v = getenv(name)
676 if v:
677 options[key] = max(1, options[key])
678 try:
679 newval = int(v)
680 except ValueError:
681 pass
682 else:
683 newval = max(1, newval)
684 options[key] = max(options[key], newval)
685
686 def parse_command_line(bargv, argv):
687 # bargv is the bytes version, argv is decoded via the default locale
688 # logic: parse arguments argv. if utf8-mode is enabled, re-decode bargv
689 # with utf-8, then parse arguments again
690 options = _parse_command_line(argv)
691 if options["utf8_mode"]:
692 argv = [b.decode("utf-8", "surrogateescape") for b in bargv]
693 return _parse_command_line(argv)
694 return options
695
696 def _parse_command_line(argv):
697 getenv = get_getenv()
698 options = default_options.copy()
699 options['warnoptions'] = []
700 options['_xoptions'] = []
701
702 iterargv = iter(argv)
703 argv = None
704 for arg in iterargv:
705 #
706 # If the next argument isn't at least two characters long or
707 # doesn't start with '-', stop processing
708 if len(arg) < 2 or arg[0] != '-':
709 if IS_WINDOWS and arg == '/?': # special case
710 print_help()
711 argv = [arg] + list(iterargv) # finishes processing
712 #
713 # If the next argument is directly in cmdline_options, handle
714 # it as a single argument
715 elif arg in cmdline_options:
716 argv = handle_argument(arg, options, iterargv)
717 elif arg.startswith("--"):
718 raise CommandLineError('unknown option %s' % (arg,))
719 #
720 # Else interpret the rest of the argument character by character
721 else:
722 iterarg = iter(arg)
723 next(iterarg) # skip the '-'
724 for c in iterarg:
725 if c not in cmdline_options:
726 raise CommandLineError('Unknown option: -%s' % (c,))
727 argv = handle_argument(c, options, iterargv, iterarg)
728
729 if not argv:
730 argv = ['']
731 options["run_stdin"] = True
732 elif argv[0] == '-':
733 options["run_stdin"] = True
734
735 # don't change the list that sys.argv is bound to
736 # (relevant in case of "reload(sys)")
737 sys.argv[:] = argv
738
739 if options["ignore_environment"]:
740 readenv = False
741 else:
742 readenv = True
743 parse_env('PYTHONDEBUG', "debug", options)
744 parse_env('PYTHONDONTWRITEBYTECODE', "dont_write_bytecode", options)
745 if options['dont_write_bytecode'] > 1:
746 options['dont_write_bytecode'] = 1
747 if getenv('PYTHONNOUSERSITE'):
748 options["no_user_site"] = 1
749 if getenv('PYTHONSAFEPATH'):
750 options["safe_path"] = True
751 if getenv('PYTHONUNBUFFERED'):
752 options["unbuffered"] = 1
753 parse_env('PYTHONVERBOSE', "verbose", options)
754 parse_env('PYTHONOPTIMIZE', "optimize", options)
755 if getenv('PYPY_DISABLE_JIT'):
756 set_jit_option(options, 'off')
757 if getenv('PYTHONDEVMODE'):
758 options["dev_mode"] = True
759 val = getenv('PYTHONUTF8')
760 if not val:
761 pass
762 elif val == "0":
763 if options["utf8_mode"] == -1: # don't overwrite -X value
764 options["utf8_mode"] = 0
765 elif val == "1":
766 if options["utf8_mode"] == -1: # don't overwrite -X value
767 options["utf8_mode"] = 1
768 else:
769 initstdio()
770 sys.stderr.write(
771 "Fatal Python error: invalid PYTHONUTF8 environment variable value %r\n" % val)
772 raise SystemExit(1)
773 if getenv("PYTHONWARNDEFAULTENCODING"):
774 options["warn_default_encoding"] = 1
775 if options["utf8_mode"] == -1: # neither env var nor -X utf8
776 import _locale
777 if _locale.setlocale(_locale.LC_CTYPE, None) in ('C', 'POSIX'):
778 options["utf8_mode"] = 1
779 else:
780 options["utf8_mode"] = 0
781
782 if (options["interactive"] or (readenv and getenv('PYTHONINSPECT'))):
783 options["inspect"] = 1
784
785 sys._xoptions = dict(x.split('=', 1) if '=' in x else (x, True)
786 for x in options['_xoptions'])
787
788 if readenv and getenv('PYTHONNODEBUGRANGES'):
789 sys._xoptions['no_debug_ranges'] = True
790
791 config_init_int_max_str_digits(
792 getenv("PYTHONINTMAXSTRDIGITS") if readenv else None,
793 sys._xoptions.get('int_max_str_digits', None),
794 options, # can be modified
795 )
796
797 if WE_ARE_TRANSLATED:
798 flags = [options[flag] for flag in sys_flags]
799 oldflags = sys.flags
800 # hack: delete the flags first to make sure they don't turn into an
801 # cell in the celldict
802 del sys.flags
803 sys.flags = type(oldflags)(flags)
804 sys.dont_write_bytecode = bool(sys.flags.dont_write_bytecode)
805
806 if getenv('PYTHON_DISABLE_REMOTE_DEBUG'):
807 disable_remote_debug(options)
808
809 ## if not WE_ARE_TRANSLATED:
810 ## for key in sorted(options):
811 ## print '%40s: %s' % (key, options[key])
812 ## print '%40s: %s' % ("sys.argv", sys.argv)
813
814 return options
815
816 @hidden_applevel
817 def run_command_line(interactive,
818 inspect,
819 run_command,
820 no_site,
821 run_module,
822 run_stdin,
823 warnoptions,
824 unbuffered,
825 ignore_environment,
826 verbose,
827 bytes_warning,
828 quiet,
829 isolated,
830 dev_mode,
831 utf8_mode,
832 warn_default_encoding,
833 int_max_str_digits,
834 safe_path,
835 **ignored):
836 # with PyPy on top of CPython we can only have around 100
837 # but we need more in the PyPy level for the compiler package
838 if not WE_ARE_TRANSLATED:
839 sys.setrecursionlimit(5000)
840 getenv = get_getenv()
841
842
843 readenv = not ignore_environment
844 io_encoding = getenv("PYTHONIOENCODING") if readenv else None
845 initstdio(io_encoding, unbuffered, utf8_mode=utf8_mode)
846
847 if 'faulthandler' in sys.builtin_module_names:
848 if dev_mode or 'faulthandler' in sys._xoptions or (readenv and getenv('PYTHONFAULTHANDLER')):
849 import faulthandler
850 try:
851 faulthandler.enable(2) # manually set to stderr
852 except ValueError:
853 pass # ignore "2 is not a valid file descriptor"
854
855 pycache_prefix = sys._xoptions.get('pycache_prefix', None)
856 if pycache_prefix is True:
857 # "-Xpycache_prefix"
858 pass
859 elif pycache_prefix is not None:
860 # "-Xpycache_prefix=" or "-Xpycache_prefix=something"
861 if pycache_prefix:
862 sys.pycache_prefix = pycache_prefix
863 elif readenv:
864 # only if no "-Xpycache_prefix at all"
865 pycache_prefix = getenv('PYTHONPYCACHEPREFIX')
866 if pycache_prefix:
867 sys.pycache_prefix = pycache_prefix
868
869 mainmodule = type(sys)('__main__')
870 mainmodule.__loader__ = sys.__loader__
871 mainmodule.__builtins__ = __builtins__
872 mainmodule.__annotations__ = {}
873 sys.modules['__main__'] = mainmodule
874
875 if not no_site:
876 # __PYVENV_LAUNCHER__, used here by CPython on macOS, is be ignored
877 # since it (possibly) results in a wrong sys.prefix and
878 # sys.exec_prefix (and consequently sys.path) set by site.py.
879 try:
880 import site
881 except:
882 print("'import site' failed", file=sys.stderr)
883
884 # The priority order for warnings configuration is (highest precedence
885 # first):
886 #
887 # - the BytesWarning filter, if needed ('-b', '-bb')
888 # - any '-W' command line options; then
889 # - the 'PYTHONWARNINGS' environment variable; then
890 # - the dev mode filter ('-X dev', 'PYTHONDEVMODE'); then
891 # - any implicit filters added by _warnings.c/warnings.py
892 #
893 # All settings except the last are passed to the warnings module via
894 # the `sys.warnoptions` list. Since the warnings module works on the basis
895 # of "the most recently added filter will be checked first", we add
896 # the lowest precedence entries first so that later entries override them.
897 sys_warnoptions = []
898 if dev_mode:
899 sys_warnoptions.append("default")
900 pythonwarnings = readenv and getenv('PYTHONWARNINGS')
901 if pythonwarnings:
902 sys_warnoptions.extend(pythonwarnings.split(','))
903 if warnoptions:
904 sys_warnoptions.extend(warnoptions)
905 if bytes_warning:
906 sys_warnoptions.append("error::BytesWarning" if bytes_warning > 1 else "default::BytesWarning")
907
908 if sys_warnoptions:
909 sys.warnoptions[:] = sys_warnoptions
910 try:
911 if 'warnings' in sys.modules:
912 from warnings import _processoptions
913 _processoptions(sys.warnoptions)
914 else:
915 import warnings
916 except ImportError as e:
917 pass # CPython just eats any exception here
918
919 # set up the Ctrl-C => KeyboardInterrupt signal handler, if the
920 # signal module is available
921 try:
922 import _signal as signal
923 except ImportError:
924 pass
925 else:
926 signal.signal(signal.SIGINT, signal.default_int_handler)
927 if hasattr(signal, "SIGPIPE"):
928 signal.signal(signal.SIGPIPE, signal.SIG_IGN)
929 if hasattr(signal, 'SIGXFZ'):
930 signal.signal(signal.SIGXFZ, signal.SIG_IGN)
931 if hasattr(signal, 'SIGXFSZ'):
932 signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
933
934 def inspect_requested():
935 # We get an interactive prompt in one of the following three cases:
936 #
937 # * interactive=True, from the "-i" option
938 # or
939 # * inspect=True and stdin is a tty
940 # or
941 # * PYTHONINSPECT is set and stdin is a tty.
942 #
943 return (interactive or
944 ((inspect or (readenv and getenv('PYTHONINSPECT')))
945 and sys.stdin.isatty()))
946
947 success = True
948
949 try:
950 from os.path import abspath
951 if run_command != 0:
952 # handle the "-c" command
953 # Put '' on sys.path
954 try:
955 bytes = run_command.encode()
956 except BaseException as e:
957 print("Unable to decode the command from the command line:",
958 file=sys.stderr)
959 display_exception(e)
960 success = False
961 else:
962 if not isolated and not safe_path:
963 sys.path.insert(0, '')
964 @hidden_applevel
965 def run_it():
966 co_python_startup = compile(bytes,
967 "<string>",
968 'exec',
969 PyCF_IGNORE_COOKIE)
970
971 if inspect_requested():
972 try:
973 import linecache
974 linecache._register_code("<string>", run_command, "<stdin>")
975 except Exception:
976 pass
977 exec(co_python_startup, mainmodule.__dict__)
978 success = run_toplevel(run_it)
979 elif run_module != 0:
980 # handle the "-m" command
981 # Put abspath('') on sys.path
982 if not isolated and not safe_path:
983 fullpath = abspath('.')
984 sys.path.insert(0, fullpath)
985 import runpy
986 success = run_toplevel(runpy._run_module_as_main, run_module)
987 elif run_stdin:
988 # handle the case where no command/filename/module is specified
989 # on the command-line.
990
991 # update sys.path *after* loading site.py, in case there is a
992 # "site.py" file in the script's directory. Only run this if we're
993 # executing the interactive prompt, if we're running a script we
994 # put it's directory on sys.path
995 if not isolated and not safe_path:
996 sys.path.insert(0, '')
997
998 if interactive or sys.stdin.isatty():
999 # If stdin is a tty or if "-i" is specified, we print a
1000 # banner (unless "-q" was specified) and run
1001 # $PYTHONSTARTUP.
1002 if not quiet:
1003 print_banner(not no_site)
1004 python_startup = readenv and getenv('PYTHONSTARTUP')
1005 if python_startup:
1006 try:
1007 with open(python_startup, 'rb') as f:
1008 startup = f.read()
1009 except IOError as e:
1010 print("Could not open PYTHONSTARTUP", file=sys.stderr)
1011 print("IOError:", e, file=sys.stderr)
1012 else:
1013 @hidden_applevel
1014 def run_it():
1015 co_python_startup = compile(startup,
1016 python_startup,
1017 'exec',
1018 PyCF_ACCEPT_NULL_BYTES)
1019 exec(co_python_startup, mainmodule.__dict__)
1020 mainmodule.__file__ = python_startup
1021 mainmodule.__cached__ = None
1022 run_toplevel(run_it)
1023 try:
1024 del mainmodule.__file__
1025 except (AttributeError, TypeError):
1026 pass
1027 # Then we need a prompt.
1028 inspect = True
1029 else:
1030 # If not interactive, just read and execute stdin normally.
1031 if verbose:
1032 print_banner(not no_site)
1033 @hidden_applevel
1034 def run_it():
1035 co_stdin = compile(sys.stdin.read(), '<stdin>', 'exec',
1036 PyCF_ACCEPT_NULL_BYTES)
1037 exec(co_stdin, mainmodule.__dict__)
1038 mainmodule.__file__ = '<stdin>'
1039 mainmodule.__cached__ = None
1040 success = run_toplevel(run_it)
1041 else:
1042 # handle the common case where a filename is specified
1043 # on the command-line.
1044 import os
1045 filename = sys.argv[0]
1046 if not os.path.isabs(filename):
1047 try:
1048 # try to make an absolute file name, which can fail
1049 filename = os.path.join(os.getcwd(), filename)
1050 except OSError as e:
1051 pass
1052 mainmodule.__file__ = filename
1053 mainmodule.__cached__ = None
1054 for hook in sys.path_hooks:
1055 try:
1056 importer = hook(filename)
1057 break
1058 except ImportError:
1059 continue
1060 else:
1061 importer = None
1062 if importer is None and not isolated and not safe_path:
1063 sys.path.insert(0, sys.pypy_resolvedirof(filename))
1064 # assume it's a pyc file only if its name says so.
1065 # CPython goes to great lengths to detect other cases
1066 # of pyc file format, but I think it's ok not to care.
1067 try:
1068 from _frozen_importlib import (
1069 SourceFileLoader, SourcelessFileLoader)
1070 except ImportError:
1071 from _frozen_importlib_external import (
1072 SourceFileLoader, SourcelessFileLoader)
1073 if IS_WINDOWS:
1074 filename = filename.lower()
1075 if filename.endswith('.pyc'):
1076 # We don't actually load via SourcelessFileLoader
1077 # because '__main__' must not be listed inside
1078 # 'importlib._bootstrap._module_locks' (it deadlocks
1079 # test_multiprocessing_main_handling.test_script_compiled)
1080 from importlib._bootstrap_external import MAGIC_NUMBER
1081 import marshal
1082 loader = SourcelessFileLoader('__main__', filename)
1083 mainmodule.__loader__ = loader
1084 @hidden_applevel
1085 def execfile(filename, namespace):
1086 with open(filename, 'rb') as f:
1087 if f.read(4) != MAGIC_NUMBER:
1088 raise RuntimeError("Bad magic number in .pyc file")
1089 if len(f.read(12)) != 12:
1090 raise RuntimeError("Truncated .pyc file")
1091 co = marshal.load(f)
1092 if type(co) is not type((lambda:0).__code__):
1093 raise RuntimeError("Bad code object in .pyc file")
1094 exec(co, namespace)
1095 args = (execfile, filename, mainmodule.__dict__)
1096 else:
1097 filename = sys.argv[0]
1098 if importer is not None:
1099 # It's the name of a directory or a zip file.
1100 # put the filename in sys.path[0] and import
1101 # the module __main__
1102 import runpy
1103 sys.path.insert(0, abspath(filename))
1104 args = (runpy._run_module_as_main, '__main__', False)
1105 else:
1106 # That's the normal path, "pypy3 stuff.py".
1107 # We don't actually load via SourceFileLoader
1108 # because we require PyCF_ACCEPT_NULL_BYTES
1109 loader = SourceFileLoader('__main__', filename)
1110 mainmodule.__loader__ = loader
1111 @hidden_applevel
1112 def execfile(filename, namespace):
1113 from os.path import abspath
1114 filename = abspath(filename)
1115 try:
1116 with open(filename, 'rb') as f:
1117 code = f.read()
1118 except IOError as e:
1119 sys.stderr.write(
1120 "%s: can't open file %s: [Errno %d] %s\n" %
1121 (sys.executable, filename, e.errno, e.strerror))
1122 raise SystemExit(e.errno)
1123 co = compile(code, filename, 'exec',
1124 PyCF_ACCEPT_NULL_BYTES)
1125 exec(co, namespace)
1126 args = (execfile, filename, mainmodule.__dict__)
1127 success = run_toplevel(*args)
1128
1129 except SystemExit as e:
1130 status = e.code
1131 if inspect_requested():
1132 display_exception(e)
1133 except KeyboardInterrupt as e:
1134 display_exception(e)
1135 status = True
1136 if not inspect_requested():
1137 try:
1138 import _signal
1139 import os
1140 except ImportError:
1141 pass
1142 else:
1143 prepare_shutdown()
1144 # make sure we quit with the right process exit code on
1145 # receiving a SIGINT
1146 _signal.signal(_signal.SIGINT, _signal.SIG_DFL)
1147 os.kill(os.getpid(), _signal.SIGINT);
1148 assert 0, "should be unreachable"
1149 else:
1150 status = not success
1151
1152 # start a prompt if requested
1153 if inspect_requested():
1154 try:
1155 from _pypy_interact import interactive_console
1156 if hasattr(sys, '__interactivehook__'):
1157 run_toplevel(sys.__interactivehook__)
1158 pypy_version_info = getattr(sys, 'pypy_version_info', sys.version_info)
1159 irc_topic = pypy_version_info[3] != 'final' or (
1160 readenv and getenv('PYPY_IRC_TOPIC'))
1161 success = run_toplevel(interactive_console, mainmodule,
1162 quiet=quiet or not irc_topic)
1163 except SystemExit as e:
1164 status = e.code
1165 else:
1166 status = not success
1167 try:
1168 sys.stdout.flush()
1169 except Exception:
1170 pass
1171 try:
1172 sys.stderr.flush()
1173 except Exception:
1174 pass
1175 return status
1176
1177 def print_banner(copyright):
1178 print('Python %s on %s' % (sys.version, sys.platform), file=sys.stderr)
1179 if copyright:
1180 print('Type "help", "copyright", "credits" or '
1181 '"license" for more information.', file=sys.stderr)
1182
1183 STDLIB_WARNING = """\
1184 debug: WARNING: Library path not found, using compiled-in sys.path, with
1185 debug: WARNING: sys.prefix = %r
1186 debug: WARNING: Make sure the pypy3 binary is kept inside its tree of files.
1187 debug: WARNING: It is ok to create a symlink to it from somewhere else."""
1188
1189 def setup_bootstrap_path(executable):
1190 """
1191 Try to do as little as possible and to have the stdlib in sys.path. In
1192 particular, we cannot use any unicode at this point, because lots of
1193 unicode operations require to be able to import encodings.
1194 """
1195 # at this point, sys.path is set to the compiled-in one, based on the
1196 # location where pypy was compiled. This is set during the objspace
1197 # initialization by module.sys.state.State.setinitialpath.
1198 #
1199 # Now, we try to find the absolute path of the executable and the stdlib
1200 # path
1201 executable = sys.pypy_find_executable(executable)
1202 stdlib_path = sys.pypy_find_stdlib(executable)
1203 if stdlib_path is None:
1204 initstdio()
1205 print(STDLIB_WARNING % (getattr(sys, 'prefix', '<missing>'),),
1206 file=sys.stderr)
1207 else:
1208 sys.path[:] = stdlib_path
1209 # from this point on, we are free to use all the unicode stuff we want,
1210 sys.executable = executable
1211 if sys.platform == 'win32':
1212 import os
1213 # someday PyPy will grow a PEP 397 launcher. Until then ...
1214 exe = executable.replace('\\', '/').rsplit('/', 1)[-1]
1215 sys._base_executable = sys.base_prefix + '\\' + exe
1216 if not os.path.exists(sys._base_executable):
1217 # when building from source, like base/pypy/goal/pypy3-c.exe
1218 # sys.base_prefix will be 'base' and exe will be pypy3-c.exe
1219 # so sys_base_executable will be wrong. Override the wrong value
1220 sys._base_executable = executable
1221 else:
1222 sys._base_executable = executable
1223
1224
1225 @hidden_applevel
1226 def entry_point(executable, bargv, argv):
1227 # note that before calling 'import site', we are limited because we
1228 # cannot import stdlib modules. In particular, we cannot use unicode
1229 # stuffs (because we need to be able to import encodings). The full stdlib
1230 # can only be used in a virtualenv after 'import site' in run_command_line
1231 setup_bootstrap_path(executable)
1232 sys.pypy_initfsencoding()
1233 sys.orig_argv[:] = [executable] + argv
1234 try:
1235 cmdline = parse_command_line(bargv, argv)
1236 except CommandLineError as e:
1237 initstdio()
1238 print_error(str(e))
1239 return 2
1240 except SystemExit as e:
1241 return e.code or 0
1242 if WE_ARE_TRANSLATED:
1243 type(sys.flags).allow_instantiation = False
1244 setup_and_fix_paths(**cmdline)
1245 return run_command_line(**cmdline)
1246
1247
1248 def main():
1249 import os
1250 # obscure! try removing the following line, see how it crashes, and
1251 # guess why...
1252 ImStillAroundDontForgetMe = sys.modules['__main__']
1253 global WE_ARE_TRANSLATED
1254 WE_ARE_TRANSLATED = False
1255
1256 # emulate passing bytes by using fsencode
1257 bargv = [os.fsencode(a) for a in sys.argv]
1258
1259
1260 if len(sys.argv) > 1 and sys.argv[1] == '--argparse-only':
1261 if sys.platform == "win32":
1262 raise RuntimeError(
1263 "redirecting sys.stdout, sys.stderr hangs when raising the SystemExit error")
1264 import io
1265 del sys.argv[:2]
1266 del bargv[:2]
1267 sys.stdout = sys.stderr = io.StringIO()
1268 try:
1269 options = parse_command_line(bargv, sys.argv)
1270 except SystemExit:
1271 print('SystemExit', file=sys.__stdout__)
1272 print(sys.stdout.getvalue(), file=sys.__stdout__)
1273 raise
1274 except BaseException as e:
1275 print('Error', file=sys.__stdout__)
1276 print(repr(e), file=sys.__stdout__)
1277 raise
1278 else:
1279 print('Return', file=sys.__stdout__)
1280 print(options, file=sys.__stdout__)
1281 print(sys.argv, file=sys.__stdout__)
1282 return
1283
1284 # Testing python on python is hard:
1285 # Some code above (run_command_line) will create a new module
1286 # named __main__ and store it into sys.modules. There it will
1287 # replace the __main__ module that CPython created to execute the
1288 # lines you are currently reading. This will free the module, and
1289 # all globals (os, sys...) will be set to None.
1290 # To avoid this we make a copy of our __main__ module.
1291 sys.modules['__cpython_main__'] = sys.modules['__main__']
1292
1293 # debugging only
1294 def pypy_find_executable(s):
1295 return os.path.abspath(s)
1296
1297 def pypy_find_stdlib(s):
1298 from os.path import abspath, join, exists, dirname as dn
1299 thisfile = abspath(__file__)
1300 root = dn(dn(dn(thisfile)))
1301 pre_build = join(root, 'lib-python', '3')
1302 if sys.platform == 'win32':
1303 post_build = join(root, 'Lib')
1304 else:
1305 post_build = join(root, 'lib', 'pypy3.8')
1306 if exists(pre_build):
1307 return [pre_build, join(root, 'lib_pypy')]
1308 elif exists(post_build):
1309 return [post_build, join(root, 'lib_pypy')]
1310 raise RuntimeError(
1311 "could not find stdlib in '{}' and '{}'".format(pre_build, post_build))
1312
1313 def pypy_resolvedirof(s):
1314 # we ignore the issue of symlinks; for tests, the executable is always
1315 # interpreter/app_main.py anyway
1316 return os.path.abspath(os.path.join(s, '..'))
1317
1318 reset = []
1319 if 'PYTHONINSPECT_' in os.environ:
1320 reset.append(('PYTHONINSPECT', os.environ.get('PYTHONINSPECT', '')))
1321 os.environ['PYTHONINSPECT'] = os.environ['PYTHONINSPECT_']
1322 if 'PYTHONWARNINGS_' in os.environ:
1323 reset.append(('PYTHONWARNINGS', os.environ.get('PYTHONWARNINGS', '')))
1324 os.environ['PYTHONWARNINGS'] = os.environ['PYTHONWARNINGS_']
1325
1326 # when run as __main__, this module is often executed by a Python
1327 # interpreter that have a different list of builtin modules.
1328 # Make some tests happy by loading them before we clobber sys.path
1329 import runpy
1330 if 'time' not in sys.builtin_module_names:
1331 import time; del time
1332 if '_operator' not in sys.builtin_module_names:
1333 import _operator; del _operator
1334
1335 # no one should change to which lists sys.argv and sys.path are bound
1336 old_argv = sys.argv
1337 old_path = sys.path
1338
1339 old_streams = sys.stdin, sys.stdout, sys.stderr
1340 del sys.stdin, sys.stdout, sys.stderr
1341
1342 sys.pypy_find_executable = pypy_find_executable
1343 sys.pypy_find_stdlib = pypy_find_stdlib
1344 sys.pypy_resolvedirof = pypy_resolvedirof
1345 sys.pypy_initfsencoding = lambda: None
1346 sys.cpython_path = sys.path[:]
1347
1348 try:
1349 sys.exit(int(entry_point(sys.argv[0], bargv[1:], sys.argv[1:])))
1350 finally:
1351 # restore the normal prompt (which was changed by _pypy_interact), in
1352 # case we are dropping to CPython's prompt
1353 sys.stdin, sys.stdout, sys.stderr = old_streams
1354 sys.ps1 = '>>> '
1355 sys.ps2 = '... '
1356 import os; os.environ.update(reset)
1357 assert old_argv is sys.argv
1358 assert old_path is sys.path
1359
1360 if __name__ == '__main__':
1361 main()