[pypy-svn] r55054 - in pypy/dist/pypy/translator/goal: . test2

arigo at codespeak.net arigo at codespeak.net
Wed May 21 11:54:37 CEST 2008


Author: arigo
Date: Wed May 21 11:54:35 2008
New Revision: 55054

Modified:
   pypy/dist/pypy/translator/goal/app_main.py
   pypy/dist/pypy/translator/goal/test2/test_app_main.py
Log:
Some more whacking at the command-line option handling logic, trying to
slowly converge to CPython's behavior.  The latter is desperately
lacking any designed -- it is a biologically grown tangle which can set
and clear the same internal global flags three times along the way.



Modified: pypy/dist/pypy/translator/goal/app_main.py
==============================================================================
--- pypy/dist/pypy/translator/goal/app_main.py	(original)
+++ pypy/dist/pypy/translator/goal/app_main.py	Wed May 21 11:54:35 2008
@@ -291,24 +291,38 @@
         if hasattr(signal, 'SIGXFSZ'):
             signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
 
-    def is_interactive():
-        return go_interactive or os.getenv('PYTHONINSPECT')
+    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
             cmd = sys.argv.pop(1)
             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:
-            if is_interactive() or sys.stdin.isatty():
+            # 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:
@@ -323,20 +337,25 @@
                                                         '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__)
-            
-        if is_interactive():
+
+        # start a prompt if requested
+        if inspect_requested():
             from _pypy_interact import interactive_console
             success = run_toplevel(interactive_console, mainmodule)
     except SystemExit, e:

Modified: pypy/dist/pypy/translator/goal/test2/test_app_main.py
==============================================================================
--- pypy/dist/pypy/translator/goal/test2/test_app_main.py	(original)
+++ pypy/dist/pypy/translator/goal/test2/test_app_main.py	Wed May 21 11:54:35 2008
@@ -6,25 +6,6 @@
 import autopath
 from pypy.tool.udir import udir
 
-DEMO_SCRIPT = """
-print 'hello'
-print 'Name:', __name__
-print 'File:', __file__
-import sys
-print 'Exec:', sys.executable
-print 'Argv:', sys.argv
-print 'goodbye'
-myvalue = 6*7
-"""
-
-CRASHING_DEMO_SCRIPT = """
-print 'Hello2'
-myvalue2 = 11
-ooups
-myvalue2 = 22
-print 'Goodbye2'   # should not be reached
-"""
-
 banner = sys.version.splitlines()[0]
 
 def relpath(path):
@@ -43,13 +24,33 @@
 app_main = os.path.join(autopath.this_dir, os.pardir, 'app_main.py')
 app_main = os.path.abspath(app_main)
 
-demo_script_p = udir.join('demo_test_app_main.py')
-demo_script_p.write(DEMO_SCRIPT)
-demo_script = relpath(demo_script_p)
-
-crashing_demo_script_p = udir.join('crashing_demo_test_app_main.py')
-crashing_demo_script_p.write(CRASHING_DEMO_SCRIPT)
-crashing_demo_script = relpath(crashing_demo_script_p)
+_counter = 0
+def getscript(source):
+    global _counter
+    p = udir.join('demo_test_app_main_%d.py' % (_counter,))
+    _counter += 1
+    p.write(str(py.code.Source(source)))
+    return relpath(p)
+
+
+demo_script = getscript("""
+    print 'hello'
+    print 'Name:', __name__
+    print 'File:', __file__
+    import sys
+    print 'Exec:', sys.executable
+    print 'Argv:', sys.argv
+    print 'goodbye'
+    myvalue = 6*7
+    """)
+
+crashing_demo_script = getscript("""
+    print 'Hello2'
+    myvalue2 = 11
+    ooups
+    myvalue2 = 22
+    print 'Goodbye2'   # should not be reached
+    """)
 
 
 class TestInteraction:
@@ -265,22 +266,6 @@
         data = os.read(pipe.stdout.fileno(), 1024)
         assert data.startswith('Python')
 
