Commit a5d23944 authored by Éric Araujo's avatar Éric Araujo

Merged revisions 86223-86224,86226,86234 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/branches/py3k

........
  r86223 | eric.araujo | 2010-11-06 00:51:56 +0100 (sam., 06 nov. 2010) | 2 lines

  Always close files in distutils code and tests (#10252).
........
  r86224 | eric.araujo | 2010-11-06 00:58:34 +0100 (sam., 06 nov. 2010) | 2 lines

  Add missing entry for r86223.
........
  r86226 | eric.araujo | 2010-11-06 00:59:32 +0100 (sam., 06 nov. 2010) | 2 lines

  Of course, I forgot one file in r86223.
........
  r86234 | eric.araujo | 2010-11-06 03:10:32 +0100 (sam., 06 nov. 2010) | 2 lines

  Also close file descriptors from os.popen and subprocess.Popen
........
parent d8c87402
...@@ -794,6 +794,7 @@ class CCompiler: ...@@ -794,6 +794,7 @@ class CCompiler:
library_dirs = [] library_dirs = []
fd, fname = tempfile.mkstemp(".c", funcname, text=True) fd, fname = tempfile.mkstemp(".c", funcname, text=True)
f = os.fdopen(fd, "w") f = os.fdopen(fd, "w")
try:
for incl in includes: for incl in includes:
f.write("""#include "%s"\n""" % incl) f.write("""#include "%s"\n""" % incl)
f.write("""\ f.write("""\
...@@ -801,6 +802,7 @@ main (int argc, char **argv) { ...@@ -801,6 +802,7 @@ main (int argc, char **argv) {
%s(); %s();
} }
""" % funcname) """ % funcname)
finally:
f.close() f.close()
try: try:
objects = self.compile([fname], include_dirs=include_dirs) objects = self.compile([fname], include_dirs=include_dirs)
......
...@@ -355,6 +355,7 @@ class bdist_rpm (Command): ...@@ -355,6 +355,7 @@ class bdist_rpm (Command):
src_rpm, non_src_rpm, spec_path) src_rpm, non_src_rpm, spec_path)
out = os.popen(q_cmd) out = os.popen(q_cmd)
try:
binary_rpms = [] binary_rpms = []
source_rpm = None source_rpm = None
while 1: while 1:
...@@ -372,6 +373,9 @@ class bdist_rpm (Command): ...@@ -372,6 +373,9 @@ class bdist_rpm (Command):
if status: if status:
raise DistutilsExecError("Failed to execute: %s" % repr(q_cmd)) raise DistutilsExecError("Failed to execute: %s" % repr(q_cmd))
finally:
out.close()
self.spawn(rpm_cmd) self.spawn(rpm_cmd)
if not self.dry_run: if not self.dry_run:
......
...@@ -356,5 +356,9 @@ class bdist_wininst (Command): ...@@ -356,5 +356,9 @@ class bdist_wininst (Command):
sfix = '' sfix = ''
filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix))
return open(filename, "rb").read() f = open(filename, "rb")
try:
return f.read()
finally:
f.close()
# class bdist_wininst # class bdist_wininst
...@@ -79,7 +79,11 @@ class upload(PyPIRCCommand): ...@@ -79,7 +79,11 @@ class upload(PyPIRCCommand):
# Fill in the data - send all the meta-data in case we need to # Fill in the data - send all the meta-data in case we need to
# register a new release # register a new release
content = open(filename,'rb').read() f = open(filename,'rb')
try:
content = f.read()
finally:
f.close()
meta = self.distribution.metadata meta = self.distribution.metadata
data = { data = {
# action # action
......
...@@ -216,7 +216,11 @@ def run_setup(script_name, script_args=None, stop_after="run"): ...@@ -216,7 +216,11 @@ def run_setup(script_name, script_args=None, stop_after="run"):
sys.argv[0] = script_name sys.argv[0] = script_name
if script_args is not None: if script_args is not None:
sys.argv[1:] = script_args sys.argv[1:] = script_args
exec open(script_name, 'r').read() in g, l f = open(script_name)
try:
exec f.read() in g, l
finally:
f.close()
finally: finally:
sys.argv = save_argv sys.argv = save_argv
_setup_stop_after = None _setup_stop_after = None
......
...@@ -382,7 +382,9 @@ def check_config_h(): ...@@ -382,7 +382,9 @@ def check_config_h():
# It would probably better to read single lines to search. # It would probably better to read single lines to search.
# But we do this only once, and it is fast enough # But we do this only once, and it is fast enough
f = open(fn) f = open(fn)
try:
s = f.read() s = f.read()
finally:
f.close() f.close()
except IOError, exc: except IOError, exc:
......
...@@ -1101,8 +1101,10 @@ class DistributionMetadata: ...@@ -1101,8 +1101,10 @@ class DistributionMetadata:
def write_pkg_info(self, base_dir): def write_pkg_info(self, base_dir):
"""Write the PKG-INFO file into the release tree. """Write the PKG-INFO file into the release tree.
""" """
pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w') pkg_info = open(os.path.join(base_dir, 'PKG-INFO'), 'w')
try:
self.write_pkg_file(pkg_info) self.write_pkg_file(pkg_info)
finally:
pkg_info.close() pkg_info.close()
def write_pkg_file(self, file): def write_pkg_file(self, file):
......
...@@ -272,7 +272,9 @@ def check_config_h(): ...@@ -272,7 +272,9 @@ def check_config_h():
# It would probably better to read single lines to search. # It would probably better to read single lines to search.
# But we do this only once, and it is fast enough # But we do this only once, and it is fast enough
f = open(fn) f = open(fn)
try:
s = f.read() s = f.read()
finally:
f.close() f.close()
except IOError, exc: except IOError, exc:
...@@ -300,7 +302,9 @@ def get_versions(): ...@@ -300,7 +302,9 @@ def get_versions():
gcc_exe = find_executable('gcc') gcc_exe = find_executable('gcc')
if gcc_exe: if gcc_exe:
out = os.popen(gcc_exe + ' -dumpversion','r') out = os.popen(gcc_exe + ' -dumpversion','r')
try:
out_string = out.read() out_string = out.read()
finally:
out.close() out.close()
result = re.search('(\d+\.\d+\.\d+)',out_string) result = re.search('(\d+\.\d+\.\d+)',out_string)
if result: if result:
......
...@@ -150,6 +150,7 @@ def read_setup_file (filename): ...@@ -150,6 +150,7 @@ def read_setup_file (filename):
file = TextFile(filename, file = TextFile(filename,
strip_comments=1, skip_blanks=1, join_lines=1, strip_comments=1, skip_blanks=1, join_lines=1,
lstrip_ws=1, rstrip_ws=1) lstrip_ws=1, rstrip_ws=1)
try:
extensions = [] extensions = []
while 1: while 1:
...@@ -221,6 +222,12 @@ def read_setup_file (filename): ...@@ -221,6 +222,12 @@ def read_setup_file (filename):
ext.extra_link_args.append(word) ext.extra_link_args.append(word)
if not value: if not value:
append_next_word = ext.extra_link_args append_next_word = ext.extra_link_args
elif word == "-Xcompiler":
append_next_word = ext.extra_compile_args
elif switch == "-u":
ext.extra_link_args.append(word)
if not value:
append_next_word = ext.extra_link_args
elif suffix in (".a", ".so", ".sl", ".o", ".dylib"): elif suffix in (".a", ".so", ".sl", ".o", ".dylib"):
# NB. a really faithful emulation of makesetup would # NB. a really faithful emulation of makesetup would
# append a .o file to extra_objects only if it # append a .o file to extra_objects only if it
...@@ -231,6 +238,8 @@ def read_setup_file (filename): ...@@ -231,6 +238,8 @@ def read_setup_file (filename):
file.warn("unrecognized argument '%s'" % word) file.warn("unrecognized argument '%s'" % word)
extensions.append(ext) extensions.append(ext)
finally:
file.close()
#print "module:", module #print "module:", module
#print "source files:", source_files #print "source files:", source_files
......
...@@ -224,6 +224,8 @@ def write_file (filename, contents): ...@@ -224,6 +224,8 @@ def write_file (filename, contents):
sequence of strings without line terminators) to it. sequence of strings without line terminators) to it.
""" """
f = open(filename, "w") f = open(filename, "w")
try:
for line in contents: for line in contents:
f.write(line + "\n") f.write(line + "\n")
finally:
f.close() f.close()
...@@ -273,10 +273,12 @@ def query_vcvarsall(version, arch="x86"): ...@@ -273,10 +273,12 @@ def query_vcvarsall(version, arch="x86"):
popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch), popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch),
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
try:
stdout, stderr = popen.communicate() stdout, stderr = popen.communicate()
if popen.wait() != 0: if popen.wait() != 0:
raise DistutilsPlatformError(stderr.decode("mbcs")) raise DistutilsPlatformError(stderr.decode("mbcs"))
finally:
popen.close()
stdout = stdout.decode("mbcs") stdout = stdout.decode("mbcs")
for line in stdout.split("\n"): for line in stdout.split("\n"):
......
...@@ -19,10 +19,14 @@ class BuildPyTestCase(support.TempdirManager, ...@@ -19,10 +19,14 @@ class BuildPyTestCase(support.TempdirManager,
def _setup_package_data(self): def _setup_package_data(self):
sources = self.mkdtemp() sources = self.mkdtemp()
f = open(os.path.join(sources, "__init__.py"), "w") f = open(os.path.join(sources, "__init__.py"), "w")
try:
f.write("# Pretend this is a package.") f.write("# Pretend this is a package.")
finally:
f.close() f.close()
f = open(os.path.join(sources, "README.txt"), "w") f = open(os.path.join(sources, "README.txt"), "w")
try:
f.write("Info about this package") f.write("Info about this package")
finally:
f.close() f.close()
destination = self.mkdtemp() destination = self.mkdtemp()
......
...@@ -71,7 +71,9 @@ class BuildScriptsTestCase(support.TempdirManager, ...@@ -71,7 +71,9 @@ class BuildScriptsTestCase(support.TempdirManager,
def write_script(self, dir, name, text): def write_script(self, dir, name, text):
f = open(os.path.join(dir, name), "w") f = open(os.path.join(dir, name), "w")
try:
f.write(text) f.write(text)
finally:
f.close() f.close()
def test_version_int(self): def test_version_int(self):
......
...@@ -108,8 +108,12 @@ class PyPIRCCommandTestCase(support.TempdirManager, ...@@ -108,8 +108,12 @@ class PyPIRCCommandTestCase(support.TempdirManager,
self.assertTrue(not os.path.exists(rc)) self.assertTrue(not os.path.exists(rc))
cmd._store_pypirc('tarek', 'xxx') cmd._store_pypirc('tarek', 'xxx')
self.assertTrue(os.path.exists(rc)) self.assertTrue(os.path.exists(rc))
content = open(rc).read() f = open(rc)
try:
content = f.read()
self.assertEquals(content, WANTED) self.assertEquals(content, WANTED)
finally:
f.close()
def test_suite(): def test_suite():
return unittest.makeSuite(PyPIRCCommandTestCase) return unittest.makeSuite(PyPIRCCommandTestCase)
......
...@@ -52,7 +52,11 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase): ...@@ -52,7 +52,11 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase):
shutil.rmtree(path) shutil.rmtree(path)
def write_setup(self, text, path=test.test_support.TESTFN): def write_setup(self, text, path=test.test_support.TESTFN):
open(path, "w").write(text) f = open(path, "w")
try:
f.write(text)
finally:
f.close()
return path return path
def test_run_setup_provides_file(self): def test_run_setup_provides_file(self):
......
...@@ -88,7 +88,9 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase): ...@@ -88,7 +88,9 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
mkpath(self.target, verbose=0) mkpath(self.target, verbose=0)
a_file = os.path.join(self.target, 'ok.txt') a_file = os.path.join(self.target, 'ok.txt')
f = open(a_file, 'w') f = open(a_file, 'w')
try:
f.write('some content') f.write('some content')
finally:
f.close() f.close()
wanted = ['copying %s -> %s' % (a_file, self.target2)] wanted = ['copying %s -> %s' % (a_file, self.target2)]
......
...@@ -102,11 +102,14 @@ class DistributionTestCase(support.TempdirManager, ...@@ -102,11 +102,14 @@ class DistributionTestCase(support.TempdirManager,
def test_command_packages_configfile(self): def test_command_packages_configfile(self):
sys.argv.append("build") sys.argv.append("build")
self.addCleanup(os.unlink, TESTFN)
f = open(TESTFN, "w") f = open(TESTFN, "w")
try: try:
print >>f, "[global]" print >>f, "[global]"
print >>f, "command_packages = foo.bar, splat" print >>f, "command_packages = foo.bar, splat"
finally:
f.close() f.close()
d = self.create_distribution([TESTFN]) d = self.create_distribution([TESTFN])
self.assertEqual(d.get_command_packages(), self.assertEqual(d.get_command_packages(),
["distutils.command", "foo.bar", "splat"]) ["distutils.command", "foo.bar", "splat"])
...@@ -123,9 +126,6 @@ class DistributionTestCase(support.TempdirManager, ...@@ -123,9 +126,6 @@ class DistributionTestCase(support.TempdirManager,
d = self.create_distribution([TESTFN]) d = self.create_distribution([TESTFN])
self.assertEqual(d.get_command_packages(), ["distutils.command"]) self.assertEqual(d.get_command_packages(), ["distutils.command"])
finally:
os.unlink(TESTFN)
def test_write_pkg_file(self): def test_write_pkg_file(self):
# Check DistributionMetadata handling of Unicode fields # Check DistributionMetadata handling of Unicode fields
tmp_dir = self.mkdtemp() tmp_dir = self.mkdtemp()
...@@ -341,7 +341,9 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard, ...@@ -341,7 +341,9 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
temp_dir = self.mkdtemp() temp_dir = self.mkdtemp()
user_filename = os.path.join(temp_dir, user_filename) user_filename = os.path.join(temp_dir, user_filename)
f = open(user_filename, 'w') f = open(user_filename, 'w')
try:
f.write('.') f.write('.')
finally:
f.close() f.close()
try: try:
......
...@@ -31,7 +31,9 @@ class FileUtilTestCase(support.TempdirManager, unittest.TestCase): ...@@ -31,7 +31,9 @@ class FileUtilTestCase(support.TempdirManager, unittest.TestCase):
def test_move_file_verbosity(self): def test_move_file_verbosity(self):
f = open(self.source, 'w') f = open(self.source, 'w')
try:
f.write('some content') f.write('some content')
finally:
f.close() f.close()
move_file(self.source, self.target, verbose=0) move_file(self.source, self.target, verbose=0)
......
...@@ -42,7 +42,9 @@ class InstallScriptsTestCase(support.TempdirManager, ...@@ -42,7 +42,9 @@ class InstallScriptsTestCase(support.TempdirManager,
def write_script(name, text): def write_script(name, text):
expected.append(name) expected.append(name)
f = open(os.path.join(source, name), "w") f = open(os.path.join(source, name), "w")
try:
f.write(text) f.write(text)
finally:
f.close() f.close()
write_script("script1.py", ("#! /usr/bin/env python2.3\n" write_script("script1.py", ("#! /usr/bin/env python2.3\n"
......
...@@ -113,7 +113,9 @@ class msvc9compilerTestCase(support.TempdirManager, ...@@ -113,7 +113,9 @@ class msvc9compilerTestCase(support.TempdirManager,
tempdir = self.mkdtemp() tempdir = self.mkdtemp()
manifest = os.path.join(tempdir, 'manifest') manifest = os.path.join(tempdir, 'manifest')
f = open(manifest, 'w') f = open(manifest, 'w')
try:
f.write(_MANIFEST) f.write(_MANIFEST)
finally:
f.close() f.close()
compiler = MSVCCompiler() compiler = MSVCCompiler()
...@@ -121,8 +123,10 @@ class msvc9compilerTestCase(support.TempdirManager, ...@@ -121,8 +123,10 @@ class msvc9compilerTestCase(support.TempdirManager,
# see what we got # see what we got
f = open(manifest) f = open(manifest)
try:
# removing trailing spaces # removing trailing spaces
content = '\n'.join([line.rstrip() for line in f.readlines()]) content = '\n'.join([line.rstrip() for line in f.readlines()])
finally:
f.close() f.close()
# makes sure the manifest was properly cleaned # makes sure the manifest was properly cleaned
......
...@@ -119,8 +119,12 @@ class RegisterTestCase(PyPIRCCommandTestCase): ...@@ -119,8 +119,12 @@ class RegisterTestCase(PyPIRCCommandTestCase):
self.assertTrue(os.path.exists(self.rc)) self.assertTrue(os.path.exists(self.rc))
# with the content similar to WANTED_PYPIRC # with the content similar to WANTED_PYPIRC
content = open(self.rc).read() f = open(self.rc)
try:
content = f.read()
self.assertEquals(content, WANTED_PYPIRC) self.assertEquals(content, WANTED_PYPIRC)
finally:
f.close()
# now let's make sure the .pypirc file generated # now let's make sure the .pypirc file generated
# really works : we shouldn't be asked anything # really works : we shouldn't be asked anything
......
...@@ -234,8 +234,12 @@ class SDistTestCase(PyPIRCCommandTestCase): ...@@ -234,8 +234,12 @@ class SDistTestCase(PyPIRCCommandTestCase):
self.assertEquals(len(content), 11) self.assertEquals(len(content), 11)
# checking the MANIFEST # checking the MANIFEST
manifest = open(join(self.tmp_dir, 'MANIFEST')).read() f = open(join(self.tmp_dir, 'MANIFEST'))
try:
manifest = f.read()
self.assertEquals(manifest, MANIFEST % {'sep': os.sep}) self.assertEquals(manifest, MANIFEST % {'sep': os.sep})
finally:
f.close()
@unittest.skipUnless(zlib, "requires zlib") @unittest.skipUnless(zlib, "requires zlib")
def test_metadata_check_option(self): def test_metadata_check_option(self):
......
...@@ -50,8 +50,10 @@ class SysconfigTestCase(support.EnvironGuard, ...@@ -50,8 +50,10 @@ class SysconfigTestCase(support.EnvironGuard,
def test_parse_makefile_base(self): def test_parse_makefile_base(self):
self.makefile = test.test_support.TESTFN self.makefile = test.test_support.TESTFN
fd = open(self.makefile, 'w') fd = open(self.makefile, 'w')
try:
fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=LIB'" '\n') fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=LIB'" '\n')
fd.write('VAR=$OTHER\nOTHER=foo') fd.write('VAR=$OTHER\nOTHER=foo')
finally:
fd.close() fd.close()
d = sysconfig.parse_makefile(self.makefile) d = sysconfig.parse_makefile(self.makefile)
self.assertEquals(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", self.assertEquals(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'",
...@@ -60,8 +62,10 @@ class SysconfigTestCase(support.EnvironGuard, ...@@ -60,8 +62,10 @@ class SysconfigTestCase(support.EnvironGuard,
def test_parse_makefile_literal_dollar(self): def test_parse_makefile_literal_dollar(self):
self.makefile = test.test_support.TESTFN self.makefile = test.test_support.TESTFN
fd = open(self.makefile, 'w') fd = open(self.makefile, 'w')
try:
fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=\$$LIB'" '\n') fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=\$$LIB'" '\n')
fd.write('VAR=$OTHER\nOTHER=foo') fd.write('VAR=$OTHER\nOTHER=foo')
finally:
fd.close() fd.close()
d = sysconfig.parse_makefile(self.makefile) d = sysconfig.parse_makefile(self.makefile)
self.assertEquals(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", self.assertEquals(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'",
......
...@@ -58,28 +58,46 @@ class TextFileTestCase(support.TempdirManager, unittest.TestCase): ...@@ -58,28 +58,46 @@ class TextFileTestCase(support.TempdirManager, unittest.TestCase):
finally: finally:
out_file.close() out_file.close()
in_file = TextFile (filename, strip_comments=0, skip_blanks=0, in_file = TextFile(filename, strip_comments=0, skip_blanks=0,
lstrip_ws=0, rstrip_ws=0) lstrip_ws=0, rstrip_ws=0)
test_input (1, "no processing", in_file, result1) try:
test_input(1, "no processing", in_file, result1)
finally:
in_file.close()
in_file = TextFile (filename, strip_comments=1, skip_blanks=0, in_file = TextFile(filename, strip_comments=1, skip_blanks=0,
lstrip_ws=0, rstrip_ws=0) lstrip_ws=0, rstrip_ws=0)
test_input (2, "strip comments", in_file, result2) try:
test_input(2, "strip comments", in_file, result2)
finally:
in_file.close()
in_file = TextFile (filename, strip_comments=0, skip_blanks=1, in_file = TextFile(filename, strip_comments=0, skip_blanks=1,
lstrip_ws=0, rstrip_ws=0) lstrip_ws=0, rstrip_ws=0)
test_input (3, "strip blanks", in_file, result3) try:
test_input(3, "strip blanks", in_file, result3)
finally:
in_file.close()
in_file = TextFile (filename) in_file = TextFile(filename)
test_input (4, "default processing", in_file, result4) try:
test_input(4, "default processing", in_file, result4)
finally:
in_file.close()
in_file = TextFile (filename, strip_comments=1, skip_blanks=1, in_file = TextFile(filename, strip_comments=1, skip_blanks=1,
join_lines=1, rstrip_ws=1) join_lines=1, rstrip_ws=1)
test_input (5, "join lines without collapsing", in_file, result5) try:
test_input(5, "join lines without collapsing", in_file, result5)
finally:
in_file.close()
in_file = TextFile (filename, strip_comments=1, skip_blanks=1, in_file = TextFile(filename, strip_comments=1, skip_blanks=1,
join_lines=1, rstrip_ws=1, collapse_join=1) join_lines=1, rstrip_ws=1, collapse_join=1)
test_input (6, "join lines with collapsing", in_file, result6) try:
test_input(6, "join lines with collapsing", in_file, result6)
finally:
in_file.close()
def test_suite(): def test_suite():
return unittest.makeSuite(TextFileTestCase) return unittest.makeSuite(TextFileTestCase)
......
...@@ -116,13 +116,15 @@ def get_platform (): ...@@ -116,13 +116,15 @@ def get_platform ():
# behaviour. # behaviour.
pass pass
else: else:
try:
m = re.search( m = re.search(
r'<key>ProductUserVisibleVersion</key>\s*' + r'<key>ProductUserVisibleVersion</key>\s*' +
r'<string>(.*?)</string>', f.read()) r'<string>(.*?)</string>', f.read())
f.close()
if m is not None: if m is not None:
macrelease = '.'.join(m.group(1).split('.')[:2]) macrelease = '.'.join(m.group(1).split('.')[:2])
# else: fall back to the default behaviour # else: fall back to the default behaviour
finally:
f.close()
if not macver: if not macver:
macver = macrelease macver = macrelease
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment