[pypy-commit] pypy py3k: Use the new io stack for sys.stdout &friends

amauryfa noreply at buildbot.pypy.org
Sat Oct 22 00:28:34 CEST 2011


Author: Amaury Forgeot d'Arc <amauryfa at gmail.com>
Branch: py3k
Changeset: r48328:8b87c77d1645
Date: 2011-10-22 00:24 +0200
http://bitbucket.org/pypy/pypy/changeset/8b87c77d1645/

Log:	Use the new io stack for sys.stdout &friends sys.stdout is not
	prebuilt anymore
	- translated code build it in app_main (to get all options & env vars)
	- untranslated code build it in sys.__init__ (easier for tests)

diff --git a/lib_pypy/_pypy_interact.py b/lib_pypy/_pypy_interact.py
--- a/lib_pypy/_pypy_interact.py
+++ b/lib_pypy/_pypy_interact.py
@@ -55,11 +55,7 @@
             else:
                 prompt = getattr(sys, 'ps1', '>>> ')
             try:
-                line = raw_input(prompt)
-                # Can be None if sys.stdin was redefined
-                encoding = getattr(sys.stdin, 'encoding', None)
-                if encoding and not isinstance(line, unicode):
-                    line = line.decode(encoding)
+                line = input(prompt)
             except EOFError:
                 console.write("\n")
                 break
diff --git a/pypy/interpreter/baseobjspace.py b/pypy/interpreter/baseobjspace.py
--- a/pypy/interpreter/baseobjspace.py
+++ b/pypy/interpreter/baseobjspace.py
@@ -489,16 +489,16 @@
         self.exceptions_module = Module(self, w_name)
         self.exceptions_module.install()
 
+        from pypy.module.imp import Module
+        w_name = self.wrap('imp')
+        mod = Module(self, w_name)
+        mod.install()
+
         from pypy.module.sys import Module
         w_name = self.wrap('sys')
         self.sys = Module(self, w_name)
         self.sys.install()
 
-        from pypy.module.imp import Module
-        w_name = self.wrap('imp')
-        mod = Module(self, w_name)
-        mod.install()
-
         from pypy.module.__builtin__ import Module
         w_name = self.wrap('builtins')
         self.builtin = Module(self, w_name)
