Example #1
0
                ['default' if WarningBytes == 1 else 'error'] + list(f)[1:])
    ctypes.c_int.in_dll(ctypes.pythonapi,
                        'Py_BytesWarningFlag').value = WarningBytes
if WarningDivision == 'new':
    ctypes.c_int.in_dll(ctypes.pythonapi, '_Py_QnewFlag').value = 1
elif WarningDivision in ('warn', 'warnall') or Warning3k:
    ctypes.c_int.in_dll(ctypes.pythonapi,
                        'Py_DivisionWarningFlag').value = (2 if WarningDivision
                                                           == 'warnall' else 1)
    warnings.filterwarnings('default',
                            category=DeprecationWarning,
                            message='classic [a-z]+ division')
if Warning3k:
    warnings.filterwarnings('default', category=DeprecationWarning)
sys.warnoptions[0:0] = WarningOptions
warnings._processoptions(WarningOptions)
bufsize = 1 if sys.version_info >= (3, ) else 0
if Unbuffered:
    sys.stdin = os.fdopen(sys.stdin.fileno(), 'r', bufsize)
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', bufsize)
    sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', bufsize)
if not NoSiteFlag:
    import site
    site.main()
# Generate the globals/locals environment
globenv = {}
for key in list(globals().keys()):
    if key.startswith('_') and key != '_frozen_name':
        globenv[key] = globals()[key]
if RunFile:
    run_file(RunFile, RunFileArgv, SkipFirstLine, globenv)
