[pypy-commit] pypy py3k: Make runsubprocess.py work on Python 3.

mjacob pypy.commits at gmail.com
Mon Oct 3 01:42:45 EDT 2016


Author: Manuel Jacob <me at manueljacob.de>
Branch: py3k
Changeset: r87538:a544b65b564f
Date: 2016-10-03 07:42 +0200
http://bitbucket.org/pypy/pypy/changeset/a544b65b564f/

Log:	Make runsubprocess.py work on Python 3.

	This is needed for build_cffi_imports.py.

diff --git a/rpython/tool/runsubprocess.py b/rpython/tool/runsubprocess.py
--- a/rpython/tool/runsubprocess.py
+++ b/rpython/tool/runsubprocess.py
@@ -6,11 +6,18 @@
 import sys
 import gc
 import os
+from io import TextIOWrapper
 from subprocess import PIPE, Popen
 
+PY2 = (sys.version_info.major == 2)
+if PY2:
+    text = unicode
+else:
+    text = str
+
 def run_subprocess(executable, args, env=None, cwd=None):
     if isinstance(args, list):
-        args = [a.encode('latin1') if isinstance(a, unicode) else a
+        args = [a.encode('latin1') if isinstance(a, text) else a
                 for a in args]
     return _run(executable, args, env, cwd)
 
@@ -71,24 +78,37 @@
     _source = os.path.join(_source, 'runsubprocess.py')   # and not e.g. '.pyc'
 
     def spawn_subprocess():
-        global _child
+        global _child, child_stdin, child_stdout
         _child = Popen([sys.executable, _source], bufsize=0,
                        stdin=PIPE, stdout=PIPE, close_fds=True)
+        if PY2:
+            child_stdin = _child.stdin
+            child_stdout = _child.stdout
+        else:
+            # create TextIOWrappers which (hopefully) have the same newline
+            # behavior as the child's stdin / stdout
+            child_stdin = TextIOWrapper(_child.stdin,
+                                        newline=sys.stdin.newlines,
+                                        write_through=True)
+            child_stdout = TextIOWrapper(_child.stdout,
+                                         newline=sys.stdout.newlines)
     spawn_subprocess()
 
     def cleanup_subprocess():
-        global _child
+        global _child, child_stdin, child_stdout
         _child = None
+        child_stdin = None
+        child_stdout = None
     import atexit; atexit.register(cleanup_subprocess)
 
     def _run(*args):
         try:
-            _child.stdin.write('%r\n' % (args,))
+            child_stdin.write('%r\n' % (args,))
         except (OSError, IOError):
             # lost the child.  Try again...
             spawn_subprocess()
-            _child.stdin.write('%r\n' % (args,))
-        results = _child.stdout.readline()
+            child_stdin.write('%r\n' % (args,))
+        results = child_stdout.readline()
         assert results.startswith('(')
         results = eval(results)
         if results[0] is None:


More information about the pypy-commit mailing list