diff --git a/pypy/module/__builtin__/__init__.py b/pypy/module/__builtin__/__init__.py
--- a/pypy/module/__builtin__/__init__.py
+++ b/pypy/module/__builtin__/__init__.py
@@ -13,7 +13,6 @@
 
     appleveldefs = {
         'execfile'      : 'app_io.execfile',
-        'raw_input'     : 'app_io.raw_input',
         'input'         : 'app_io.input',
         'print'         : 'app_io.print_',
 
diff --git a/pypy/module/__builtin__/app_io.py b/pypy/module/__builtin__/app_io.py
--- a/pypy/module/__builtin__/app_io.py
+++ b/pypy/module/__builtin__/app_io.py
@@ -27,8 +27,8 @@
     co = compile(source.rstrip()+"\n", filename, 'exec')
     exec(co, glob, loc)
 
-def raw_input(prompt=None):
-    """raw_input([prompt]) -> string
+def input(prompt=None):
+    """input([prompt]) -> string
 
 Read a string from standard input.  The trailing newline is stripped.
 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
@@ -37,11 +37,11 @@
     try:
         stdin = sys.stdin
     except AttributeError:
-        raise RuntimeError("[raw_]input: lost sys.stdin")
+        raise RuntimeError("input: lost sys.stdin")
     try:
         stdout = sys.stdout
     except AttributeError:
-        raise RuntimeError("[raw_]input: lost sys.stdout")
+        raise RuntimeError("input: lost sys.stdout")
 
     # hook for the readline module
     if (hasattr(sys, '__raw_input__') and
@@ -66,10 +66,6 @@
         return line[:-1]
     return line
 
-def input(prompt=None):
-    """Equivalent to eval(raw_input(prompt))."""
-    return eval(raw_input(prompt))
-
 def print_(*args, **kwargs):
     """The new-style print function from py3k."""
     fp = kwargs.pop("file", sys.stdout)
@@ -78,8 +74,6 @@
     def write(data):
         if not isinstance(data, str):
             data = str(data)
-        if getattr(fp, 'encoding', None):
-            data = data.encode(fp.encoding)
         fp.write(data)
     sep = kwargs.pop("sep", None)
     if sep is not None:
diff --git a/pypy/module/sys/__init__.py b/pypy/module/sys/__init__.py
--- a/pypy/module/sys/__init__.py
+++ b/pypy/module/sys/__init__.py
@@ -28,12 +28,6 @@
         'maxsize'               : 'space.wrap(sys.maxint)',
         'byteorder'             : 'space.wrap(sys.byteorder)', 
         'maxunicode'            : 'space.wrap(vm.MAXUNICODE)',
-        'stdin'                 : 'state.getio(space).w_stdin',
-        '__stdin__'             : 'state.getio(space).w_stdin',
-        'stdout'                : 'state.getio(space).w_stdout',
-        '__stdout__'            : 'state.getio(space).w_stdout',
-        'stderr'                : 'state.getio(space).w_stderr',
-        '__stderr__'            : 'state.getio(space).w_stderr',
         'pypy_objspaceclass'    : 'space.wrap(repr(space))',
         #'prefix'               : # added by pypy_initial_path() when it 
         #'exec_prefix'          : # succeeds, pointing to trunk or /usr
@@ -116,6 +110,18 @@
                 w_handle = vm.get_dllhandle(space)
                 space.setitem(self.w_dict, space.wrap("dllhandle"), w_handle)
 
+        if not space.config.translating:
+            # Install standard streams for tests that don't call app_main
+            space.appexec([], """():
+                import sys, io
+                sys.stdin = sys.__stdin__ = io.open(0, "r", closefd=False)
+                sys.stdin.buffer.raw.name = "<stdin>"
+                sys.stdout = sys.__stdout__ = io.open(1, "w", closefd=False)
+                sys.stdout.buffer.raw.name = "<stdout>"
+                sys.stderr = sys.__stderr__ = io.open(2, "w", closefd=False)
+                sys.stderr.buffer.raw.name = "<stderr>"
+               """)
+
     def getmodule(self, name):
         space = self.space
         w_modules = self.get('modules') 
diff --git a/pypy/module/sys/state.py b/pypy/module/sys/state.py
--- a/pypy/module/sys/state.py
+++ b/pypy/module/sys/state.py
@@ -84,31 +84,6 @@
 def get(space):
     return space.fromcache(State)
 
-class IOState:
-    def __init__(self, space):
-        from pypy.module._file.interp_file import W_File
-        self.space = space
-
-        stdin = W_File(space)
-        stdin.file_fdopen(0, "r", 1)
-        stdin.name = '<stdin>'
-        self.w_stdin = space.wrap(stdin)
-
-        stdout = W_File(space)
-        stdout.file_fdopen(1, "w", 1)
-        stdout.name = '<stdout>'
-        self.w_stdout = space.wrap(stdout)
-
-        stderr = W_File(space)
-        stderr.file_fdopen(2, "w", 0)
-        stderr.name = '<stderr>'
-        self.w_stderr = space.wrap(stderr)
-
-        stdin._when_reading_first_flush(stdout)
-
-def getio(space):
-    return space.fromcache(IOState)
-
 def pypy_getudir(space):
     """NOT_RPYTHON
     (should be removed from interpleveldefs before translation)"""
diff --git a/pypy/translator/goal/app_main.py b/pypy/translator/goal/app_main.py
--- a/pypy/translator/goal/app_main.py
+++ b/pypy/translator/goal/app_main.py
@@ -33,7 +33,7 @@
         except:
             # not an integer: print it to stderr
             try:
-                print >> sys.stderr, exitcode
+                print(exitcode, file=sys.stderr)
             except:
                 pass   # too bad
             exitcode = 1
@@ -74,16 +74,16 @@
         # extra debugging info in case the code below goes very wrong
         if DEBUG and hasattr(sys, 'stderr'):
             s = getattr(etype, '__name__', repr(etype))
-            print >> sys.stderr, "debug: exception-type: ", s
-            print >> sys.stderr, "debug: exception-value:", str(evalue)
+            print("debug: exception-type: ", s, file=sys.stderr)
+            print("debug: exception-value:", str(evalue), file=sys.stderr)
             tbentry = etraceback
             if tbentry:
                 while tbentry.tb_next:
                     tbentry = tbentry.tb_next
                 lineno = tbentry.tb_lineno
                 filename = tbentry.tb_frame.f_code.co_filename
-                print >> sys.stderr, "debug: exception-tb:    %s:%d" % (
-                    filename, lineno)
+                print("debug: exception-tb:    %s:%d" % (filename, lineno),
+                      file=sys.stderr)
 
         # set the sys.last_xxx attributes
         sys.last_type = etype
@@ -101,10 +101,10 @@
         except AttributeError:
             pass   # too bad
         else:
-            print >> stderr, 'Error calling sys.excepthook:'
+            print('Error calling sys.excepthook:', file=stderr)
             originalexcepthook(*sys.exc_info())
-            print >> stderr
-            print >> stderr, 'Original exception was:'
+            print(file=stderr)
+            print('Original exception was:', file=stderr)
 
     # we only get here if sys.excepthook didn't do its job
     originalexcepthook(etype, evalue, etraceback)
@@ -117,7 +117,7 @@
     try:
         options = sys.pypy_translation_info
     except AttributeError:
-        print >> sys.stderr, 'no translation information found'
+        print('no translation information found', file=sys.stderr)
     else:
         optitems = options.items()
         optitems.sort()
@@ -170,14 +170,6 @@
         from os import fdopen
     return fdopen(fd, mode, bufsize)
 
-def set_unbuffered_io():
-    sys.stdin  = sys.__stdin__  = fdopen(0, 'rb', 0)
-    sys.stdout = sys.__stdout__ = fdopen(1, 'wb', 0)
-    sys.stderr = sys.__stderr__ = fdopen(2, 'wb', 0)
-
-def set_fully_buffered_io():
-    sys.stdout = sys.__stdout__ = fdopen(1, 'w')
-
 # ____________________________________________________________
 # Main entry point
 
@@ -257,6 +249,56 @@
             sys.path.append(dir)
             _seen[dir] = True
 
+def initstdio(encoding, unbuffered):
+    if ':' in encoding:
+        encoding, errors = encoding.split(':', 1)
+    else:
+        errors = None
+
+    sys.stdin = sys.__stdin__ = create_stdio(
+        0, False, "<stdin>", encoding, errors, unbuffered)
+    sys.stdout = sys.__stdout__ = create_stdio(
+        1, True, "<stdout>", encoding, errors, unbuffered)
+    sys.stderr = sys.__stderr__ = create_stdio(
+        2, True, "<stderr>", encoding, errors, unbuffered)
+
+def create_stdio(fd, writing, name, encoding, errors, unbuffered):
+    import io
+
+    if writing:
+        mode = "wb"
+    else:
+        mode= "rb"
+    # stdin is always opened in buffered mode, first because it
+    # shouldn't make a difference in common use cases, second because
+    # TextIOWrapper depends on the presence of a read1() method which
+    # only exists on buffered streams.
+    if writing:
+        buffering = 0
+    else:
+        buffering = -1
+    if sys.platform == 'win32' and not writing:
+        # translate \r\n to \n for sys.stdin on Windows
+        newline = None
+    else:
+        newline = '\n'
+    buf = io.open(fd, mode, buffering, closefd=False)
+
+    if buffering:
+        raw = buf.raw
+    else:
+        raw = buf
+    raw.name = name
+    if unbuffered or raw.isatty():
+        line_buffering = True
+    else:
+        line_buffering = False
+
+    stream = io.TextIOWrapper(buf, encoding, errors,
+                              newline=newline,
+                              line_buffering=line_buffering)
+    return stream
+    
 def set_io_encoding(io_encoding):
     try:
         import _file
@@ -467,10 +509,10 @@
     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()
+    readenv = not ignore_environment
+    io_encoding = ((readenv and os.getenv("PYTHONIOENCODING"))
+                   or sys.getfilesystemencoding())
+    initstdio(io_encoding, unbuffered)
 
     mainmodule = type(sys)('__main__')
     sys.modules['__main__'] = mainmodule
@@ -481,12 +523,6 @@
         except:
             print("'import site' failed", file=sys.stderr)
 
-    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(','))
@@ -606,6 +642,10 @@
                     args = (runpy._run_module_as_main, '__main__', False)
                 else:
                     # no.  That's the normal path, "pypy stuff.py".
+                    def execfile(filename, namespace):
+                        with open(filename) as f:
+                            code = f.read()
+                        exec(code, namespace)
                     args = (execfile, filename, mainmodule.__dict__)
             success = run_toplevel(*args)
 
@@ -653,29 +693,55 @@
     setup_sys_executable(executable, nanos)
     try:
         cmdline = parse_command_line(argv)
-    except CommandLineError, e:
+    except CommandLineError as e:
         print_error(str(e))
         return 2
-    except SystemExit, e:
+    except SystemExit as e:
         return e.code or 0
     setup_initial_paths(**cmdline)
     return run_command_line(**cmdline)
 
 
 if __name__ == '__main__':
-    import autopath
-    import nanos
-    # obscure! try removing the following line, see how it crashes, and
-    # guess why...
-    ImStillAroundDontForgetMe = sys.modules['__main__']
+    "For unit tests only"
+    import os as nanos
+    import os
 
-    # debugging only
+    if len(sys.argv) > 1 and sys.argv[1] == '--argparse-only':
+        import io
+        del sys.argv[:2]
+        sys.stdout = sys.stderr = io.StringIO()
+        try:
+            options = parse_command_line(sys.argv)
+        except SystemExit:
+            print('SystemExit', file=sys.__stdout__)
+            print(sys.stdout.getvalue(), file=sys.__stdout__)
+            raise
+        except BaseException as e:
+            print('Error', file=sys.__stdout__)
+            raise
+        else:
+            print('Return', file=sys.__stdout__)
+        print(options, file=sys.__stdout__)
+        print(sys.argv, file=sys.__stdout__)
+
+    # Testing python on python is hard:
+    # Some code above (run_command_line) will create a new module
+    # named __main__ and store it into sys.modules.  There it will
+    # replace the __main__ module that CPython created to execute the
+    # lines you are currently reading. This will free the module, and
+    # all globals (os, sys...) will be set to None.
+    # To avoid this we make a copy of our __main__ module.
+    sys.modules['__cpython_main__'] = sys.modules['__main__']
+
     def pypy_initial_path(s):
+        return ["../lib-python/3.2", "../lib_pypy", ".."]
         from pypy.module.sys.state import getinitialpath
         try:
             return getinitialpath(s)
         except OSError:
             return None
+    sys.pypy_initial_path = pypy_initial_path
 
     # add an emulator for these pypy-only or 2.7-only functions
     # (for test_pyc_commandline_argument)
@@ -711,10 +777,6 @@
     old_argv = sys.argv
     old_path = sys.path
 
-    from pypy.module.sys.version import PYPY_VERSION
-    sys.pypy_version_info = PYPY_VERSION
-    sys.pypy_initial_path = pypy_initial_path
-    os = nanos.os_module_for_testing
     try:
         sys.exit(int(entry_point(sys.argv[0], sys.argv[1:], os)))
     finally:
diff --git a/pypy/translator/goal/test2/mymodule.py b/pypy/translator/goal/test2/mymodule.py
--- a/pypy/translator/goal/test2/mymodule.py
+++ b/pypy/translator/goal/test2/mymodule.py
@@ -2,9 +2,9 @@
 
 import sys
 
-print 'mymodule running'
-print 'Name:', __name__
-print 'File:', __file__
-print 'Argv:', sys.argv
+print('mymodule running')
+print('Name:', __name__)
+print('File:', __file__)
+print('Argv:', sys.argv)
 
 somevalue = "foobar"
diff --git a/pypy/translator/goal/test2/test_app_main.py b/pypy/translator/goal/test2/test_app_main.py
--- a/pypy/translator/goal/test2/test_app_main.py
+++ b/pypy/translator/goal/test2/test_app_main.py
@@ -8,7 +8,15 @@
 from pypy.tool.udir import udir
 from contextlib import contextmanager
 
-banner = sys.version.splitlines()[0]
+python3 = os.environ.get("PYTHON3", "python3")
+
+def get_banner():
+    p = subprocess.Popen([python3, "-c",
+                          "import sys; print(sys.version.splitlines()[0])"],
+                         stdout=subprocess.PIPE)
+    return p.stdout.read().rstrip()
+banner = get_banner()
+print repr(banner)
 
 app_main = os.path.join(autopath.this_dir, os.pardir, 'app_main.py')
 app_main = os.path.abspath(app_main)
@@ -53,29 +61,28 @@
     return py.path.local().bestrelpath(pdir)
 
 demo_script = getscript("""
-    print 'hello'
-    print 'Name:', __name__
-    print 'File:', __file__
+    print('hello')
+    print('Name:', __name__)
+    print('File:', __file__)
     import sys
-    print 'Exec:', sys.executable
-    print 'Argv:', sys.argv
-    print 'goodbye'
+    print('Exec:', sys.executable)
+    print('Argv:', sys.argv)
+    print('goodbye')
     myvalue = 6*7
     """)
 
 crashing_demo_script = getscript("""
-    print 'Hello2'
+    print('Hello2')
     myvalue2 = 11
     ooups
     myvalue2 = 22
-    print 'Goodbye2'   # should not be reached
+    print('Goodbye2')  # should not be reached
     """)
 
 
 class TestParseCommandLine:
 
-    def check_options(self, options, sys_argv, **expected):
-        assert sys.argv == sys_argv
+    def check_options(self, options, sys_argv, expected):
         for key, value in expected.items():
             assert options[key] == value
         for key, value in options.items():
@@ -84,25 +91,20 @@
                     "option %r has unexpectedly the value %r" % (key, value))
 
     def check(self, argv, **expected):