Example #2
0
def run_command_line(go_interactive,
                     run_command,
                     import_site,
                     run_module,
                     run_stdin,
                     warnoptions,
                     unbuffered,
                     cmd=None,
                     **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 
    sys.setrecursionlimit(5000)

    if unbuffered:
        set_unbuffered_io()
    elif not sys.stdout.isatty():
        set_fully_buffered_io()


    mainmodule = type(sys)('__main__')
    sys.modules['__main__'] = mainmodule

    if import_site:
        try:
            import site
        except:
            print >> sys.stderr, "'import site' failed"

    if warnoptions:
        sys.warnoptions.append(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 two cases:
        #
        #     * go_interactive=True, either from the "-i" option or
        #       from the fact that we printed the banner;
        # or
        #     * PYTHONINSPECT is set and stdin is a tty.
        #
        return (go_interactive or
                (os.getenv('PYTHONINSPECT') and sys.stdin.isatty()))

    success = True

    try:
        if run_command:
            # handle the "-c" command
            def run_it():
                exec cmd in mainmodule.__dict__
            success = run_toplevel(run_it)
        elif run_module:
            # handle the "-m" command
            def run_it():
                import runpy
                runpy.run_module(sys.argv[0], None, '__main__', True)
            success = run_toplevel(run_it)
        elif run_stdin:
            # handle the case where no command/filename/module is specified
            # on the command-line.
            if go_interactive or sys.stdin.isatty():
                # If stdin is a tty or if "-i" is specified, we print
                # a banner and run $PYTHONSTARTUP.
                print_banner()
                python_startup = os.getenv('PYTHONSTARTUP')
                if python_startup:
                    try:
                        startup = open(python_startup).read()
                    except IOError:
                        pass
                    else:
                        def run_it():
                            co_python_startup = compile(startup,
                                                        python_startup,
                                                        'exec')
                            exec co_python_startup in mainmodule.__dict__
                        run_toplevel(run_it)
                # Then we need a prompt.
                go_interactive = 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.
            mainmodule.__file__ = sys.argv[0]
            scriptdir = resolvedirof(sys.argv[0])
            sys.path.insert(0, scriptdir)
            success = run_toplevel(execfile, sys.argv[0], mainmodule.__dict__)

        # start a prompt if requested
        if inspect_requested():
            from _pypy_interact import interactive_console
            success = run_toplevel(interactive_console, mainmodule)
    except SystemExit, e:
        return e.code
Example #3
0
def run_command_line(interactive, inspect, run_command, no_site, run_module,
                     run_stdin, warnoptions, unbuffered, ignore_environment,
                     **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)

    if unbuffered:
        set_unbuffered_io()
    elif not sys.stdout.isatty():
        set_fully_buffered_io()

    mainmodule = type(sys)('__main__')
    sys.modules['__main__'] = mainmodule

    if not no_site:
        try:
            import site
        except:
            print >> sys.stderr, "'import site' failed"

    readenv = not ignore_environment
    io_encoding = readenv and os.getenv("PYTHONIOENCODING")
    if io_encoding:
        errors = None
        if ":" in io_encoding:
            io_encoding, errors = io_encoding.split(":", 1)
        set_io_encoding(io_encoding, io_encoding, errors, True)
    else:
        if IS_WINDOWS:
            import __pypy__
            io_encoding, io_encoding_output = __pypy__.get_console_cp()
        else:
            io_encoding = io_encoding_output = sys.getfilesystemencoding()
        if io_encoding:
            set_io_encoding(io_encoding, io_encoding_output, None, False)

    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.
        #
        return (interactive
                or ((inspect or (readenv and os.getenv('PYTHONINSPECT')))
                    and sys.stdin.isatty()))

    success = True

    try:
        if run_command != 0:
            # handle the "-c" command
            # Put '' on sys.path
            sys.path.insert(0, '')

            def run_it():
                exec run_command in mainmodule.__dict__

            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()
                python_startup = readenv and os.getenv('PYTHONSTARTUP')
                if python_startup:
                    try:
                        f = open(python_startup)
                        startup = f.read()
                        f.close()
                    except IOError, e:
                        print >> sys.stderr, "Could not open PYTHONSTARTUP"
                        print >> sys.stderr, "IOError:", e
                    else:

                        def run_it():
                            co_python_startup = compile(
                                startup, python_startup, 'exec')
                            exec co_python_startup in mainmodule.__dict__

                        run_toplevel(run_it)
                # 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:
Example #4
0
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
Example #5
0
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
Example #6
0
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
Example #7
0
def run_command_line(interactive,
                     inspect,
                     run_command,
                     no_site,
                     run_module,
                     run_stdin,
                     warnoptions,
                     unbuffered,
                     ignore_environment,
                     **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)

    if unbuffered:
        set_unbuffered_io()
    elif not sys.stdout.isatty():
        set_fully_buffered_io()

    mainmodule = type(sys)('__main__')
    sys.modules['__main__'] = mainmodule

    if not no_site:
        try:
            import site
        except:
            print >> sys.stderr, "'import site' failed"

    readenv = not ignore_environment
    io_encoding = ((readenv and os.getenv("PYTHONIOENCODING"))
                   or sys.getfilesystemencoding())
    if io_encoding:
        set_io_encoding(io_encoding)

    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.
        #
        return (interactive or
                ((inspect or (readenv and os.getenv('PYTHONINSPECT')))
                 and sys.stdin.isatty()))

    success = True

    try:
        if run_command != 0:
            # handle the "-c" command
            # Put '' on sys.path
            sys.path.insert(0, '')

            def run_it():
                exec run_command in mainmodule.__dict__
            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()
                python_startup = readenv and os.getenv('PYTHONSTARTUP')
                if python_startup:
                    try:
                        f = open(python_startup)
                        startup = f.read()
                        f.close()
                    except IOError, e:
                        print >> sys.stderr, "Could not open PYTHONSTARTUP"
                        print >> sys.stderr, "IOError:", e
                    else:
                        def run_it():
                            co_python_startup = compile(startup,
                                                        python_startup,
                                                        'exec')
                            exec co_python_startup in mainmodule.__dict__
                        run_toplevel(run_it)
                # 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:
Example #8
0
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
Example #9
0
def run_command_line(go_interactive,
                     run_command,
                     import_site,
                     run_module,
                     run_stdin,
                     warnoptions,
                     unbuffered,
                     cmd=None,
                     **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
    sys.setrecursionlimit(5000)

    if unbuffered:
        set_unbuffered_io()
    elif not sys.stdout.isatty():
        set_fully_buffered_io()

    mainmodule = type(sys)('__main__')
    sys.modules['__main__'] = mainmodule

    if import_site:
        try:
            import site
        except:
            print >> sys.stderr, "'import site' failed"

    if warnoptions:
        sys.warnoptions.append(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 two cases:
        #
        #     * go_interactive=True, either from the "-i" option or
        #       from the fact that we printed the banner;
        # or
        #     * PYTHONINSPECT is set and stdin is a tty.
        #
        return (go_interactive
                or (os.getenv('PYTHONINSPECT') and sys.stdin.isatty()))

    success = True

    try:
        if run_command:
            # handle the "-c" command
            def run_it():
                exec cmd in mainmodule.__dict__

            success = run_toplevel(run_it)
        elif run_module:
            # handle the "-m" command
            def run_it():
                import runpy
                runpy.run_module(sys.argv[0], None, '__main__', True)

            success = run_toplevel(run_it)
        elif run_stdin:
            # handle the case where no command/filename/module is specified
            # on the command-line.
            if go_interactive or sys.stdin.isatty():
                # If stdin is a tty or if "-i" is specified, we print
                # a banner and run $PYTHONSTARTUP.
                print_banner()
                python_startup = os.getenv('PYTHONSTARTUP')
                if python_startup:
                    try:
                        startup = open(python_startup).read()
                    except IOError:
                        pass
                    else:

                        def run_it():
                            co_python_startup = compile(
                                startup, python_startup, 'exec')
                            exec co_python_startup in mainmodule.__dict__

                        run_toplevel(run_it)
                # Then we need a prompt.
                go_interactive = 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.
            mainmodule.__file__ = sys.argv[0]
            scriptdir = resolvedirof(sys.argv[0])
            sys.path.insert(0, scriptdir)
            success = run_toplevel(execfile, sys.argv[0], mainmodule.__dict__)

        # start a prompt if requested
        if inspect_requested():
            from _pypy_interact import interactive_console
            success = run_toplevel(interactive_console, mainmodule)
    except SystemExit, e:
        return e.code
Example #10
0
def main():  # noqa
    import ctypes
    import os
    import six
    import sys
    import warnings

    AllModules = False

    if len(sys.argv) == 1 and not hasattr(sys, 'frozen'):
        AllModules = True
    if not AllModules and sys.argv[:2][-1] != '--all':
        pass
    else:
        # IMPORT ALL MODULES
        import modules_pyexe_list  # noqa, this is the output of modules_pyexe
        print(dir(modules_pyexe_list))  # for installers to include submodules
        # END IMPORT ALL MODULES
        # Import modules which failed to be included in the auto-generated list.
        import setuptools._vendor.pyparsing  # noqa

    def alternate_raw_input(prompt=None):
        """
        Write the prompt to stderr, then call raw_input without a prompt.  This
        is to try to mimic better what the python executable does.

        Enter: prompt: prompt to print to stderr.
        """
        if prompt and len(prompt):
            sys.stderr.write(prompt)
            sys.stderr.flush()
        return six.moves.input('')

    def get_env_flag(currentValue, key):
        """
        Check if the environment has a key.  Parse this as a positive integer,
        if possible, otherwise treat it like 1.  Return the greater of the
        current value and the parsed value.
        """
        if not os.environ.get(key):
            return currentValue
        try:
            value = int(os.environ.get(key))
            if value < 0:
                value = 1
        except ValueError:
            value = 1
        return max(currentValue, value)

    def print_version(details=1):
        """
        Print the current version.

        Enter: details: 0 if part of help, 1 for basic verison, 2 for more
                    details.
        """
        from py_version import Version, Description

        print('%s, Version %s' % (Description, Version))
        if details > 1:
            print('Python %s' % (sys.version))
            # pywin32
            import win32api
            fileinfo = win32api.GetFileVersionInfo(win32api.__file__, '\\')
            print('pywin32: %s' % str(fileinfo['FileVersionLS'] >> 16))
            # Others
            import importlib
            for module_name in ('pip', 'psutil', 'setuptools', 'six'):
                module = importlib.import_module(module_name)
                print('%s: %s' % (module_name, module.__version__))

    def run_file(runFile, runFileArgv, skipFirstLine, globenv):
        """
        Exec a file with a limited set of globals.  We can't use runpy.run_path
        for (a) skipped first line, (b) Python 2.7 and zipapps (pyz files).
        Rather than use run_path in the limited cases where it can be used, we
        use one code path for executing files in general.

        Enter: runFile: path of the file to exec.
               runFileArgv: arguments to set sys.argv to.
               SkipFileLine: True to skip the first line of the file.
               globenv: global environment to use.
        """
        import codecs
        import re
        import zipfile
        sys.argv[:] = runFileArgv
        if zipfile.is_zipfile(os.path.abspath(runFile)):
            sys.path[0:0] = [runFile]
            with zipfile.ZipFile(runFile) as zptr:
                src = zptr.open('__main__.py').read()
        else:
            if not Isolated:
                sys.path[0:0] = [os.path.split(os.path.abspath(runFile))[0]]
            with open(runFile, 'rb') as fptr:
                src = fptr.read()
                # This is similar to what universal newline support does
                useenc = 'utf-8' if sys.version_info >= (3, ) else 'latin-1'
                if src.startswith(codecs.BOM_UTF8):
                    useenc = 'utf-8'
                    src = src[len(codecs.BOM_UTF8):]
                src = src.replace(b'\r\n', b'\n').replace(b'\r', b'\n')
                if skipFirstLine:
                    src = src.split(b'\n', 1)[1] if b'\n' in src else b''
                # first two lines may contain encoding:
                firsttwo = src.split(b'\n', 2)
                coding_re = re.compile(
                    r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)')
                try:
                    match = coding_re.match(firsttwo[0].decode('utf8'))
                except Exception:
                    match = None
                if match:
                    useenc = match.group(1)
                    src = b'\n'.join(firsttwo[1:])
                else:
                    try:
                        match = coding_re.match(firsttwo[1].decode('utf8'))
                    except Exception:
                        match = None
                    if match:
                        useenc = match.group(1)
                        src = b'\n'.join(firsttwo[:1] + firsttwo[2:])
                src = src.decode(useenc)
        # If we use anything other than the actual globals() dictionary,
        # multiprocessing doesn't work.  Therefore, mutate globals() and
        # merge back in when done.
        globs = globals()
        originalGlobals = globs.copy()
        globs.clear()
        globs.update(globenv)
        globs['__name__'] = '__main__'
        globs['__file__'] = runFile
        six.exec_(src, globs)
        # globs.clear()
        globs.update(originalGlobals)

    def skip_once(cls, method):
        """
        The first time a mthod of a class is called, skip doing the action.

        Enter: cls: the class instance with the method.
               method: the name of the method (a string).
        """
        orig = getattr(cls, method, None)

        def skip(*args, **kwargs):
            setattr(cls, method, orig)

        setattr(cls, method, skip)

    if hasattr(sys, 'frozen'):
        delattr(sys, 'frozen')
    Help = False
    Interactive = None
    InteractiveArgv = None
    Isolated = False
    NoSiteFlag = False
    Optimize = 0
    PrintVersion = 0
    QuietFlag = False
    RunCommand = None
    RunFile = None
    RunModule = None
    SkipFirstLine = False
    StartupFile = None
    TabcheckFlag = 0
    Unbuffered = False
    UseEnvironment = True
    VerboseFlag = 0
    Warning3k = 0
    WarningBytes = 0
    WarningDivision = None
    WarningOptions = []
    skip = 0
    sys.dont_write_bytecode = False
    for i in six.moves.range(1, len(sys.argv)):  # noqa
        if skip:
            skip -= 1
            continue
        arg = sys.argv[i]
        if arg.startswith('-') and len(arg) > 1 and arg[1:2] != '-':
            for let in arg[1:]:
                if let == 'b':
                    WarningBytes += 1
                elif let == 'B':
                    sys.dont_write_bytecode = True
                elif let == 'c':
                    RunCommand = sys.argv[i + 1 + skip]
                    RunCommandArgv = ['-c'] + sys.argv[i + 2 + skip:]
                    skip = len(sys.argv)
                elif let == 'd':
                    # We don't have to do anything for this flag, since we
                    # never bundle with a debug build of Python
                    pass
                elif let == 'E':
                    UseEnvironment = False
                elif let == 'h':
                    Help = True
                elif let == 'i':
                    Interactive = True
                elif let == 'I' and sys.version_info >= (3, ):
                    UseEnvironment = False
                    Isolated = True
                elif let == 'm' and i + 1 < len(sys.argv):
                    RunModule = sys.argv[i + 1 + skip]
                    RunModuleArgv = sys.argv[i + 1 + skip:]
                    skip = len(sys.argv)
                elif let == 'O':
                    Optimize += 1
                elif let == 'q' and sys.version_info >= (3, ):
                    QuietFlag = True
                elif let == 'Q' and sys.version_info < (3, ):
                    if arg.startswith('-' + let) and len(arg) > 2:
                        WarningDivision = arg[2:]
                    else:
                        WarningDivision = sys.argv[i + 1 + skip]
                        skip += 1
                    if WarningDivision not in ('old', 'warn', 'warnall',
                                               'new'):
                        sys.stderr.write(
                            """-Q option should be `-Qold', `-Qwarn', `-Qwarnall', or `-Qnew' only
usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `%s -h' for more information.
    """ % (sys.argv[0], sys.argv[0]))
                        sys.exit(2)
                    if arg.startswith('-' + let) and len(arg) > 2:
                        break
                elif let == 'R':
                    # We can't change the hash seed after start, so ignore it.
                    pass
                elif let == 's':
                    # We don't have to do anything for this flag, since we
                    # never have a local user site-packages directory in
                    # stand-alone mode
                    pass
                elif let == 'S':
                    NoSiteFlag = True
                elif let == 't' and sys.version_info < (3, ):
                    TabcheckFlag += 1
                elif let == 'u':
                    Unbuffered = True
                elif let == 'v':
                    VerboseFlag += 1
                elif let == 'V':
                    PrintVersion += 1
                elif let == 'W':
                    if arg.startswith('-' + let) and len(arg) > 2:
                        WarningOptions.append(arg[2:])
                        break
                    else:
                        WarningOptions.append(sys.argv[i + 1 + skip])
                        skip += 1
                elif let == 'x':
                    SkipFirstLine = True
                elif let == 'X':
                    # We don't have do anything for this flag, as the basic
                    # implementation doesn't have such options.
                    if arg.startswith('-' + let) and len(arg) > 2:
                        break
                    else:
                        skip += 1
                elif let == '3' and sys.version_info < (3, ):
                    Warning3k += 1
                    TabcheckFlag = max(TabcheckFlag, 1)
                else:
                    Help = True
        elif ((arg == '--check-hash-based-pycs'
               or arg.startswith('--check-hash-based-pycs='))
              and sys.version_info >= (3, 6)):
            # There is no exposure to this option in Python's DLL, so can't do
            # it
            if '=' not in arg:
                skip += 1
        elif arg == '--all':
            pass
        elif arg == '--help' or arg == '/?':
            Help = True
        elif arg == '--version':
            PrintVersion += 1
        elif arg == '-':
            Interactive = 'check'
            InteractiveArgv = ['-'] + sys.argv[i + 1 + skip:]
            skip = len(sys.argv)
        elif arg.startswith('-'):
            Help = True
        elif not RunFile:
            RunFile = sys.argv[i + skip]
            RunFileArgv = sys.argv[i + skip:]
            skip = len(sys.argv)
    if Help:
        print_version(0)
        print('usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...' %
              sys.argv[0])
        print(
            """Options and arguments (and corresponding environment variables):"""
        )
        if sys.version_info >= (3, ):
            print(
                """-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)""")
        print(
            """-B     : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --help, /?)
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x""")
        if sys.version_info >= (3, ):
            print(
                """-I     : isolate Python from the user's environment (implies -E and -s)"""
            )
        print(
            """-m mod : run library module as a script (terminates option list)
-O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO    : remove doc-strings in addition to the -O optimizations""")
        if sys.version_info >= (3, ):
            print(
                """-q     : don't print version and copyright messages on interactive startup"""
            )
        if sys.version_info < (3, ):
            print(
                """-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew"""
            )
        print(
            """-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S     : don't imply 'import site' on initialization""")
        if sys.version_info < (3, ):
            print(
                """-t     : issue warnings about inconsistent tab usage (-tt: issue errors)"""
            )
        print(
            """-u     : unbuffered binary stdout and stderr, stdin always buffered;
         also PYTHONUNBUFFERED=x
         see man page for details on internal buffering relating to '-u'
-v     : verbose (trace import statements); also PYTHONVERBOSE=x
         can be supplied multiple times to increase verbosity
-V     : print the Python version number and exit (also --version).  Use twice
         for more complete information.
-W arg : warning control; arg is action:message:category:module:lineno
         also PYTHONWARNINGS=arg
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option""")
        if sys.version_info < (3, ):
            print(
                """-3     : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix"""
            )  # noqa
        print("""file   : program read from script file
-      : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Stand-alone specific options:
--all  : imports all bundled modules.

Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ';'-separated list of directories prefixed to the
               default module search path.  The result is sys.path.
PYTHONCASEOK : ignore case in 'import' statements (Windows).""")
        sys.exit(0)
    if PrintVersion:
        print_version(PrintVersion)
        sys.exit(0)
    # Explicitly add the path of the current executable to the system paths and
    # its subpath of Lib\site-packages.  Installed Python always includes these
    # paths, but PyInstaller changes them to the expanded paths.
    sys.path[0:0] = [
        os.path.abspath(os.path.dirname(sys.executable)),
        os.path.abspath(
            os.path.join(os.path.dirname(sys.executable), 'Lib',
                         'site-packages'))
    ]
    if UseEnvironment:
        if os.environ.get('PYTHONDONTWRITEBYTECODE'):
            sys.dont_write_bytecode = True
        if Interactive is not True and os.environ.get('PYTHONINSPECT'):
            Interactive = 'check'
        Optimize = get_env_flag(Optimize, 'PYTHONOPTIMIZE')
        if os.environ.get('PYTHONPATH'):
            sys.path[0:0] = os.environ.get('PYTHONPATH').split(os.pathsep)
        StartupFile = os.environ.get('PYTHONSTARTUP')
        if Unbuffered is False and os.environ.get('PYTHONUNBUFFERED'):
            Unbuffered = True
        VerboseFlag = get_env_flag(VerboseFlag, 'PYTHONVERBOSE')
        if os.environ.get('PYTHONWARNINGS'):
            WarningOptions.extend(os.environ.get('PYTHONWARNINGS').split(','))
    if Isolated:
        # We have to suppress some environment effects
        os.environ.pop('PYTHONCASEOK', None)
        for key in list(sys.modules):  # for Python 3.x
            if hasattr(sys.modules[key], '_relax_case'):
                sys.modules[key]._relax_case = lambda: False
    if VerboseFlag:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_VerboseFlag').value = VerboseFlag
    if TabcheckFlag:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_TabcheckFlag').value = TabcheckFlag
    if Warning3k:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_Py3kWarningFlag').value = Warning3k
    if Optimize:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_OptimizeFlag').value = Optimize
    if WarningBytes:
        for idx, f in enumerate(warnings.filters):
            if f[2] == BytesWarning:
                warnings.filters[idx] = tuple(
                    ['default' if WarningBytes == 1 else 'error'] +
                    list(f)[1:])
        if not any([f for f in warnings.filters if f[2] == BytesWarning]):
            warnings.filterwarnings(
                'default' if WarningBytes == 1 else 'error',
                category=BytesWarning)
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_BytesWarningFlag').value = WarningBytes
    if WarningDivision == 'new':
        ctypes.c_int.in_dll(ctypes.pythonapi, '_Py_QnewFlag').value = 1
    elif WarningDivision in ('warn', 'warnall') or Warning3k:
        ctypes.c_int.in_dll(
            ctypes.pythonapi,
            'Py_DivisionWarningFlag').value = (2 if WarningDivision
                                               == 'warnall' else 1)
        warnings.filterwarnings('default',
                                category=DeprecationWarning,
                                message='classic [a-z]+ division')
    if Warning3k:
        warnings.filterwarnings('default', category=DeprecationWarning)
    sys.warnoptions[0:0] = WarningOptions
    warnings._processoptions(WarningOptions)
    bufsize = 1 if sys.version_info >= (3, ) else 0
    if Unbuffered:
        sys.stdin = os.fdopen(sys.stdin.fileno(), 'r', bufsize)
        sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', bufsize)
        sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', bufsize)
    if not NoSiteFlag:
        import site
        site.main()
    # Generate the globals/locals environment
    globenv = {}
    for key in list(globals().keys()):
        if key.startswith(
                '_') and not key in ['_frozen_name', '_setup_ctypes']:
            globenv[key] = globals()[key]
    if RunFile:
        run_file(RunFile, RunFileArgv, SkipFirstLine, globenv)
    elif RunModule:
        import runpy
        sys.argv[:] = RunModuleArgv
        runpy.run_module(RunModule, run_name='__main__')
    elif RunCommand is not None:
        if not Isolated:
            sys.path[0:0] = ['']
        sys.argv[:] = RunCommandArgv
        six.exec_(RunCommand, globenv)
    elif Interactive is None:
        Interactive = 'check'
    if Interactive:
        if not Isolated:
            sys.path[0:0] = ['']
        if InteractiveArgv:
            sys.argv[:] = InteractiveArgv
        if Interactive is True or sys.stdin.isatty():
            if not RunFile and not RunModule and not RunCommand and StartupFile:
                import runpy
                runpy.run_path(StartupFile, run_name='__main__')
            import code
            cons = code.InteractiveConsole(locals=globenv)
            if not sys.stdout.isatty():
                cons.raw_input = alternate_raw_input
                if not Unbuffered:
                    sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', bufsize)
                    sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', bufsize)
            banner = 'Python %s' % sys.version
            if not NoSiteFlag:
                banner += '\nType "help", "copyright", "credits" or "license" for more information.'
            if RunModule or RunCommand or QuietFlag:
                banner = ''
                if sys.version_info < (3, ):
                    skip_once(cons, 'write')
            kwargs = {}
            if sys.version_info >= (3, 6):
                kwargs['exitmsg'] = ''
            cons.interact(banner=banner, **kwargs)
        else:
            src = sys.stdin.read()
            # This doesn't work the way I expect for some reason
            #  interp = code.InteractiveInterpreter(locals=globenv)
            #  interp.runsource(src, '<stdin>')
            # But an exec works fine
            globenv['__file__'] = '<stdin>'
            six.exec_(src, globenv)
Example #11
0
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
Example #12
0
def pymain(argv, init=None):
    import sys
    from os.path import dirname, realpath

    # sys.executable
    # on windows there are
    #   gpython-script.py
    #   gpython.exe
    #   gpython.manifest
    # and argv[0] is gpython-script.py
    exe = realpath(argv[0])
    argv = argv[1:]
    if exe.endswith('-script.py'):
        exe = exe[:-len('-script.py')]
        exe = exe + '.exe'
    sys._gpy_underlying_executable = sys.executable
    sys.executable = exe

    # `python /path/to/gpython` adds /path/to to sys.path[0] - remove it.
    # `gpython file` will add path-to-file to sys.path[0] by itself, and
    # /path/to/gpython is unnecessary and would create difference in behaviour
    # in between gpython and python.
    exedir = dirname(exe)
    if sys.path[0] == exedir:
        del sys.path[0]
    else:
        # buildout injects `sys.path[0:0] = eggs` into python scripts.
        # detect that and remove sys.path entry corresponding to exedir.
        if not _is_buildout_script(exe):
            raise RuntimeError(
                'pymain: internal error: sys.path[0] was not set by underlying python to dirname(exe):'
                '\n\n\texe:\t%s\n\tsys.path[0]:\t%s' % (exe, sys.path[0]))
        else:
            if exedir in sys.path:
                sys.path.remove(exedir)
            else:
                raise RuntimeError(
                    'pymain: internal error: sys.path does not contain dirname(exe):'
                    '\n\n\texe:\t%s\n\tsys.path:\t%s' % (exe, sys.path))

    run = None  # function to run according to -c/-m/file/stdin/interactive
    version = False  # set if `-V`
    warnoptions = []  # collected `-W arg`
    reexec_with = [
    ]  # reexecute underlying python with those options (e.g. -O, -S, ...)
    reexec_argv = [
    ]  # if reexecuting, reexecute with this application-level argv
    inspect = False  # inspect interactively at the end

    igetopt = _IGetOpt(argv, _pyopt, _pyopt_long)
    for (opt, arg) in igetopt:
        # options that require reexecuting through underlying python with that -<opt>
        if opt in (
                '-O',  # optimize
        ):
            reexec_with.append(opt)
            if arg is not None:
                reexec_with.append(arg)
            continue

        reexec_argv.append(opt)
        if arg is not None:
            reexec_argv.append(arg)

        # -V / --version
        if opt in ('-V', '--version'):
            version = True
            break

        # -c command
        elif opt == '-c':
            cmd = arg
            sys.argv = ['-c'] + igetopt.argv  # python leaves '-c' as argv[0]
            sys.path.insert(0, '')  # cwd

            def run(mmain):
                import six
                six.exec_(cmd, mmain.__dict__)

            break

        # -m module
        elif opt == '-m':
            mod = arg
            sys.argv = [mod] + igetopt.argv
            # sys.path <- cwd
            # NOTE python2 injects '', while python3 injects realpath('')
            # we stick to python3 behaviour, as it is more sane because e.g.
            # import path does not change after chdir.
            sys.path.insert(0, realpath(''))  # realpath(cwd)

            def run(mmain):
                import runpy
                # search sys.path for module and run corresponding .py file as script
                # NOTE runpy._run_module_as_main works on sys.modules['__main__']
                sysmain = sys.modules['__main__']
                assert sysmain is mmain, (sysmain, mmain)
                runpy._run_module_as_main(mod)

            break

        # -W arg  (warning control)
        elif opt == '-W':
            warnoptions.append(arg)

        # -i inspect interactively
        elif opt == '-i':
            inspect = True

        else:
            print("unknown option: '%s'" % opt, file=sys.stderr)
            sys.exit(2)

    argv = igetopt.argv
    reexec_argv += argv
    if run is None:
        # file
        if len(argv) > 0 and argv[0] != '-':
            sys.argv = argv
            filepath = argv[0]
            # starting from cpython 3.9 __file__ is always absolute
            # https://bugs.python.org/issue20443
            if sys.version_info >= (3, 9):
                filepath = realpath(filepath)

            sys.path.insert(0, realpath(
                dirname(filepath)))  # not abspath -> see PySys_SetArgvEx

            def run(mmain):
                mmain.__file__ = filepath
                _execfile(filepath, mmain.__dict__)

        # interactive console / program on non-tty stdin
        else:
            sys.argv = [''] if len(argv) == 0 else argv  # e.g. ['-']
            sys.path.insert(0, '')  # cwd

            if sys.stdin.isatty() or inspect:
                inspect = False  # no console after console

                def run(mmain):
                    mmain.__file__ = '<stdin>'
                    _interact(mmain)
            else:

                def run(mmain):
                    import six
                    prog = sys.stdin.read()
                    mmain.__file__ = '<stdin>'
                    six.exec_(prog, mmain.__dict__)

    # ---- options processed -> start the interpreter ----

    # reexec underlying interpreter on options that we cannot handle at python
    # level after underlying interpreter is already started. For example
    #
    #   gpython -O file.py
    #
    # is reexecuted as
    #
    #   python -O gpython file.py
    if len(reexec_with) > 0:
        import os
        argv = [sys._gpy_underlying_executable
                ] + reexec_with + [sys.executable] + reexec_argv
        os.execv(argv[0], argv)

    if init is not None:
        init()

    # handle -V/--version
    if version:
        ver = []
        if 'GPython' in sys.version:
            golang = sys.modules['golang']  # must be already imported
            gevent = sys.modules.get('gevent', None)
            gpyver = 'GPython %s' % golang.__version__
            if gevent is not None:
                gpyver += ' [gevent %s]' % gevent.__version__
            else:
                gpyver += ' [threads]'
            ver.append(gpyver)

        import platform
        pyimpl = platform.python_implementation()

        v = _version_info_str
        if pyimpl == 'CPython':
            ver.append('CPython %s' % v(sys.version_info))
        elif pyimpl == 'PyPy':
            ver.append('PyPy %s' % v(sys.pypy_version_info))
            ver.append('Python %s' % v(sys.version_info))
        else:
            ver = []  # unknown

        ver = ' / '.join(ver)
        if ver == '':
            # unknown implementation: just print full sys.version
            ver = sys.version

        print(ver, file=sys.stderr)
        return

    # init warnings
    if len(warnoptions) > 0:
        # NOTE warnings might be already imported by code that calls pymain.
        # This way we cannot set `sys.warnoptions = warnoptions` and just
        # import/reload warnings (if we reload warnings, it will loose all
        # previous setup that pymain caller might have done to it).
        # -> only amend warnings setup
        #
        # NOTE $PYTHONWARNINGS is handled by underlying python natively.
        import warnings
        sys.warnoptions += warnoptions
        warnings._processoptions(warnoptions)

    # inject new empty __main__ module instead of previous __main__
    import types
    mmain = types.ModuleType('__main__')
    mmain.__file__ = None
    mmain.__loader__ = None
    mmain.__package__ = None
    mmain.__doc__ = None
    sys.modules['__main__'] = mmain

    # execute -m/-c/file/interactive
    import traceback
    try:
        run(mmain)
    except:
        # print exception becore going to interactive inspect
        if inspect:
            traceback.print_exc()
        else:
            raise
    finally:
        # interactive inspect
        if inspect:
            _interact(mmain, banner='')
Example #13
0
 def update_event(self, inp=-1):
     self.set_output_val(0, warnings._processoptions(self.input(0)))