-    def test_options_u_PYTHONINSPECT(self):
-        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"],
-                                stdout=subprocess.PIPE,
-                                stdin=subprocess.PIPE,
-                                stderr=subprocess.STDOUT,
-                                bufsize=0, close_fds=True,
-                                env={'PYTHONINSPECT': '1'})
-        iwtd, owtd, ewtd = select.select([pipe.stdout], [], [], 5)
-        assert iwtd    # else we timed out
-        data = os.read(pipe.stdout.fileno(), 1024)
-        assert data.startswith('Python')
-
     def test_paste_several_lines_doesnt_mess_prompt(self):
         py.test.skip("this can only work if readline is enabled")
         child = self.spawn([])
@@ -291,18 +276,56 @@
         child.expect('42')
         child.expect('>>> ')
 
+    def test_pythoninspect(self):
+        old = os.environ.get('PYTHONINSPECT', '')
+        try:
+            os.environ['PYTHONINSPECT'] = '1'
+            path = getscript("""
+                print 6*7
+                """)
+            child = self.spawn([path])
+            child.expect('42')
+            child.expect('>>> ')
+        finally:
+            os.environ['PYTHONINSPECT'] = old
+
+    def test_set_pythoninspect(self):
+        path = getscript("""
+            import os
+            os.environ['PYTHONINSPECT'] = '1'
+            print 6*7
+            """)
+        child = self.spawn([path])
+        child.expect('42')
+        child.expect('>>> ')
+
+    def test_clear_pythoninspect(self):
+        py.test.skip("obscure difference with CPython -- do we care?")
+        old = os.environ.get('PYTHONINSPECT', '')
+        try:
+            path = getscript("""
+                import os
+                del os.environ['PYTHONINSPECT']
+                """)
+            child = self.spawn([path])
+            xxx  # do we expect a prompt or not?  CPython gives one
+        finally:
+            os.environ['PYTHONINSPECT'] = old
+
 
 class TestNonInteractive:
 
-    def run(self, cmdline):
+    def run(self, cmdline, senddata='', expect_prompt=False,
+            expect_banner=False):
         cmdline = '%s "%s" %s' % (sys.executable, app_main, cmdline)
         print 'POPEN:', cmdline
         child_in, child_out_err = os.popen4(cmdline)
+        child_in.write(senddata)
         child_in.close()
         data = child_out_err.read()
         child_out_err.close()
-        assert banner not in data          # no banner
-        assert '>>> ' not in data          # no prompt
+        assert (banner in data) == expect_banner   # no banner unless expected
+        assert ('>>> ' in data) == expect_prompt   # no prompt unless expected
         return data
 
     def test_script_on_stdin(self):
@@ -356,3 +379,26 @@
         # concerning drive letters right now.
         assert ('File: ' + p) in data
         assert ('Argv: ' + repr([p, 'extra'])) in data
+
+    def test_pythoninspect_doesnt_override_isatty(self):
+        old = os.environ.get('PYTHONINSPECT', '')
+        try:
+            os.environ['PYTHONINSPECT'] = '1'
+            data = self.run('', senddata='6*7\nprint 2+3\n')
+            assert data == '5\n'
+        finally:
+            os.environ['PYTHONINSPECT'] = old
+
+    def test_i_flag_overrides_isatty(self):
+        data = self.run('-i', senddata='6*7\nraise SystemExit\n',
+                              expect_prompt=True, expect_banner=True)
+        assert '42\n' in data
+        # if a file name is passed, the banner is never printed but
+        # we get a prompt anyway
+        cmdline = '-i %s' % getscript("""
+            print 'hello world'
+            """)
+        data = self.run(cmdline, senddata='6*7\nraise SystemExit\n',
+                                 expect_prompt=True, expect_banner=False)
+        assert 'hello world\n' in data
+        assert '42\n' in data



More information about the Pypy-commit mailing list