Exemple #1
0
 def test_getimporter(self):
     import imp, os
     # an existing directory
     importer = imp._getimporter(self.udir)
     assert importer is None
     # an existing file
     path = os.path.join(self.udir, 'test_getimporter')
     open(path, 'w').close()
     importer = imp._getimporter(path)
     assert isinstance(importer, imp.NullImporter)
     # a non-existing path
     path = os.path.join(self.udir, 'does_not_exist_at_all')
     importer = imp._getimporter(path)
     assert isinstance(importer, imp.NullImporter)
     # a mostly-empty zip file
     path = os.path.join(self.udir, 'test_getimporter.zip')
     f = open(path, 'wb')
     f.write('PK\x03\x04\n\x00\x00\x00\x00\x00P\x9eN>\x00\x00\x00\x00\x00'
             '\x00\x00\x00\x00\x00\x00\x00\x05\x00\x15\x00emptyUT\t\x00'
             '\x03wyYMwyYMUx\x04\x00\xf4\x01d\x00PK\x01\x02\x17\x03\n\x00'
             '\x00\x00\x00\x00P\x9eN>\x00\x00\x00\x00\x00\x00\x00\x00\x00'
             '\x00\x00\x00\x05\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00'
             '\xa4\x81\x00\x00\x00\x00emptyUT\x05\x00\x03wyYMUx\x00\x00PK'
             '\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00@\x00\x00\x008\x00'
             '\x00\x00\x00\x00')
     f.close()
     importer = imp._getimporter(path)
     import zipimport
     assert isinstance(importer, zipimport.zipimporter)
Exemple #2
0
 def test_getimporter(self):
     import imp, os
     # an existing directory
     importer = imp._getimporter(self.udir)
     assert importer is None
     # an existing file
     path = os.path.join(self.udir, 'test_getimporter')
     open(path, 'w').close()
     importer = imp._getimporter(path)
     assert isinstance(importer, imp.NullImporter)
     # a non-existing path
     path = os.path.join(self.udir, 'does_not_exist_at_all')
     importer = imp._getimporter(path)
     assert isinstance(importer, imp.NullImporter)
     # a mostly-empty zip file
     path = os.path.join(self.udir, 'test_getimporter.zip')
     f = open(path, 'wb')
     f.write('PK\x03\x04\n\x00\x00\x00\x00\x00P\x9eN>\x00\x00\x00\x00\x00'
             '\x00\x00\x00\x00\x00\x00\x00\x05\x00\x15\x00emptyUT\t\x00'
             '\x03wyYMwyYMUx\x04\x00\xf4\x01d\x00PK\x01\x02\x17\x03\n\x00'
             '\x00\x00\x00\x00P\x9eN>\x00\x00\x00\x00\x00\x00\x00\x00\x00'
             '\x00\x00\x00\x05\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00'
             '\xa4\x81\x00\x00\x00\x00emptyUT\x05\x00\x03wyYMUx\x00\x00PK'
             '\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00@\x00\x00\x008\x00'
             '\x00\x00\x00\x00')
     f.close()
     importer = imp._getimporter(path)
     import zipimport
     assert isinstance(importer, zipimport.zipimporter)
Exemple #3
0
    def test_getimporter(self):
        import imp, os

        # an existing directory
        importer = imp._getimporter(self.udir)
        assert importer is None
        # an existing file
        path = os.path.join(self.udir, "test_getimporter")
        with open(path, "w") as f:
            pass
        importer = imp._getimporter(path)
        assert isinstance(importer, imp.NullImporter)
        # a non-existing path
        path = os.path.join(self.udir, "does_not_exist_at_all")
        importer = imp._getimporter(path)
        assert isinstance(importer, imp.NullImporter)
        # a mostly-empty zip file
        path = os.path.join(self.udir, "test_getimporter.zip")
        with open(path, "wb") as f:
            f.write(
                "PK\x03\x04\n\x00\x00\x00\x00\x00P\x9eN>\x00\x00\x00\x00\x00"
                "\x00\x00\x00\x00\x00\x00\x00\x05\x00\x15\x00emptyUT\t\x00"
                "\x03wyYMwyYMUx\x04\x00\xf4\x01d\x00PK\x01\x02\x17\x03\n\x00"
                "\x00\x00\x00\x00P\x9eN>\x00\x00\x00\x00\x00\x00\x00\x00\x00"
                "\x00\x00\x00\x05\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00"
                "\xa4\x81\x00\x00\x00\x00emptyUT\x05\x00\x03wyYMUx\x00\x00PK"
                "\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00@\x00\x00\x008\x00"
                "\x00\x00\x00\x00"
            )
        importer = imp._getimporter(path)
        import zipimport

        assert isinstance(importer, zipimport.zipimporter)
Exemple #4
0
            filename = sys.argv[0]
            mainmodule.__file__ = filename
            sys.path.insert(0, 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".
                    args = (execfile, filename, mainmodule.__dict__)
            success = run_toplevel(*args)

    except SystemExit, e:
        status = e.code
        if inspect_requested():
            display_exception()
Exemple #5
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
Exemple #6
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
Exemple #7
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
Exemple #8
0
            filename = sys.argv[0]
            mainmodule.__file__ = filename
            sys.path.insert(0, 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".
                    args = (execfile, filename, mainmodule.__dict__)
            success = run_toplevel(*args)

    except SystemExit, e:
        status = e.code
        if inspect_requested():
            display_exception()
Exemple #9
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