def run_command_line(interactive, inspect, run_command, no_site, run_module, run_stdin, warnoptions, unbuffered, ignore_environment, verbose, bytes_warning, quiet, isolated, dev_mode, **ignored): # with PyPy in top of CPython we can only have around 100 # but we need more in the PyPy level for the compiler package if not WE_ARE_TRANSLATED: sys.setrecursionlimit(5000) getenv = get_getenv() readenv = not ignore_environment io_encoding = getenv("PYTHONIOENCODING") if readenv else None initstdio(io_encoding, unbuffered) if 'faulthandler' in sys.builtin_module_names: if dev_mode or 'faulthandler' in sys._xoptions or ( readenv and getenv('PYTHONFAULTHANDLER')): import faulthandler try: faulthandler.enable(2) # manually set to stderr except ValueError: pass # ignore "2 is not a valid file descriptor" mainmodule = type(sys)('__main__') mainmodule.__loader__ = sys.__loader__ mainmodule.__builtins__ = __builtins__ mainmodule.__annotations__ = {} sys.modules['__main__'] = mainmodule if not no_site: # __PYVENV_LAUNCHER__, used here by CPython on macOS, is be ignored # since it (possibly) results in a wrong sys.prefix and # sys.exec_prefix (and consequently sys.path) set by site.py. try: import site except: print("'import site' failed", file=sys.stderr) # The priority order for warnings configuration is (highest precedence # first): # # - the BytesWarning filter, if needed ('-b', '-bb') # - any '-W' command line options; then # - the 'PYTHONWARNINGS' environment variable; then # - the dev mode filter ('-X dev', 'PYTHONDEVMODE'); then # - any implicit filters added by _warnings.c/warnings.py # # All settings except the last are passed to the warnings module via # the `sys.warnoptions` list. Since the warnings module works on the basis # of "the most recently added filter will be checked first", we add # the lowest precedence entries first so that later entries override them. sys_warnoptions = [] if dev_mode: sys_warnoptions.append("default") pythonwarnings = readenv and getenv('PYTHONWARNINGS') if pythonwarnings: sys_warnoptions.extend(pythonwarnings.split(',')) if warnoptions: sys_warnoptions.extend(warnoptions) if bytes_warning: sys_warnoptions.append("error::BytesWarning" if bytes_warning > 1 else "default::BytesWarning") if sys_warnoptions: sys.warnoptions[:] = sys_warnoptions try: if 'warnings' in sys.modules: from warnings import _processoptions _processoptions(sys.warnoptions) else: import warnings except ImportError as e: pass # CPython just eats any exception here # set up the Ctrl-C => KeyboardInterrupt signal handler, if the # signal module is available try: import _signal as signal except ImportError: pass else: signal.signal(signal.SIGINT, signal.default_int_handler) if hasattr(signal, "SIGPIPE"): signal.signal(signal.SIGPIPE, signal.SIG_IGN) if hasattr(signal, 'SIGXFZ'): signal.signal(signal.SIGXFZ, signal.SIG_IGN) if hasattr(signal, 'SIGXFSZ'): signal.signal(signal.SIGXFSZ, signal.SIG_IGN) def inspect_requested(): # We get an interactive prompt in one of the following three cases: # # * interactive=True, from the "-i" option # or # * inspect=True and stdin is a tty # or # * PYTHONINSPECT is set and stdin is a tty. # return (interactive or ((inspect or (readenv and getenv('PYTHONINSPECT'))) and sys.stdin.isatty())) success = True try: if run_command != 0: # handle the "-c" command # Put '' on sys.path try: bytes = run_command.encode() except BaseException as e: print("Unable to decode the command from the command line:", file=sys.stderr) display_exception(e) success = False else: if not isolated: sys.path.insert(0, '') success = run_toplevel(exec, bytes, mainmodule.__dict__) elif run_module != 0: # handle the "-m" command # '' on sys.path is required also here if not isolated: sys.path.insert(0, '') import runpy success = run_toplevel(runpy._run_module_as_main, run_module) elif run_stdin: # handle the case where no command/filename/module is specified # on the command-line. # update sys.path *after* loading site.py, in case there is a # "site.py" file in the script's directory. Only run this if we're # executing the interactive prompt, if we're running a script we # put it's directory on sys.path if not isolated: sys.path.insert(0, '') if interactive or sys.stdin.isatty(): # If stdin is a tty or if "-i" is specified, we print a # banner (unless "-q" was specified) and run # $PYTHONSTARTUP. if not quiet: print_banner(not no_site) python_startup = readenv and getenv('PYTHONSTARTUP') if python_startup: try: with open(python_startup, 'rb') as f: startup = f.read() except IOError as e: print("Could not open PYTHONSTARTUP", file=sys.stderr) print("IOError:", e, file=sys.stderr) else: @hidden_applevel def run_it(): co_python_startup = compile( startup, python_startup, 'exec', PyCF_ACCEPT_NULL_BYTES) exec(co_python_startup, mainmodule.__dict__) mainmodule.__file__ = python_startup mainmodule.__cached__ = None run_toplevel(run_it) try: del mainmodule.__file__ except (AttributeError, TypeError): pass # Then we need a prompt. inspect = True else: # If not interactive, just read and execute stdin normally. if verbose: print_banner(not no_site) @hidden_applevel def run_it(): co_stdin = compile(sys.stdin.read(), '<stdin>', 'exec', PyCF_ACCEPT_NULL_BYTES) exec(co_stdin, mainmodule.__dict__) mainmodule.__file__ = '<stdin>' mainmodule.__cached__ = None success = run_toplevel(run_it) else: # handle the common case where a filename is specified # on the command-line. filename = sys.argv[0] mainmodule.__file__ = filename mainmodule.__cached__ = None for hook in sys.path_hooks: try: importer = hook(filename) break except ImportError: continue else: importer = None if importer is None and not isolated: sys.path.insert(0, sys.pypy_resolvedirof(filename)) # assume it's a pyc file only if its name says so. # CPython goes to great lengths to detect other cases # of pyc file format, but I think it's ok not to care. try: from _frozen_importlib import (SourceFileLoader, SourcelessFileLoader) except ImportError: from _frozen_importlib_external import (SourceFileLoader, SourcelessFileLoader) if IS_WINDOWS: filename = filename.lower() if filename.endswith('.pyc'): # We don't actually load via SourcelessFileLoader # because '__main__' must not be listed inside # 'importlib._bootstrap._module_locks' (it deadlocks # test_multiprocessing_main_handling.test_script_compiled) from importlib._bootstrap_external import MAGIC_NUMBER import marshal loader = SourcelessFileLoader('__main__', filename) mainmodule.__loader__ = loader @hidden_applevel def execfile(filename, namespace): with open(filename, 'rb') as f: if f.read(4) != MAGIC_NUMBER: raise RuntimeError("Bad magic number in .pyc file") if len(f.read(8)) != 8: raise RuntimeError("Truncated .pyc file") co = marshal.load(f) if type(co) is not type((lambda: 0).__code__): raise RuntimeError("Bad code object in .pyc file") exec(co, namespace) args = (execfile, filename, mainmodule.__dict__) else: filename = sys.argv[0] if importer is not None: # It's the name of a directory or a zip file. # put the filename in sys.path[0] and import # the module __main__ import runpy sys.path.insert(0, filename) args = (runpy._run_module_as_main, '__main__', False) else: # That's the normal path, "pypy3 stuff.py". # We don't actually load via SourceFileLoader # because we require PyCF_ACCEPT_NULL_BYTES loader = SourceFileLoader('__main__', filename) mainmodule.__loader__ = loader @hidden_applevel def execfile(filename, namespace): with open(filename, 'rb') as f: code = f.read() co = compile(code, filename, 'exec', PyCF_ACCEPT_NULL_BYTES) exec(co, namespace) args = (execfile, filename, mainmodule.__dict__) success = run_toplevel(*args) except SystemExit as e: status = e.code if inspect_requested(): display_exception(e) else: status = not success # start a prompt if requested if inspect_requested(): try: from _pypy_interact import interactive_console if hasattr(sys, '__interactivehook__'): run_toplevel(sys.__interactivehook__) pypy_version_info = getattr(sys, 'pypy_version_info', sys.version_info) irc_topic = pypy_version_info[3] != 'final' or ( readenv and getenv('PYPY_IRC_TOPIC')) success = run_toplevel(interactive_console, mainmodule, quiet=quiet or not irc_topic) except SystemExit as e: status = e.code else: status = not success return status
def run_command_line(interactive, inspect, run_command, no_site, run_module, run_stdin, warnoptions, unbuffered, ignore_environment, verbose, **ignored): # with PyPy in top of CPython we can only have around 100 # but we need more in the translated PyPy for the compiler package if '__pypy__' not in sys.builtin_module_names: sys.setrecursionlimit(5000) import os if unbuffered: set_unbuffered_io() elif not sys.stdout.isatty(): set_fully_buffered_io() if we_are_translated(): import __pypy__ __pypy__.save_module_content_for_future_reload(sys) mainmodule = type(sys)('__main__') sys.modules['__main__'] = mainmodule if not no_site: try: import site except: print >> sys.stderr, "'import site' failed" set_stdio_encodings(ignore_environment) readenv = not ignore_environment pythonwarnings = readenv and os.getenv('PYTHONWARNINGS') if pythonwarnings: warnoptions.extend(pythonwarnings.split(',')) if warnoptions: sys.warnoptions[:] = warnoptions from warnings import _processoptions _processoptions(sys.warnoptions) # set up the Ctrl-C => KeyboardInterrupt signal handler, if the # signal module is available try: import signal except ImportError: pass else: signal.signal(signal.SIGINT, signal.default_int_handler) if hasattr(signal, "SIGPIPE"): signal.signal(signal.SIGPIPE, signal.SIG_IGN) if hasattr(signal, 'SIGXFZ'): signal.signal(signal.SIGXFZ, signal.SIG_IGN) if hasattr(signal, 'SIGXFSZ'): signal.signal(signal.SIGXFSZ, signal.SIG_IGN) # Pre-load the default encoder (controlled by PYTHONIOENCODING) now. # This is needed before someone mucks up with sys.path (or even adds # a unicode string to it, leading to infinite recursion when we try # to encode it during importing). Note: very obscure. Issue #2314. str(u'') def inspect_requested(): # We get an interactive prompt in one of the following three cases: # # * interactive=True, from the "-i" option # or # * inspect=True and stdin is a tty # or # * PYTHONINSPECT is set and stdin is a tty. # try: # we need a version of getenv that bypasses Python caching from __pypy__.os import real_getenv except ImportError: # dont fail on CPython here real_getenv = os.getenv return (interactive or ((inspect or (readenv and real_getenv('PYTHONINSPECT'))) and sys.stdin.isatty())) try: from _ast import PyCF_ACCEPT_NULL_BYTES except ImportError: PyCF_ACCEPT_NULL_BYTES = 0 future_flags = [0] success = True try: if run_command != 0: # handle the "-c" command # Put '' on sys.path sys.path.insert(0, '') @hidden_applevel def run_it(): co_cmd = compile(run_command, '<module>', 'exec') exec co_cmd in mainmodule.__dict__ future_flags[0] = co_cmd.co_flags success = run_toplevel(run_it) elif run_module: # handle the "-m" command # '' on sys.path is required also here sys.path.insert(0, '') import runpy success = run_toplevel(runpy._run_module_as_main, sys.argv[0]) elif run_stdin: # handle the case where no command/filename/module is specified # on the command-line. # update sys.path *after* loading site.py, in case there is a # "site.py" file in the script's directory. Only run this if we're # executing the interactive prompt, if we're running a script we # put it's directory on sys.path sys.path.insert(0, '') if interactive or sys.stdin.isatty(): # If stdin is a tty or if "-i" is specified, we print # a banner and run $PYTHONSTARTUP. print_banner(not no_site) python_startup = readenv and os.getenv('PYTHONSTARTUP') if python_startup: try: with open(python_startup) as f: startup = f.read() except IOError as e: print >> sys.stderr, "Could not open PYTHONSTARTUP" print >> sys.stderr, "IOError:", e else: @hidden_applevel def run_it(): co_python_startup = compile( startup, python_startup, 'exec', PyCF_ACCEPT_NULL_BYTES) exec co_python_startup in mainmodule.__dict__ future_flags[0] = co_python_startup.co_flags mainmodule.__file__ = python_startup run_toplevel(run_it) try: del mainmodule.__file__ except (AttributeError, TypeError): pass # Then we need a prompt. inspect = True else: # If not interactive, just read and execute stdin normally. if verbose: print_banner(not no_site) @hidden_applevel def run_it(): co_stdin = compile(sys.stdin.read(), '<stdin>', 'exec', PyCF_ACCEPT_NULL_BYTES) exec co_stdin in mainmodule.__dict__ future_flags[0] = co_stdin.co_flags mainmodule.__file__ = '<stdin>' success = run_toplevel(run_it) else: # handle the common case where a filename is specified # on the command-line. filename = sys.argv[0] mainmodule.__file__ = filename sys.path.insert(0, sys.pypy_resolvedirof(filename)) # assume it's a pyc file only if its name says so. # CPython goes to great lengths to detect other cases # of pyc file format, but I think it's ok not to care. import imp if IS_WINDOWS: filename = filename.lower() if filename.endswith('.pyc') or filename.endswith('.pyo'): args = (imp._run_compiled_module, '__main__', sys.argv[0], None, mainmodule) else: # maybe it's the name of a directory or a zip file filename = sys.argv[0] importer = imp._getimporter(filename) if not isinstance(importer, imp.NullImporter): # yes. put the filename in sys.path[0] and import # the module __main__ import runpy sys.path.insert(0, filename) args = (runpy._run_module_as_main, '__main__', False) else: # no. That's the normal path, "pypy stuff.py". # This includes the logic from execfile(), tweaked # to grab the future_flags at the end. @hidden_applevel def run_it(): f = file(filename, 'rU') try: source = f.read() finally: f.close() co_main = compile(source.rstrip() + "\n", filename, 'exec', PyCF_ACCEPT_NULL_BYTES) exec co_main in mainmodule.__dict__ future_flags[0] = co_main.co_flags args = (run_it, ) success = run_toplevel(*args) except SystemExit as e: status = e.code if inspect_requested(): display_exception(e) else: status = not success # start a prompt if requested if inspect_requested(): try: import __future__ from _pypy_interact import interactive_console pypy_version_info = getattr(sys, 'pypy_version_info', sys.version_info) irc_topic = pypy_version_info[3] != 'final' or ( readenv and os.getenv('PYPY_IRC_TOPIC')) flags = 0 for fname in __future__.all_feature_names: feature = getattr(__future__, fname) if future_flags[0] & feature.compiler_flag: flags |= feature.compiler_flag kwds = {} if flags: kwds['future_flags'] = flags success = run_toplevel(interactive_console, mainmodule, quiet=not irc_topic, **kwds) except SystemExit as e: status = e.code else: status = not success return status
def run_command_line(interactive, inspect, run_command, no_site, run_module, run_stdin, warnoptions, unbuffered, ignore_environment, quiet, **ignored): # with PyPy in top of CPython we can only have around 100 # but we need more in the translated PyPy for the compiler package if '__pypy__' not in sys.builtin_module_names: sys.setrecursionlimit(5000) import os readenv = not ignore_environment io_encoding = os.getenv("PYTHONIOENCODING") if readenv else None initstdio(io_encoding, unbuffered) if we_are_translated(): import __pypy__ __pypy__.save_module_content_for_future_reload(sys) mainmodule = type(sys)('__main__') sys.modules['__main__'] = mainmodule if not no_site: try: import site except: print("'import site' failed", file=sys.stderr) pythonwarnings = readenv and os.getenv('PYTHONWARNINGS') if pythonwarnings: warnoptions.extend(pythonwarnings.split(',')) if warnoptions: sys.warnoptions[:] = warnoptions from warnings import _processoptions _processoptions(sys.warnoptions) # set up the Ctrl-C => KeyboardInterrupt signal handler, if the # signal module is available try: import signal except ImportError: pass else: signal.signal(signal.SIGINT, signal.default_int_handler) if hasattr(signal, "SIGPIPE"): signal.signal(signal.SIGPIPE, signal.SIG_IGN) if hasattr(signal, 'SIGXFZ'): signal.signal(signal.SIGXFZ, signal.SIG_IGN) if hasattr(signal, 'SIGXFSZ'): signal.signal(signal.SIGXFSZ, signal.SIG_IGN) def inspect_requested(): # We get an interactive prompt in one of the following three cases: # # * interactive=True, from the "-i" option # or # * inspect=True and stdin is a tty # or # * PYTHONINSPECT is set and stdin is a tty. # try: # we need a version of getenv that bypasses Python caching from __pypy__.os import real_getenv except ImportError: # dont fail on CPython here real_getenv = os.getenv return (interactive or ((inspect or (readenv and real_getenv('PYTHONINSPECT'))) and sys.stdin.isatty())) success = True try: if run_command != 0: # handle the "-c" command # Put '' on sys.path try: bytes = run_command.encode() except BaseException as e: print("Unable to decode the command from the command line:", file=sys.stderr) display_exception(e) success = False else: sys.path.insert(0, '') success = run_toplevel(exec_, bytes, mainmodule.__dict__) elif run_module != 0: # handle the "-m" command # '' on sys.path is required also here sys.path.insert(0, '') import runpy success = run_toplevel(runpy._run_module_as_main, run_module) elif run_stdin: # handle the case where no command/filename/module is specified # on the command-line. # update sys.path *after* loading site.py, in case there is a # "site.py" file in the script's directory. Only run this if we're # executing the interactive prompt, if we're running a script we # put it's directory on sys.path sys.path.insert(0, '') if interactive or sys.stdin.isatty(): # If stdin is a tty or if "-i" is specified, we print a # banner (unless "-q" was specified) and run # $PYTHONSTARTUP. if not quiet: print_banner(not no_site) python_startup = readenv and os.getenv('PYTHONSTARTUP') if python_startup: try: with open(python_startup, 'rb') as f: startup = f.read() except IOError as e: print("Could not open PYTHONSTARTUP", file=sys.stderr) print("IOError:", e, file=sys.stderr) else: @hidden_applevel def run_it(): co_python_startup = compile( startup, python_startup, 'exec', PyCF_ACCEPT_NULL_BYTES) exec_(co_python_startup, mainmodule.__dict__) mainmodule.__file__ = python_startup mainmodule.__cached__ = None run_toplevel(run_it) try: del mainmodule.__file__ except (AttributeError, TypeError): pass # Then we need a prompt. inspect = True else: # If not interactive, just read and execute stdin normally. @hidden_applevel def run_it(): co_stdin = compile(sys.stdin.read(), '<stdin>', 'exec', PyCF_ACCEPT_NULL_BYTES) exec_(co_stdin, mainmodule.__dict__) mainmodule.__file__ = '<stdin>' mainmodule.__cached__ = None success = run_toplevel(run_it) else: # handle the common case where a filename is specified # on the command-line. filename = sys.argv[0] mainmodule.__file__ = filename mainmodule.__cached__ = None sys.path.insert(0, sys.pypy_resolvedirof(filename)) # assume it's a pyc file only if its name says so. # CPython goes to great lengths to detect other cases # of pyc file format, but I think it's ok not to care. import imp if IS_WINDOWS: filename = filename.lower() if filename.endswith('.pyc') or filename.endswith('.pyo'): args = (imp._run_compiled_module, '__main__', sys.argv[0], None, mainmodule, False) else: # maybe it's the name of a directory or a zip file filename = sys.argv[0] importer = imp._getimporter(filename) if not isinstance(importer, imp.NullImporter): # yes. put the filename in sys.path[0] and import # the module __main__ import runpy sys.path.insert(0, filename) args = (runpy._run_module_as_main, '__main__', False) else: # no. That's the normal path, "pypy stuff.py". @hidden_applevel def execfile(filename, namespace): with open(filename, 'rb') as f: code = f.read() co = compile(code, filename, 'exec', PyCF_ACCEPT_NULL_BYTES) exec_(co, namespace) args = (execfile, filename, mainmodule.__dict__) success = run_toplevel(*args) except SystemExit as e: status = e.code if inspect_requested(): display_exception(e) else: status = not success # start a prompt if requested if inspect_requested(): try: from _pypy_interact import interactive_console pypy_version_info = getattr(sys, 'pypy_version_info', sys.version_info) irc_topic = pypy_version_info[3] != 'final' or ( readenv and os.getenv('PYPY_IRC_TOPIC')) success = run_toplevel(interactive_console, mainmodule, quiet=quiet or not irc_topic) except SystemExit as e: status = e.code else: status = not success return status
def run_command_line(interactive, inspect, run_command, no_site, run_module, run_stdin, warnoptions, unbuffered, ignore_environment, verbose, **ignored): # with PyPy in top of CPython we can only have around 100 # but we need more in the translated PyPy for the compiler package if '__pypy__' not in sys.builtin_module_names: sys.setrecursionlimit(5000) import os if unbuffered: set_unbuffered_io() elif not sys.stdout.isatty(): set_fully_buffered_io() if we_are_translated(): import __pypy__ __pypy__.save_module_content_for_future_reload(sys) mainmodule = type(sys)('__main__') sys.modules['__main__'] = mainmodule if not no_site: try: import site except: print >> sys.stderr, "'import site' failed" set_stdio_encodings(ignore_environment) readenv = not ignore_environment pythonwarnings = readenv and os.getenv('PYTHONWARNINGS') if pythonwarnings: warnoptions.extend(pythonwarnings.split(',')) if warnoptions: sys.warnoptions[:] = warnoptions from warnings import _processoptions _processoptions(sys.warnoptions) # set up the Ctrl-C => KeyboardInterrupt signal handler, if the # signal module is available try: import signal except ImportError: pass else: signal.signal(signal.SIGINT, signal.default_int_handler) if hasattr(signal, "SIGPIPE"): signal.signal(signal.SIGPIPE, signal.SIG_IGN) if hasattr(signal, 'SIGXFZ'): signal.signal(signal.SIGXFZ, signal.SIG_IGN) if hasattr(signal, 'SIGXFSZ'): signal.signal(signal.SIGXFSZ, signal.SIG_IGN) # Pre-load the default encoder (controlled by PYTHONIOENCODING) now. # This is needed before someone mucks up with sys.path (or even adds # a unicode string to it, leading to infinite recursion when we try # to encode it during importing). Note: very obscure. Issue #2314. str(u'') def inspect_requested(): # We get an interactive prompt in one of the following three cases: # # * interactive=True, from the "-i" option # or # * inspect=True and stdin is a tty # or # * PYTHONINSPECT is set and stdin is a tty. # try: # we need a version of getenv that bypasses Python caching from __pypy__.os import real_getenv except ImportError: # dont fail on CPython here real_getenv = os.getenv return (interactive or ((inspect or (readenv and real_getenv('PYTHONINSPECT'))) and sys.stdin.isatty())) try: from _ast import PyCF_ACCEPT_NULL_BYTES except ImportError: PyCF_ACCEPT_NULL_BYTES = 0 future_flags = [0] success = True try: if run_command != 0: # handle the "-c" command # Put '' on sys.path sys.path.insert(0, '') @hidden_applevel def run_it(): co_cmd = compile(run_command, '<module>', 'exec') exec co_cmd in mainmodule.__dict__ future_flags[0] = co_cmd.co_flags success = run_toplevel(run_it) elif run_module: # handle the "-m" command # '' on sys.path is required also here sys.path.insert(0, '') import runpy success = run_toplevel(runpy._run_module_as_main, sys.argv[0]) elif run_stdin: # handle the case where no command/filename/module is specified # on the command-line. # update sys.path *after* loading site.py, in case there is a # "site.py" file in the script's directory. Only run this if we're # executing the interactive prompt, if we're running a script we # put it's directory on sys.path sys.path.insert(0, '') if interactive or sys.stdin.isatty(): # If stdin is a tty or if "-i" is specified, we print # a banner and run $PYTHONSTARTUP. print_banner(not no_site) python_startup = readenv and os.getenv('PYTHONSTARTUP') if python_startup: try: with open(python_startup) as f: startup = f.read() except IOError as e: print >> sys.stderr, "Could not open PYTHONSTARTUP" print >> sys.stderr, "IOError:", e else: @hidden_applevel def run_it(): co_python_startup = compile(startup, python_startup, 'exec', PyCF_ACCEPT_NULL_BYTES) exec co_python_startup in mainmodule.__dict__ future_flags[0] = co_python_startup.co_flags mainmodule.__file__ = python_startup run_toplevel(run_it) try: del mainmodule.__file__ except (AttributeError, TypeError): pass # Then we need a prompt. inspect = True else: # If not interactive, just read and execute stdin normally. if verbose: print_banner(not no_site) @hidden_applevel def run_it(): co_stdin = compile(sys.stdin.read(), '<stdin>', 'exec', PyCF_ACCEPT_NULL_BYTES) exec co_stdin in mainmodule.__dict__ future_flags[0] = co_stdin.co_flags mainmodule.__file__ = '<stdin>' success = run_toplevel(run_it) else: # handle the common case where a filename is specified # on the command-line. filename = sys.argv[0] mainmodule.__file__ = filename sys.path.insert(0, sys.pypy_resolvedirof(filename)) # assume it's a pyc file only if its name says so. # CPython goes to great lengths to detect other cases # of pyc file format, but I think it's ok not to care. import imp if IS_WINDOWS: filename = filename.lower() if filename.endswith('.pyc') or filename.endswith('.pyo'): args = (imp._run_compiled_module, '__main__', sys.argv[0], None, mainmodule) else: # maybe it's the name of a directory or a zip file filename = sys.argv[0] importer = imp._getimporter(filename) if not isinstance(importer, imp.NullImporter): # yes. put the filename in sys.path[0] and import # the module __main__ import runpy sys.path.insert(0, filename) args = (runpy._run_module_as_main, '__main__', False) else: # no. That's the normal path, "pypy stuff.py". # This includes the logic from execfile(), tweaked # to grab the future_flags at the end. @hidden_applevel def run_it(): f = file(filename, 'rU') try: source = f.read() finally: f.close() co_main = compile(source.rstrip()+"\n", filename, 'exec', PyCF_ACCEPT_NULL_BYTES) exec co_main in mainmodule.__dict__ future_flags[0] = co_main.co_flags args = (run_it,) success = run_toplevel(*args) except SystemExit as e: status = e.code if inspect_requested(): display_exception(e) else: status = not success # start a prompt if requested if inspect_requested(): try: import __future__ from _pypy_interact import interactive_console pypy_version_info = getattr(sys, 'pypy_version_info', sys.version_info) irc_topic = pypy_version_info[3] != 'final' or ( readenv and os.getenv('PYPY_IRC_TOPIC')) flags = 0 for fname in __future__.all_feature_names: feature = getattr(__future__, fname) if future_flags[0] & feature.compiler_flag: flags |= feature.compiler_flag kwds = {} if flags: kwds['future_flags'] = flags success = run_toplevel(interactive_console, mainmodule, quiet=not irc_topic, **kwds) except SystemExit as e: status = e.code else: status = not success return status
# Then we need a prompt. inspect = True else: # If not interactive, just read and execute stdin normally. def run_it(): co_stdin = compile(sys.stdin.read(), "<stdin>", "exec") exec co_stdin in mainmodule.__dict__ mainmodule.__file__ = "<stdin>" success = run_toplevel(run_it) else: # handle the common case where a filename is specified # on the command-line. filename = sys.argv[0] mainmodule.__file__ = filename sys.path.insert(0, sys.pypy_resolvedirof(filename)) # assume it's a pyc file only if its name says so. # CPython goes to great lengths to detect other cases # of pyc file format, but I think it's ok not to care. import imp if IS_WINDOWS: filename = filename.lower() if filename.endswith(".pyc") or filename.endswith(".pyo"): args = (imp._run_compiled_module, "__main__", sys.argv[0], None, mainmodule) else: # maybe it's the name of a directory or a zip file filename = sys.argv[0] importer = imp._getimporter(filename) if not isinstance(importer, imp.NullImporter): # yes. put the filename in sys.path[0] and import
def run_command_line(interactive, inspect, run_command, no_site, run_module, run_stdin, warnoptions, unbuffered, ignore_environment, quiet, **ignored): # with PyPy in top of CPython we can only have around 100 # but we need more in the translated PyPy for the compiler package if '__pypy__' not in sys.builtin_module_names: sys.setrecursionlimit(5000) import os readenv = not ignore_environment io_encoding = os.getenv("PYTHONIOENCODING") if readenv else None initstdio(io_encoding, unbuffered) if we_are_translated(): import __pypy__ __pypy__.save_module_content_for_future_reload(sys) mainmodule = type(sys)('__main__') sys.modules['__main__'] = mainmodule if not no_site: try: import site except: print("'import site' failed", file=sys.stderr) pythonwarnings = readenv and os.getenv('PYTHONWARNINGS') if pythonwarnings: warnoptions.extend(pythonwarnings.split(',')) if warnoptions: sys.warnoptions[:] = warnoptions from warnings import _processoptions _processoptions(sys.warnoptions) # set up the Ctrl-C => KeyboardInterrupt signal handler, if the # signal module is available try: import signal except ImportError: pass else: signal.signal(signal.SIGINT, signal.default_int_handler) if hasattr(signal, "SIGPIPE"): signal.signal(signal.SIGPIPE, signal.SIG_IGN) if hasattr(signal, 'SIGXFZ'): signal.signal(signal.SIGXFZ, signal.SIG_IGN) if hasattr(signal, 'SIGXFSZ'): signal.signal(signal.SIGXFSZ, signal.SIG_IGN) def inspect_requested(): # We get an interactive prompt in one of the following three cases: # # * interactive=True, from the "-i" option # or # * inspect=True and stdin is a tty # or # * PYTHONINSPECT is set and stdin is a tty. # try: # we need a version of getenv that bypasses Python caching from __pypy__.os import real_getenv except ImportError: # dont fail on CPython here real_getenv = os.getenv return (interactive or ((inspect or (readenv and real_getenv('PYTHONINSPECT'))) and sys.stdin.isatty())) success = True try: if run_command != 0: # handle the "-c" command # Put '' on sys.path try: bytes = run_command.encode() except BaseException as e: print("Unable to decode the command from the command line:", file=sys.stderr) display_exception(e) success = False else: sys.path.insert(0, '') success = run_toplevel(exec_, bytes, mainmodule.__dict__) elif run_module != 0: # handle the "-m" command # '' on sys.path is required also here sys.path.insert(0, '') import runpy success = run_toplevel(runpy._run_module_as_main, run_module) elif run_stdin: # handle the case where no command/filename/module is specified # on the command-line. # update sys.path *after* loading site.py, in case there is a # "site.py" file in the script's directory. Only run this if we're # executing the interactive prompt, if we're running a script we # put it's directory on sys.path sys.path.insert(0, '') if interactive or sys.stdin.isatty(): # If stdin is a tty or if "-i" is specified, we print a # banner (unless "-q" was specified) and run # $PYTHONSTARTUP. if not quiet: print_banner(not no_site) python_startup = readenv and os.getenv('PYTHONSTARTUP') if python_startup: try: with open(python_startup, 'rb') as f: startup = f.read() except IOError as e: print("Could not open PYTHONSTARTUP", file=sys.stderr) print("IOError:", e, file=sys.stderr) else: @hidden_applevel def run_it(): co_python_startup = compile(startup, python_startup, 'exec', PyCF_ACCEPT_NULL_BYTES) exec_(co_python_startup, mainmodule.__dict__) mainmodule.__file__ = python_startup mainmodule.__cached__ = None run_toplevel(run_it) try: del mainmodule.__file__ except (AttributeError, TypeError): pass # Then we need a prompt. inspect = True else: # If not interactive, just read and execute stdin normally. @hidden_applevel def run_it(): co_stdin = compile(sys.stdin.read(), '<stdin>', 'exec', PyCF_ACCEPT_NULL_BYTES) exec_(co_stdin, mainmodule.__dict__) mainmodule.__file__ = '<stdin>' mainmodule.__cached__ = None success = run_toplevel(run_it) else: # handle the common case where a filename is specified # on the command-line. filename = sys.argv[0] mainmodule.__file__ = filename mainmodule.__cached__ = None sys.path.insert(0, sys.pypy_resolvedirof(filename)) # assume it's a pyc file only if its name says so. # CPython goes to great lengths to detect other cases # of pyc file format, but I think it's ok not to care. import imp if IS_WINDOWS: filename = filename.lower() if filename.endswith('.pyc') or filename.endswith('.pyo'): args = (imp._run_compiled_module, '__main__', sys.argv[0], None, mainmodule, False) else: # maybe it's the name of a directory or a zip file filename = sys.argv[0] importer = imp._getimporter(filename) if not isinstance(importer, imp.NullImporter): # yes. put the filename in sys.path[0] and import # the module __main__ import runpy sys.path.insert(0, filename) args = (runpy._run_module_as_main, '__main__', False) else: # no. That's the normal path, "pypy stuff.py". @hidden_applevel def execfile(filename, namespace): with open(filename, 'rb') as f: code = f.read() co = compile(code, filename, 'exec', PyCF_ACCEPT_NULL_BYTES) exec_(co, namespace) args = (execfile, filename, mainmodule.__dict__) success = run_toplevel(*args) except SystemExit as e: status = e.code if inspect_requested(): display_exception(e) else: status = not success # start a prompt if requested if inspect_requested(): try: from _pypy_interact import interactive_console pypy_version_info = getattr(sys, 'pypy_version_info', sys.version_info) irc_topic = pypy_version_info[3] != 'final' or ( readenv and os.getenv('PYPY_IRC_TOPIC')) success = run_toplevel(interactive_console, mainmodule, quiet=quiet or not irc_topic) except SystemExit as e: status = e.code else: status = not success return status