diff options
Diffstat (limited to 'setuptools/tests')
-rw-r--r-- | setuptools/tests/__init__.py | 10 | ||||
-rw-r--r-- | setuptools/tests/doctest.py | 58 | ||||
-rw-r--r-- | setuptools/tests/server.py | 12 | ||||
-rw-r--r-- | setuptools/tests/test_bdist_egg.py | 2 | ||||
-rw-r--r-- | setuptools/tests/test_develop.py | 22 | ||||
-rw-r--r-- | setuptools/tests/test_dist_info.py | 43 | ||||
-rw-r--r-- | setuptools/tests/test_easy_install.py | 19 | ||||
-rw-r--r-- | setuptools/tests/test_packageindex.py | 22 | ||||
-rw-r--r-- | setuptools/tests/test_resources.py | 17 | ||||
-rw-r--r-- | setuptools/tests/test_sdist.py | 4 | ||||
-rw-r--r-- | setuptools/tests/test_test.py | 4 | ||||
-rw-r--r-- | setuptools/tests/win_script_wrapper.txt | 66 |
12 files changed, 132 insertions, 147 deletions
diff --git a/setuptools/tests/__init__.py b/setuptools/tests/__init__.py index b6988a08..298141a7 100644 --- a/setuptools/tests/__init__.py +++ b/setuptools/tests/__init__.py @@ -9,6 +9,7 @@ from distutils.errors import DistutilsOptionError, DistutilsPlatformError from distutils.errors import DistutilsSetupError from distutils.core import Extension from distutils.version import LooseVersion +from setuptools.compat import func_code import setuptools.dist import setuptools.depends as dep @@ -53,17 +54,18 @@ class DependsTests(unittest.TestCase): x = "test" y = z + fc = func_code(f1) # unrecognized name - self.assertEqual(dep.extract_constant(f1.func_code,'q', -1), None) + self.assertEqual(dep.extract_constant(fc,'q', -1), None) # constant assigned - self.assertEqual(dep.extract_constant(f1.func_code,'x', -1), "test") + self.assertEqual(dep.extract_constant(fc,'x', -1), "test") # expression assigned - self.assertEqual(dep.extract_constant(f1.func_code,'y', -1), -1) + self.assertEqual(dep.extract_constant(fc,'y', -1), -1) # recognized name, not assigned - self.assertEqual(dep.extract_constant(f1.func_code,'z', -1), None) + self.assertEqual(dep.extract_constant(fc,'z', -1), None) def testFindModule(self): self.assertRaises(ImportError, dep.find_module, 'no-such.-thing') diff --git a/setuptools/tests/doctest.py b/setuptools/tests/doctest.py index cc1e06c3..35d588d0 100644 --- a/setuptools/tests/doctest.py +++ b/setuptools/tests/doctest.py @@ -9,7 +9,7 @@ try: basestring except NameError: - basestring = str,unicode + basestring = str try: enumerate @@ -109,7 +109,7 @@ import __future__ import sys, traceback, inspect, linecache, os, re, types import unittest, difflib, pdb, tempfile import warnings -from StringIO import StringIO +from setuptools.compat import StringIO, execfile, exec_, func_code, im_func # Don't whine about the deprecated is_private function in this # module's tests. @@ -240,7 +240,7 @@ def _normalize_module(module, depth=2): """ if inspect.ismodule(module): return module - elif isinstance(module, (str, unicode)): + elif isinstance(module, basestring): return __import__(module, globals(), locals(), ["*"]) elif module is None: return sys.modules[sys._getframe(depth).f_globals['__name__']] @@ -367,9 +367,9 @@ class _OutputRedirectingPdb(pdb.Pdb): # [XX] Normalize with respect to os.path.pardir? def _module_relative_path(module, path): if not inspect.ismodule(module): - raise TypeError, 'Expected a module: %r' % module + raise TypeError('Expected a module: %r' % module) if path.startswith('/'): - raise ValueError, 'Module-relative files may not have absolute paths' + raise ValueError('Module-relative files may not have absolute paths') # Find the base directory for the path. if hasattr(module, '__file__'): @@ -877,7 +877,7 @@ class DocTestFinder: if module is None: return True elif inspect.isfunction(object): - return module.__dict__ is object.func_globals + return module.__dict__ is func_globals(object) elif inspect.isclass(object): return module.__name__ == object.__module__ elif inspect.getmodule(object) is not None: @@ -895,7 +895,7 @@ class DocTestFinder: add them to `tests`. """ if self._verbose: - print 'Finding tests in %s' % name + print('Finding tests in %s' % name) # If we've already processed this object, then ignore it. if id(obj) in seen: @@ -948,7 +948,7 @@ class DocTestFinder: if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): - val = getattr(obj, valname).im_func + val = im_func(getattr(obj, valname)) # Recurse to methods, properties, and nested classes. if ((inspect.isfunction(val) or inspect.isclass(val) or @@ -1020,8 +1020,8 @@ class DocTestFinder: break # Find the line number for functions & methods. - if inspect.ismethod(obj): obj = obj.im_func - if inspect.isfunction(obj): obj = obj.func_code + if inspect.ismethod(obj): obj = im_func(obj) + if inspect.isfunction(obj): obj = func_code(obj) if inspect.istraceback(obj): obj = obj.tb_frame if inspect.isframe(obj): obj = obj.f_code if inspect.iscode(obj): @@ -1250,8 +1250,8 @@ class DocTestRunner: # keyboard interrupts.) try: # Don't blink! This is where the user's code gets run. - exec compile(example.source, filename, "single", - compileflags, 1) in test.globs + exec_(compile(example.source, filename, "single", + compileflags, 1), test.globs) self.debugger.set_continue() # ==== Example Finished ==== exception = None except KeyboardInterrupt: @@ -1335,7 +1335,7 @@ class DocTestRunner: if m and m.group('name') == self.test.name: example = self.test.examples[int(m.group('examplenum'))] return example.source.splitlines(True) - elif self.save_linecache_getlines.func_code.co_argcount>1: + elif func_code(self.save_linecache_getlines).co_argcount > 1: return self.save_linecache_getlines(filename, module_globals) else: return self.save_linecache_getlines(filename) @@ -1427,28 +1427,28 @@ class DocTestRunner: failed.append(x) if verbose: if notests: - print len(notests), "items had no tests:" + print(len(notests), "items had no tests:") notests.sort() for thing in notests: - print " ", thing + print(" ", thing) if passed: - print len(passed), "items passed all tests:" + print(len(passed), "items passed all tests:") passed.sort() for thing, count in passed: - print " %3d tests in %s" % (count, thing) + print(" %3d tests in %s" % (count, thing)) if failed: - print self.DIVIDER - print len(failed), "items had failures:" + print(self.DIVIDER) + print(len(failed), "items had failures:") failed.sort() for thing, (f, t) in failed: - print " %3d of %3d in %s" % (f, t, thing) + print(" %3d of %3d in %s" % (f, t, thing)) if verbose: - print totalt, "tests in", len(self._name2ft), "items." - print totalt - totalf, "passed and", totalf, "failed." + print(totalt, "tests in", len(self._name2ft), "items.") + print(totalt - totalf, "passed and", totalf, "failed.") if totalf: - print "***Test Failed***", totalf, "failures." + print("***Test Failed***", totalf, "failures.") elif verbose: - print "Test passed." + print("Test passed.") return totalf, totalt #///////////////////////////////////////////////////////////////// @@ -1458,8 +1458,8 @@ class DocTestRunner: d = self._name2ft for name, (f, t) in other._name2ft.items(): if name in d: - print "*** DocTestRunner.merge: '" + name + "' in both" \ - " testers; summing outcomes." + print("*** DocTestRunner.merge: '" + name + "' in both" \ + " testers; summing outcomes.") f2, t2 = d[name] f = f + f2 t = t + t2 @@ -2039,10 +2039,10 @@ class Tester: def runstring(self, s, name): test = DocTestParser().get_doctest(s, self.globs, name, None, None) if self.verbose: - print "Running string", name + print("Running string", name) (f,t) = self.testrunner.run(test) if self.verbose: - print f, "of", t, "examples failed in string", name + print(f, "of", t, "examples failed in string", name) return (f,t) def rundoc(self, object, name=None, module=None): @@ -2556,7 +2556,7 @@ def debug_script(src, pm=False, globs=None): try: execfile(srcfilename, globs, globs) except: - print sys.exc_info()[1] + print(sys.exc_info()[1]) pdb.post_mortem(sys.exc_info()[2]) else: # Note that %r is vital here. '%s' instead can, e.g., cause diff --git a/setuptools/tests/server.py b/setuptools/tests/server.py index b2ab7acc..ae2381e3 100644 --- a/setuptools/tests/server.py +++ b/setuptools/tests/server.py @@ -1,12 +1,11 @@ """Basic http server for tests to simulate PyPI or custom indexes """ -import urllib2 import sys import time import threading -import BaseHTTPServer -from BaseHTTPServer import HTTPServer -from SimpleHTTPServer import SimpleHTTPRequestHandler +from setuptools.compat import BaseHTTPRequestHandler +from setuptools.compat import (urllib2, URLError, HTTPServer, + SimpleHTTPRequestHandler) class IndexServer(HTTPServer): """Basic single-threaded http server simulating a package index @@ -48,16 +47,17 @@ class IndexServer(HTTPServer): urllib2.urlopen(url, timeout=5) else: urllib2.urlopen(url) - except urllib2.URLError: + except URLError: # ignore any errors; all that's important is the request pass self.thread.join() + self.socket.close() def base_url(self): port = self.server_port return 'http://127.0.0.1:%s/setuptools/tests/indexes/' % port -class RequestRecorder(BaseHTTPServer.BaseHTTPRequestHandler): +class RequestRecorder(BaseHTTPRequestHandler): def do_GET(self): requests = vars(self.server).setdefault('requests', []) requests.append(self) diff --git a/setuptools/tests/test_bdist_egg.py b/setuptools/tests/test_bdist_egg.py index 7da122cc..1a122186 100644 --- a/setuptools/tests/test_bdist_egg.py +++ b/setuptools/tests/test_bdist_egg.py @@ -4,9 +4,9 @@ import sys import os, re, shutil, tempfile, unittest import tempfile import site -from StringIO import StringIO from distutils.errors import DistutilsError +from setuptools.compat import StringIO from setuptools.command.bdist_egg import bdist_egg from setuptools.command import easy_install as easy_install_pkg from setuptools.dist import Distribution diff --git a/setuptools/tests/test_develop.py b/setuptools/tests/test_develop.py index 315058c5..9d7ce711 100644 --- a/setuptools/tests/test_develop.py +++ b/setuptools/tests/test_develop.py @@ -4,11 +4,11 @@ import sys import os, shutil, tempfile, unittest import tempfile import site -from StringIO import StringIO from distutils.errors import DistutilsError from setuptools.command.develop import develop from setuptools.command import easy_install as easy_install_pkg +from setuptools.compat import StringIO from setuptools.dist import Distribution SETUP_PY = """\ @@ -43,7 +43,7 @@ class TestDevelopTest(unittest.TestCase): f = open(init, 'w') f.write(INIT_PY) f.close() - + os.chdir(self.dir) self.old_base = site.USER_BASE site.USER_BASE = tempfile.mkdtemp() @@ -53,7 +53,7 @@ class TestDevelopTest(unittest.TestCase): def tearDown(self): if sys.version < "2.6" or hasattr(sys, 'real_prefix'): return - + os.chdir(self.old_cwd) shutil.rmtree(self.dir) shutil.rmtree(site.USER_BASE) @@ -90,11 +90,15 @@ class TestDevelopTest(unittest.TestCase): # Check that we are using the right code. egg_link_file = open(os.path.join(site.USER_SITE, 'foo.egg-link'), 'rt') - path = egg_link_file.read().split()[0].strip() - egg_link_file.close() + try: + path = egg_link_file.read().split()[0].strip() + finally: + egg_link_file.close() init_file = open(os.path.join(path, 'foo', '__init__.py'), 'rt') - init = init_file.read().strip() - init_file.close() + try: + init = init_file.read().strip() + finally: + init_file.close() if sys.version < "3": self.assertEqual(init, 'print "foo"') else: @@ -109,10 +113,10 @@ class TestDevelopTest(unittest.TestCase): try: try: dist = Distribution({'setup_requires': ['I_DONT_EXIST']}) - except DistutilsError, e: + except DistutilsError: + e = sys.exc_info()[1] error = str(e) if error == wanted: pass finally: os.chdir(old_dir) - diff --git a/setuptools/tests/test_dist_info.py b/setuptools/tests/test_dist_info.py index fcb78c36..a8adb68c 100644 --- a/setuptools/tests/test_dist_info.py +++ b/setuptools/tests/test_dist_info.py @@ -51,30 +51,33 @@ class TestDistInfo(unittest.TestCase): 'VersionedDistribution-2.718.dist-info') os.mkdir(versioned) metadata_file = open(os.path.join(versioned, 'METADATA'), 'w+') - metadata_file.write(DALS( - """ - Metadata-Version: 1.2 - Name: VersionedDistribution - Requires-Dist: splort (4) - Provides-Extra: baz - Requires-Dist: quux (>=1.1); extra == 'baz' - """)) - metadata_file.close() - + try: + metadata_file.write(DALS( + """ + Metadata-Version: 1.2 + Name: VersionedDistribution + Requires-Dist: splort (4) + Provides-Extra: baz + Requires-Dist: quux (>=1.1); extra == 'baz' + """)) + finally: + metadata_file.close() unversioned = os.path.join(self.tmpdir, 'UnversionedDistribution.dist-info') os.mkdir(unversioned) metadata_file = open(os.path.join(unversioned, 'METADATA'), 'w+') - metadata_file.write(DALS( - """ - Metadata-Version: 1.2 - Name: UnversionedDistribution - Version: 0.3 - Requires-Dist: splort (==4) - Provides-Extra: baz - Requires-Dist: quux (>=1.1); extra == 'baz' - """)) - metadata_file.close() + try: + metadata_file.write(DALS( + """ + Metadata-Version: 1.2 + Name: UnversionedDistribution + Version: 0.3 + Requires-Dist: splort (==4) + Provides-Extra: baz + Requires-Dist: quux (>=1.1); extra == 'baz' + """)) + finally: + metadata_file.close() def tearDown(self): shutil.rmtree(self.tmpdir) diff --git a/setuptools/tests/test_easy_install.py b/setuptools/tests/test_easy_install.py index 582219ce..d76025d2 100644 --- a/setuptools/tests/test_easy_install.py +++ b/setuptools/tests/test_easy_install.py @@ -6,10 +6,10 @@ import shutil import tempfile import unittest import site +from setuptools.compat import StringIO, BytesIO, next +from setuptools.compat import urlparse import textwrap import tarfile -import urlparse -import StringIO import distutils.core from setuptools.sandbox import run_setup, SandboxViolation @@ -78,7 +78,7 @@ class TestEasyInstallTest(unittest.TestCase): old_platform = sys.platform try: - name, script = [i for i in get_script_args(dist).next()][0:2] + name, script = [i for i in next(get_script_args(dist))][0:2] finally: sys.platform = old_platform @@ -139,8 +139,7 @@ class TestEasyInstallTest(unittest.TestCase): cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok') cmd.args = ['ok'] cmd.ensure_finalized() - keys = cmd.package_index.scanned_urls.keys() - keys.sort() + keys = sorted(cmd.package_index.scanned_urls.keys()) self.assertEqual(keys, ['link1', 'link2']) @@ -304,8 +303,8 @@ class TestUserInstallTest(unittest.TestCase): old_stdout = sys.stdout old_stderr = sys.stderr - sys.stdout = StringIO.StringIO() - sys.stderr = StringIO.StringIO() + sys.stdout = StringIO() + sys.stderr = StringIO() try: reset_setup_stop_context( lambda: run_setup(test_setup_py, ['install']) @@ -329,7 +328,7 @@ class TestSetupRequires(unittest.TestCase): p_index = setuptools.tests.server.MockServer() p_index.start() netloc = 1 - p_index_loc = urlparse.urlparse(p_index.url)[netloc] + p_index_loc = urlparse(p_index.url)[netloc] if p_index_loc.endswith(':0'): # Some platforms (Jython) don't find a port to which to bind, # so skip this test for them. @@ -396,9 +395,9 @@ def make_trivial_sdist(dist_path, setup_py): setup_py_file = tarfile.TarInfo(name='setup.py') try: # Python 3 (StringIO gets converted to io module) - MemFile = StringIO.BytesIO + MemFile = BytesIO except AttributeError: - MemFile = StringIO.StringIO + MemFile = StringIO setup_py_bytes = MemFile(setup_py.encode('utf-8')) setup_py_file.size = len(setup_py_bytes.getvalue()) dist = tarfile.open(dist_path, 'w:gz') diff --git a/setuptools/tests/test_packageindex.py b/setuptools/tests/test_packageindex.py index 3e446b54..b596d37f 100644 --- a/setuptools/tests/test_packageindex.py +++ b/setuptools/tests/test_packageindex.py @@ -2,12 +2,11 @@ """ import sys import unittest -import urllib2 import pkg_resources -import httplib +from setuptools.compat import urllib2, httplib, HTTPError, unicode import distutils.errors import setuptools.package_index -from server import IndexServer +from setuptools.tests.server import IndexServer class TestPackageIndex(unittest.TestCase): @@ -16,10 +15,11 @@ class TestPackageIndex(unittest.TestCase): url = 'http://127.0.0.1:0/nonesuch/test_package_index' try: v = index.open_url(url) - except Exception, v: + except Exception: + v = sys.exc_info()[1] self.assertTrue(url in str(v)) else: - self.assertTrue(isinstance(v,urllib2.HTTPError)) + self.assertTrue(isinstance(v, HTTPError)) def test_bad_url_typo(self): # issue 16 @@ -32,10 +32,11 @@ class TestPackageIndex(unittest.TestCase): url = 'url:%20https://svn.plone.org/svn/collective/inquant.contentmirror.plone/trunk' try: v = index.open_url(url) - except Exception, v: + except Exception: + v = sys.exc_info()[1] self.assertTrue(url in str(v)) else: - self.assertTrue(isinstance(v, urllib2.HTTPError)) + self.assertTrue(isinstance(v, HTTPError)) def test_bad_url_bad_status_line(self): index = setuptools.package_index.PackageIndex( @@ -43,7 +44,6 @@ class TestPackageIndex(unittest.TestCase): ) def _urlopen(*args): - import httplib raise httplib.BadStatusLine('line') old_urlopen = urllib2.urlopen @@ -52,7 +52,8 @@ class TestPackageIndex(unittest.TestCase): try: try: v = index.open_url(url) - except Exception, v: + except Exception: + v = sys.exc_info()[1] self.assertTrue('line' in str(v)) else: raise AssertionError('Should have raise here!') @@ -71,7 +72,8 @@ class TestPackageIndex(unittest.TestCase): url = 'http://http://svn.pythonpaste.org/Paste/wphp/trunk' try: index.open_url(url) - except distutils.errors.DistutilsError, error: + except distutils.errors.DistutilsError: + error = sys.exc_info()[1] msg = unicode(error) assert 'nonnumeric port' in msg or 'getaddrinfo failed' in msg or 'Name or service not known' in msg return diff --git a/setuptools/tests/test_resources.py b/setuptools/tests/test_resources.py index 292b78d1..a2ec03c0 100644 --- a/setuptools/tests/test_resources.py +++ b/setuptools/tests/test_resources.py @@ -3,7 +3,8 @@ # NOTE: the shebang and encoding lines are for ScriptHeaderTests; do not remove from unittest import TestCase, makeSuite; from pkg_resources import * from setuptools.command.easy_install import get_script_header, is_sh -import os, pkg_resources, sys, StringIO, tempfile, shutil +from setuptools.compat import StringIO, iteritems +import os, pkg_resources, sys, tempfile, shutil try: frozenset except NameError: from sets import ImmutableSet as frozenset @@ -149,7 +150,7 @@ class DistroTests(TestCase): for i in range(3): targets = list(ws.resolve(parse_requirements("Foo"), ad)) self.assertEqual(targets, [Foo]) - map(ws.add,targets) + list(map(ws.add,targets)) self.assertRaises(VersionConflict, ws.resolve, parse_requirements("Foo==0.9"), ad) ws = WorkingSet([]) # reset @@ -272,7 +273,7 @@ class EntryPointTests(TestCase): def checkSubMap(self, m): self.assertEqual(len(m), len(self.submap_expect)) - for key, ep in self.submap_expect.iteritems(): + for key, ep in iteritems(self.submap_expect): self.assertEqual(repr(m.get(key)), repr(ep)) submap_expect = dict( @@ -296,10 +297,10 @@ class EntryPointTests(TestCase): def testParseMap(self): m = EntryPoint.parse_map({'xyz':self.submap_str}) self.checkSubMap(m['xyz']) - self.assertEqual(m.keys(),['xyz']) + self.assertEqual(list(m.keys()),['xyz']) m = EntryPoint.parse_map("[xyz]\n"+self.submap_str) self.checkSubMap(m['xyz']) - self.assertEqual(m.keys(),['xyz']) + self.assertEqual(list(m.keys()),['xyz']) self.assertRaises(ValueError, EntryPoint.parse_map, ["[xyz]", "[xyz]"]) self.assertRaises(ValueError, EntryPoint.parse_map, self.submap_str) @@ -568,12 +569,12 @@ class ScriptHeaderTests(TestCase): # Ensure we generate what is basically a broken shebang line # when there's options, with a warning emitted - sys.stdout = sys.stderr = StringIO.StringIO() + sys.stdout = sys.stderr = StringIO() self.assertEqual(get_script_header('#!/usr/bin/python -x', executable=exe), '#!%s -x\n' % exe) self.assertTrue('Unable to adapt shebang line' in sys.stdout.getvalue()) - sys.stdout = sys.stderr = StringIO.StringIO() + sys.stdout = sys.stderr = StringIO() self.assertEqual(get_script_header('#!/usr/bin/python', executable=self.non_ascii_exe), '#!%s -x\n' % self.non_ascii_exe) @@ -633,7 +634,7 @@ class NamespaceTests(TestCase): self._assertIn("pkg1", pkg_resources._namespace_packages.keys()) try: import pkg1.pkg2 - except ImportError, e: + except ImportError: self.fail("Distribute tried to import the parent namespace package") # check the _namespace_packages dict self._assertIn("pkg1.pkg2", pkg_resources._namespace_packages.keys()) diff --git a/setuptools/tests/test_sdist.py b/setuptools/tests/test_sdist.py index f51d4567..ececa765 100644 --- a/setuptools/tests/test_sdist.py +++ b/setuptools/tests/test_sdist.py @@ -7,11 +7,9 @@ import shutil import sys import tempfile import unittest -import urllib import unicodedata -from StringIO import StringIO - +from setuptools.compat import StringIO, urllib from setuptools.command.sdist import sdist from setuptools.command.egg_info import manifest_maker from setuptools.dist import Distribution diff --git a/setuptools/tests/test_test.py b/setuptools/tests/test_test.py index ad7cbd0f..e7022995 100644 --- a/setuptools/tests/test_test.py +++ b/setuptools/tests/test_test.py @@ -6,9 +6,9 @@ import sys import os, shutil, tempfile, unittest import tempfile import site -from StringIO import StringIO from distutils.errors import DistutilsError +from setuptools.compat import StringIO from setuptools.command.test import test from setuptools.command import easy_install as easy_install_pkg from setuptools.dist import Distribution @@ -121,4 +121,4 @@ class TestTestTest(unittest.TestCase): pass finally: sys.stdout = old_stdout -
\ No newline at end of file + diff --git a/setuptools/tests/win_script_wrapper.txt b/setuptools/tests/win_script_wrapper.txt index db1daf6b..731243dd 100644 --- a/setuptools/tests/win_script_wrapper.txt +++ b/setuptools/tests/win_script_wrapper.txt @@ -49,37 +49,16 @@ GUI programs, the suffix '-script-pyw' is added.) This is why we named out script the way we did. Now we can run out script by running the wrapper: - >>> from subprocess import Popen, PIPE, STDOUT - >>> try: - ... unicode=unicode - ... except: - ... unicode=str - >>> def popen4(cmd, *args): - ... if hasattr(os, 'popen4'): - ... input, output = os.popen4(cmd + " ".join(args)) - ... return input, output - ... else: - ... #emulate popen4 in python 3 - ... if cmd[0] == '"' and cmd[-1] != '"': - ... cmd = cmd[1:] - ... cmd += " ".join(args) - ... p = Popen(cmd, shell=True, bufsize=0, - ... stdin=PIPE, stdout=PIPE, stderr=STDOUT) - ... return p.stdin, p.stdout - - >>> input, output = popen4('"' + nt_quote_arg(os.path.join(sample_directory, 'foo.exe')), - ... r' arg1', r'"arg 2"', r'"arg \"2\\\""', r'"arg 4\\"', r'"arg5 a\\b"') - >>> bytes_written = input.write('hello\nworld\n'.encode('utf-8')) - >>> input.close() - >>> # This is needed for line ending differences between py2 and py3 on win32 - >>> msg = unicode(output.read(), encoding='utf-8').split("\n") - >>> for line in msg: - ... print(line.strip()) + >>> import subprocess + >>> cmd = [os.path.join(sample_directory, 'foo.exe'), 'arg1', 'arg 2', + ... 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] + >>> proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE) + >>> stdout, stderr = proc.communicate('hello\nworld\n'.encode('ascii')) + >>> bytes = sys.stdout.write(stdout.decode('ascii').replace('\r\n', '\n')) \foo-script.py ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] 'hello\nworld\n' non-optimized - <BLANKLINE> This example was a little pathological in that it exercised windows (MS C runtime) quoting rules: @@ -115,18 +94,14 @@ enter the interpreter after running the script, you could use -Oi: ... sys.ps1 = '---' ... """ % dict(python_exe=nt_quote_arg(sys.executable))) >>> f.close() - - >>> input, output = popen4(nt_quote_arg(os.path.join(sample_directory, 'foo.exe'))) - >>> input.close() - >>> # This is needed for line ending differences between py2 and py3 on win32 - >>> msg = unicode(output.read(), encoding='utf-8').split("\n") - >>> for line in msg: - ... print(line.strip()) + >>> cmd = [os.path.join(sample_directory, 'foo.exe')] + >>> proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) + >>> stdout, stderr = proc.communicate() + >>> bytes = sys.stdout.write(stdout.decode('ascii').replace('\r\n', '\n')) \foo-script.py [] '' --- - <BLANKLINE> Testing the GUI Version ----------------------- @@ -157,18 +132,19 @@ We'll also copy gui.exe to the sample-directory with the name bar.exe: Finally, we'll run the script and check the result: - >>> input, output = popen4('"'+nt_quote_arg(os.path.join(sample_directory, 'bar.exe')), - ... r' "%s" "Test Argument"' % os.path.join(sample_directory, 'test_output.txt')) - >>> input.close() - >>> # This is needed for line ending differences between py2 and py3 on win32 - >>> msg = unicode(output.read(), encoding='utf-8').split("\n") - >>> for line in msg: - ... print(line.strip()) + >>> cmd = [ + ... os.path.join(sample_directory, 'bar.exe'), + ... os.path.join(sample_directory, 'test_output.txt'), + ... 'Test Argument', + ... ] + >>> proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) + >>> stdout, stderr = proc.communicate() + >>> print(stdout.decode('ascii')) <BLANKLINE> - >>> f = open(os.path.join(sample_directory, 'test_output.txt'), 'rb') - >>> print(unicode(f.read(), encoding='utf-8')) + >>> f_out = open(os.path.join(sample_directory, 'test_output.txt'), 'rb') + >>> print(f_out.read().decode('ascii')) 'Test Argument' - >>> f.close() + >>> f_out.close() We're done with the sample_directory: |