-        import StringIO
-        from pypy.translator.goal import app_main
-        saved_sys_argv = sys.argv[:]
-        saved_sys_stdout = sys.stdout
-        saved_sys_stderr = sys.stdout
-        app_main.os = os
-        try:
-            sys.stdout = sys.stderr = StringIO.StringIO()
-            try:
-                options = app_main.parse_command_line(argv)
-            except SystemExit:
-                output = expected['output_contains']
-                assert output in sys.stdout.getvalue()
-            else:
-                self.check_options(options, **expected)
-        finally:
-            sys.argv[:] = saved_sys_argv
-            sys.stdout = saved_sys_stdout
-            sys.stderr = saved_sys_stderr
+        p = subprocess.Popen([python3, app_main,
+                              '--argparse-only'] + list(argv),
+                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+        res = p.wait()
+        outcome = p.stdout.readline()
+        if outcome == 'SystemExit\n':
+            output = p.stdout.read()
+            assert expected['output_contains'] in output
+        else:
+            app_options = eval(p.stdout.readline())
+            sys_argv = eval(p.stdout.readline())
+            app_options['sys_argv'] = sys_argv
+            self.check_options(app_options, sys_argv, expected)
 
     def test_all_combinations_I_can_think_of(self):
         self.check([], sys_argv=[''], run_stdin=True)
@@ -227,7 +229,7 @@
         return child
 
     def spawn(self, argv):
-        return self._spawn(sys.executable, [app_main] + argv)
+        return self._spawn(python3, [app_main] + argv)
 
     def test_interactive(self):
         child = self.spawn([])
@@ -336,7 +338,7 @@
     def test_atexit(self):
         child = self.spawn([])
         child.expect('>>> ')
-        child.sendline('def f(): print "foobye"')
+        child.sendline('def f(): print("foobye")')
         child.sendline('')
         child.sendline('import atexit; atexit.register(f)')
         child.sendline('6*7')
@@ -407,7 +409,8 @@
             os.environ['PYTHONPATH'] = old
 
     def test_unbuffered(self):
-        line = 'import os,sys;sys.stdout.write(str(789));os.read(0,1)'
+        # In Python3, -u affects the "binary layer" of sys.stdout.
+        line = 'import os,sys;sys.stdout.buffer.write(str(789).encode());os.read(0,1)'
         child = self.spawn(['-u', '-c', line])
         child.expect('789')    # expect to see it before the timeout hits
         child.sendline('X')
@@ -447,8 +450,7 @@
         if sys.platform == "win32":
             skip("close_fds is not supported on Windows platforms")
         import subprocess, select, os
-        python = sys.executable
-        pipe = subprocess.Popen([python, app_main, "-u", "-i"],
+        pipe = subprocess.Popen([python3, app_main, "-u", "-i"],
                                 stdout=subprocess.PIPE,
                                 stdin=subprocess.PIPE,
                                 stderr=subprocess.STDOUT,
@@ -472,7 +474,7 @@
         os.environ['PYTHONINSPECT_'] = '1'
         try:
             path = getscript("""
-                print 6*7
+                print(6*7)
                 """)
             child = self.spawn([path])
             child.expect('42')
@@ -484,7 +486,7 @@
         path = getscript("""
             import os
             os.environ['PYTHONINSPECT'] = '1'
-            print 6*7
+            print(6*7)
             """)
         child = self.spawn([path])
         child.expect('42')
@@ -503,6 +505,7 @@
             del os.environ['PYTHONINSPECT_']
 
     def test_stdout_flushes_before_stdin_blocks(self):
+        skip("Python3 does not implement this behavior")
         # This doesn't really test app_main.py, but a behavior that
         # can only be checked on top of py.py with pexpect.
         path = getscript("""
@@ -510,10 +513,10 @@
             sys.stdout.write('Are you suggesting coconuts migrate? ')
             line = sys.stdin.readline()
             assert line.rstrip() == 'Not at all. They could be carried.'
-            print 'A five ounce bird could not carry a one pound coconut.'
+            print('A five ounce bird could not carry a one pound coconut.')
             """)
         py_py = os.path.join(autopath.pypydir, 'bin', 'py.py')
-        child = self._spawn(sys.executable, [py_py, path])
+        child = self._spawn(sys.executable, [py_py, '-S', path])
         child.expect('Are you suggesting coconuts migrate?', timeout=120)
         child.sendline('Not at all. They could be carried.')
         child.expect('A five ounce bird could not carry a one pound coconut.')
@@ -521,14 +524,14 @@
     def test_no_space_before_argument(self):
         if not hasattr(runpy, '_run_module_as_main'):
             skip("requires CPython >= 2.6")
-        child = self.spawn(['-cprint "hel" + "lo"'])
+        child = self.spawn(['-cprint("hel" + "lo")'])
         child.expect('hello')
 
         child = self.spawn(['-mpypy.translator.goal.test2.mymodule'])
         child.expect('mymodule running')
 
     def test_ps1_only_if_interactive(self):
-        argv = ['-c', 'import sys; print hasattr(sys, "ps1")']
+        argv = ['-c', 'import sys; print(hasattr(sys, "ps1"))']
         child = self.spawn(argv)
         child.expect('False')
 
@@ -536,7 +539,7 @@
 
     def run_with_status_code(self, cmdline, senddata='', expect_prompt=False,
             expect_banner=False, python_flags='', env=None):
-        cmdline = '%s %s "%s" %s' % (sys.executable, python_flags,
+        cmdline = '%s %s "%s" %s' % (python3, python_flags,
                                      app_main, cmdline)
         print 'POPEN:', cmdline
         process = subprocess.Popen(
@@ -586,9 +589,9 @@
         assert 'Goodbye2' not in data
 
     def test_option_W(self):
-        data = self.run('-W d -c "print 42"')
+        data = self.run('-W d -c "print(42)"')
         assert '42' in data
-        data = self.run('-Wd -c "print 42"')
+        data = self.run('-Wd -c "print(42)"')
         assert '42' in data
 
     def test_option_W_crashing(self):
@@ -604,7 +607,7 @@
         assert "Invalid -W option ignored: invalid action:" in data
 
     def test_option_c(self):
-        data = self.run('-c "print 6**5"')
+        data = self.run('-c "print(6**5)"')
         assert '7776' in data
 
     def test_no_pythonstartup(self):
@@ -623,7 +626,7 @@
         try:
             os.environ['PYTHONWARNINGS'] = "once,error"
             data = self.run('-W ignore -W default '
-                            '-c "import sys; print sys.warnoptions"')
+                            '-c "import sys; print(sys.warnoptions)"')
             assert "['ignore', 'default', 'once', 'error']" in data
         finally:
             os.environ['PYTHONWARNINGS'] = old
@@ -644,7 +647,7 @@
     def test_pythoninspect_doesnt_override_isatty(self):
         os.environ['PYTHONINSPECT_'] = '1'
         try:
-            data = self.run('', senddata='6*7\nprint 2+3\n')
+            data = self.run('', senddata='6*7\nprint(2+3)\n')
             assert data == '5\n'
         finally:
             del os.environ['PYTHONINSPECT_']
@@ -656,7 +659,7 @@
         # if a file name is passed, the banner is never printed but
         # we get a prompt anyway
         cmdline = '-i %s' % getscript("""
-            print 'hello world'
+            print('hello world')
             """)
         data = self.run(cmdline, senddata='6*7\nraise SystemExit\n',
                                  expect_prompt=True, expect_banner=False)
@@ -672,7 +675,7 @@
             time.sleep(1)
             # stdout flushed automatically here
             """)
-        cmdline = '%s -u "%s" %s' % (sys.executable, app_main, path)
+        cmdline = '%s -u "%s" %s' % (python3, app_main, path)
         print 'POPEN:', cmdline
         child_in, child_out_err = os.popen4(cmdline)
         data = child_out_err.read(11)
@@ -697,35 +700,35 @@
                 if old_pythonpath is not None:
                     os.putenv('PYTHONPATH', old_pythonpath)
 
-        tmpdir.join('site.py').write('print "SHOULD NOT RUN"')
+        tmpdir.join('site.py').write('print("SHOULD NOT RUN")')
         runme_py = tmpdir.join('runme.py')
-        runme_py.write('print "some text"')
+        runme_py.write('print("some text")')
 
         cmdline = str(runme_py)
 
         with chdir_and_unset_pythonpath(tmpdir):
             data = self.run(cmdline, python_flags='-S')
 
-        assert data == "some text\n"
+        assert data in ("'import site' failed\nsome text\n")
 
         runme2_py = tmpdir.mkdir('otherpath').join('runme2.py')
-        runme2_py.write('print "some new text"\n'
+        runme2_py.write('print("some new text")\n'
                         'import sys\n'
-                        'print sys.path\n')
+                        'print(sys.path)\n')
 
         cmdline2 = str(runme2_py)
 
         with chdir_and_unset_pythonpath(tmpdir):
             data = self.run(cmdline2, python_flags='-S')
-        assert data.startswith("some new text\n")
+        assert data.startswith("'import site' failed\nsome new text\n")
         assert repr(str(tmpdir.join('otherpath'))) in data
         assert "''" not in data
 
-        data = self.run('-c "import sys; print sys.path"')
+        data = self.run('-c "import sys; print(sys.path)"')
         assert data.startswith("[''")
 
     def test_pyc_commandline_argument(self):
-        p = getscript_pyc(self.space, "print 6*7\n")
+        p = getscript_pyc(self.space, "print(6*7)\n")
         assert os.path.isfile(p) and p.endswith('.pyc')
         data = self.run(p)
         assert data == 'in _run_compiled_module\n'
@@ -733,7 +736,7 @@
     def test_main_in_dir_commandline_argument(self):
         if not hasattr(runpy, '_run_module_as_main'):
             skip("requires CPython >= 2.6")
-        p = getscript_in_dir('import sys; print sys.argv[0]\n')
+        p = getscript_in_dir('import sys; print(sys.argv[0])\n')
         data = self.run(p)
         assert data == p + '\n'
         data = self.run(p + os.sep)


More information about the pypy-commit mailing list