Massive changes from SF 589982 (tempfile.py rewrite, by Zack

Weinberg).  This changes all uses of deprecated tempfile functions to
the recommended ones.
This commit is contained in:
Guido van Rossum 2002-08-09 16:38:32 +00:00
parent 830a5151c1
commit 3b0a3293c3
31 changed files with 134 additions and 149 deletions

View file

@ -143,22 +143,17 @@ class RCS:
if message and message[-1] != '\n':
message = message + '\n'
lockflag = "-u"
textfile = None
try:
if new:
textfile = tempfile.mktemp()
f = open(textfile, 'w')
f = tempfile.NamedTemporaryFile()
f.write(message)
f.close()
f.flush()
cmd = 'ci %s%s -t%s %s %s' % \
(lockflag, rev, textfile, otherflags, name)
(lockflag, rev, f.name, otherflags, name)
else:
message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message)
cmd = 'ci %s%s -m"%s" %s %s' % \
(lockflag, rev, message, otherflags, name)
return self._system(cmd)
finally:
if textfile: self._remove(textfile)
# --- Exported support methods ---

View file

@ -172,17 +172,13 @@ class MyFile(File):
if self.lsum == sum:
return
import tempfile
tfn = tempfile.mktemp()
try:
tf = open(tfn, 'w')
tf = tempfile.NamedTemporaryFile()
tf.write(data)
tf.close()
tf.flush()
print 'diff %s -r%s %s' % (flags, rev, fn)
sts = os.system('diff %s %s %s' % (flags, tfn, fn))
sts = os.system('diff %s %s %s' % (flags, tf.name, fn))
if sts:
print '='*70
finally:
remove(tfn)
def commitcheck(self):
return self.action() != 'C'

View file

@ -102,17 +102,13 @@ def diff(x, copts, fn):
flags = flags + ' ' + o + a
flags = flags[1:]
data = x.get(fn)
tfn = tempfile.mktemp()
try:
tf = open(tfn, 'w')
tf = tempfile.NamedTemporaryFile()
tf.write(data)
tf.close()
tf.flush()
print 'diff %s -r%s %s' % (flags, x.head(fn), fn)
sts = os.system('diff %s %s %s' % (flags, tfn, fn))
sts = os.system('diff %s %s %s' % (flags, tf.name, fn))
if sts:
print '='*70
finally:
remove(tfn)
def same(x, copts, fn, data = None):
if data is None:

View file

@ -120,19 +120,11 @@ for line in SCRIPT:
program = program + (string.joinfields(epilogue, '\n') + '\n')
import tempfile
tfn = tempfile.mktemp()
try:
fp = open(tfn, 'w')
fp.write(program)
fp.close()
if DFLAG:
fp = tempfile.NamedTemporaryFile()
fp.write(program)
fp.flush()
if DFLAG:
import pdb
pdb.run('execfile(' + `tfn` + ')')
else:
else:
execfile(tfn)
finally:
import os
try:
os.unlink(tfn)
except:
pass

View file

@ -193,10 +193,10 @@ class Hook:
if self.logdir is not None:
import os, tempfile
name = tempfile.mktemp(['.html', '.txt'][text])
path = os.path.join(self.logdir, os.path.basename(name))
(fd, name) = tempfile.mkstemp(suffix=['.html', '.txt'][text],
dir=self.logdir)
try:
file = open(path, 'w')
file = os.fdopen(fd, 'w')
file.write(doc)
file.close()
msg = '<p> %s contains the description of this error.' % path

View file

@ -130,8 +130,9 @@ class bdist_wininst (Command):
# And make an archive relative to the root of the
# pseudo-installation tree.
from tempfile import mktemp
archive_basename = mktemp()
from tempfile import NamedTemporaryFile
arc = NamedTemporaryFile(".zip")
archive_basename = arc.name[:-4]
fullname = self.distribution.get_fullname()
arcname = self.make_archive(archive_basename, "zip",
root_dir=self.bdist_dir)
@ -139,7 +140,7 @@ class bdist_wininst (Command):
self.create_exe(arcname, fullname, self.bitmap)
# remove the zip-file again
log.debug("removing temporary file '%s'", arcname)
os.remove(arcname)
arc.close()
if not self.keep_temp:
remove_tree(self.bdist_dir, dry_run=self.dry_run)

View file

@ -359,11 +359,11 @@ def byte_compile (py_files,
# "Indirect" byte-compilation: write a temporary script and then
# run it with the appropriate flags.
if not direct:
from tempfile import mktemp
script_name = mktemp(".py")
from tempfile import mkstemp
(script_fd, script_name) = mkstemp(".py")
log.info("writing byte-compilation script '%s'", script_name)
if not dry_run:
script = open(script_name, "w")
script = os.fdopen(script_fd, "w")
script.write("""\
from distutils.util import byte_compile

View file

@ -8,12 +8,10 @@ import test.pystone
if sys.argv[1:]:
logfile = sys.argv[1]
cleanup = 0
else:
import tempfile
logfile = tempfile.mktemp()
cleanup = 1
logf = tempfile.NamedTemporaryFile()
logfile = logf.name
p = hotshot.Profile(logfile)
benchtime, stones = p.runcall(test.pystone.pystones)
@ -24,8 +22,6 @@ print "Pystone(%s) time for %d passes = %g" % \
print "This machine benchmarks at %g pystones/second" % stones
stats = hotshot.stats.load(logfile)
if cleanup:
os.unlink(logfile)
stats.strip_dirs()
stats.sort_stats('time', 'calls')
try:

View file

@ -202,8 +202,8 @@ def pipeto(input, command):
pipe.close()
def pipethrough(input, command, output):
tempname = tempfile.mktemp()
temp = open(tempname, 'w')
(fd, tempname) = tempfile.mkstemp()
temp = os.fdopen(fd, 'w')
copyliteral(input, temp)
temp.close()
pipe = os.popen(command + ' <' + tempname, 'r')

View file

@ -225,7 +225,8 @@ def makepipeline(infile, steps, outfile):
lkind = list[i-1][2]
rkind = list[i][2]
if lkind[1] == 'f' or rkind[0] == 'f':
temp = tempfile.mktemp()
(fd, temp) = tempfile.mkstemp()
os.close(fd)
garbage.append(temp)
list[i-1][-1] = list[i][0] = temp
#

View file

@ -70,7 +70,8 @@ def torgb(filename):
def _torgb(filename, temps):
if filename[-2:] == '.Z':
fname = tempfile.mktemp()
(fd, fname) = tempfile.mkstemp()
os.close(fd)
temps.append(fname)
sts = uncompress.copy(filename, fname)
if sts:
@ -91,7 +92,8 @@ def _torgb(filename, temps):
if ftype is None or not table.has_key(ftype):
raise error, \
filename + ': unsupported image file type ' + `ftype`
temp = tempfile.mktemp()
(fd, temp) = tempfile.mktemp()
os.close(fd)
sts = table[ftype].copy(fname, temp)
if sts:
raise error, filename + ': conversion to rgb failed'

View file

@ -70,7 +70,8 @@ def torgb(filename):
def _torgb(filename, temps):
if filename[-2:] == '.Z':
fname = tempfile.mktemp()
(fd, fname) = tempfile.mkstemp()
os.close(fd)
temps.append(fname)
sts = uncompress.copy(filename, fname)
if sts:
@ -91,7 +92,8 @@ def _torgb(filename, temps):
if ftype is None or not table.has_key(ftype):
raise error, \
filename + ': unsupported image file type ' + `ftype`
temp = tempfile.mktemp()
(fd, temp) = tempfile.mktemp()
os.close(fd)
sts = table[ftype].copy(fname, temp)
if sts:
raise error, filename + ': conversion to rgb failed'

View file

@ -1203,8 +1203,8 @@ def getpager():
return lambda text: pipepager(text, 'less')
import tempfile
filename = tempfile.mktemp()
open(filename, 'w').close()
(fd, filename) = tempfile.mkstemp()
os.close(fd)
try:
if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
return lambda text: pipepager(text, 'more')
@ -1229,8 +1229,8 @@ def pipepager(text, cmd):
def tempfilepager(text, cmd):
"""Page through text by invoking a program on a temporary file."""
import tempfile
filename = tempfile.mktemp()
file = open(filename, 'w')
(fd, filename) = tempfile.mkstemp()
file = os.fdopen(fd, 'w')
file.write(text)
file.close()
try:

View file

@ -1,5 +1,5 @@
import unittest
from test.test_support import TestFailed, have_unicode
from test.test_support import TestFailed, have_unicode, TESTFN
class C:
def __cmp__(self, other):
@ -269,17 +269,19 @@ class AbstractPickleTests(unittest.TestCase):
class AbstractPickleModuleTests(unittest.TestCase):
def test_dump_closed_file(self):
import tempfile, os
fn = tempfile.mktemp()
f = open(fn, "w")
import os
f = open(TESTFN, "w")
try:
f.close()
self.assertRaises(ValueError, self.module.dump, 123, f)
os.remove(fn)
finally:
os.remove(TESTFN)
def test_load_closed_file(self):
import tempfile, os
fn = tempfile.mktemp()
f = open(fn, "w")
import os
f = open(TESTFN, "w")
try:
f.close()
self.assertRaises(ValueError, self.module.dump, 123, f)
os.remove(fn)
finally:
os.remove(TESTFN)

View file

@ -6,11 +6,10 @@
import os
import unittest
import anydbm
import tempfile
import glob
from test import test_support
_fname = tempfile.mktemp()
_fname = test_support.TESTFN
def _delete_files():
# we don't know the precise name the underlying database uses

View file

@ -6,7 +6,6 @@
"""
import binhex
import os
import tempfile
import unittest
from test import test_support
@ -14,8 +13,8 @@ from test import test_support
class BinHexTestCase(unittest.TestCase):
def setUp(self):
self.fname1 = tempfile.mktemp()
self.fname2 = tempfile.mktemp()
self.fname1 = test_support.TESTFN + "1"
self.fname2 = test_support.TESTFN + "2"
def tearDown(self):
try: os.unlink(self.fname1)

View file

@ -5,8 +5,7 @@
import os
import bsddb
import dbhash # Just so we know it's imported
import tempfile
from test.test_support import verbose, verify
from test.test_support import verbose, verify, TESTFN
def test(openmethod, what, ondisk=1):
@ -14,7 +13,7 @@ def test(openmethod, what, ondisk=1):
print '\nTesting: ', what, (ondisk and "on disk" or "in memory")
if ondisk:
fname = tempfile.mktemp()
fname = TESTFN
else:
fname = None
f = openmethod(fname, 'c')

View file

@ -24,10 +24,17 @@ class CommandTests(unittest.TestCase):
self.assertEquals(getoutput('echo xyzzy'), 'xyzzy')
self.assertEquals(getstatusoutput('echo xyzzy'), (0, 'xyzzy'))
# we use mktemp in the next line to get a filename which we
# _know_ won't exist. This is guaranteed to fail.
status, output = getstatusoutput('cat ' + tempfile.mktemp())
# we use mkdtemp in the next line to create an empty directory
# under our exclusive control; from that, we can invent a pathname
# that we _know_ won't exist. This is guaranteed to fail.
try:
dir = tempfile.mkdtemp()
name = os.path.join(dir, "foo")
status, output = getstatusoutput('cat ' + name)
self.assertNotEquals(status, 0)
finally:
os.rmdir(dir)
def test_getstatus(self):
# This pattern should match 'ls -ld /.' on any posix

View file

@ -6,10 +6,9 @@
import os
import unittest
import dumbdbm
import tempfile
from test import test_support
_fname = tempfile.mktemp()
_fname = test_support.TESTFN
def _delete_files():
for ext in [".dir", ".dat", ".bak"]:

View file

@ -1,8 +1,8 @@
from test.test_support import verify
from test.test_support import verify, TESTFN
import sys, os
import gzip, tempfile
import gzip
filename = tempfile.mktemp()
filename = TESTFN
data1 = """ int length=DEFAULTALLOC, err = Z_OK;
PyObject *RetVal;

View file

@ -1,5 +1,5 @@
import netrc, os, tempfile, unittest
import netrc, os, unittest
from test import test_support
TEST_NETRC = """
@ -17,7 +17,7 @@ default login log2 password pass2
"""
temp_filename = tempfile.mktemp()
temp_filename = test_support.TESTFN
class NetrcTestCase(unittest.TestCase):

View file

@ -8,6 +8,7 @@ from test.test_support import verify, verbose, TestFailed
# Helpers to create and destroy hierarchies.
def mkhier(root, descr):
if not os.path.isdir(root):
mkdir(root)
for name, contents in descr:
comps = name.split()
@ -52,18 +53,17 @@ def fixdir(lst):
# Helper to run a test
def runtest(hier, code):
root = tempfile.mktemp()
root = tempfile.mkdtemp()
mkhier(root, hier)
savepath = sys.path[:]
codefile = tempfile.mktemp()
f = open(codefile, "w")
f.write(code)
f.close()
codefile = tempfile.NamedTemporaryFile()
codefile.write(code)
codefile.flush()
try:
sys.path.insert(0, root)
if verbose: print "sys.path =", sys.path
try:
execfile(codefile, globals(), {})
execfile(codefile.name, globals(), {})
except:
traceback.print_exc(file=sys.stdout)
finally:
@ -72,7 +72,6 @@ def runtest(hier, code):
cleanout(root)
except (os.error, IOError):
pass
os.remove(codefile)
# Test descriptions

View file

@ -17,8 +17,7 @@ class TestImport(unittest.TestCase):
del sys.modules[module_name]
def setUp(self):
self.test_dir = tempfile.mktemp()
os.mkdir(self.test_dir)
self.test_dir = tempfile.mkdtemp()
sys.path.append(self.test_dir)
self.package_dir = os.path.join(self.test_dir,
self.package_name)

View file

@ -124,8 +124,7 @@ except uu.Error, e:
verify(str(e) == 'No valid begin line found in input file')
# Test to verify that decode() will refuse to overwrite an existing file
import tempfile
outfile = tempfile.mktemp()
outfile = TESTFN + "out"
inp = StringIO('Here is a message to be uuencoded')
out = StringIO()
uu.encode(inp, out, outfile)

View file

@ -1,5 +1,5 @@
from test.test_support import TestFailed
import os, tempfile
from test.test_support import TestFailed, TESTFN
import os
import wave
def check(t, msg=None):
@ -11,9 +11,7 @@ sampwidth = 2
framerate = 8000
nframes = 100
testfile = tempfile.mktemp()
f = wave.open(testfile, 'wb')
f = wave.open(TESTFN, 'wb')
f.setnchannels(nchannels)
f.setsampwidth(sampwidth)
f.setframerate(framerate)
@ -22,7 +20,7 @@ output = '\0' * nframes * nchannels * sampwidth
f.writeframes(output)
f.close()
f = wave.open(testfile, 'rb')
f = wave.open(TESTFN, 'rb')
check(nchannels == f.getnchannels(), "nchannels")
check(sampwidth == f.getsampwidth(), "sampwidth")
check(framerate == f.getframerate(), "framerate")
@ -31,4 +29,4 @@ input = f.readframes(nframes)
check(input == output, "data")
f.close()
os.remove(testfile)
os.remove(TESTFN)

View file

@ -11,7 +11,7 @@ import anydbm
import tempfile
import glob
_fname = tempfile.mktemp()
_fname = test.test_support.TESTFN
def _delete_files():
# we don't know the precise name the underlying database uses

View file

@ -75,7 +75,8 @@ def toaiff(filename):
def _toaiff(filename, temps):
if filename[-2:] == '.Z':
fname = tempfile.mktemp()
(fd, fname) = tempfile.mkstemp()
os.close(fd)
temps.append(fname)
sts = uncompress.copy(filename, fname)
if sts:
@ -98,7 +99,8 @@ def _toaiff(filename, temps):
if ftype is None or not ftype in table:
raise error, \
filename + ': unsupported audio file type ' + `ftype`
temp = tempfile.mktemp()
(fd, temp) = tempfile.mktemp()
os.close(fd)
temps.append(temp)
sts = table[ftype].copy(fname, temp)
if sts:

View file

@ -212,19 +212,21 @@ class URLopener:
pass
fp = self.open(url, data)
headers = fp.info()
if not filename:
if filename:
tfp = open(filename, 'wb')
else:
import tempfile
garbage, path = splittype(url)
garbage, path = splithost(path or "")
path, garbage = splitquery(path or "")
path, garbage = splitattr(path or "")
suffix = os.path.splitext(path)[1]
filename = tempfile.mktemp(suffix)
(fd, filename) = tempfile.mkstemp(suffix)
self.__tempfiles.append(filename)
tfp = os.open(fd, 'wb')
result = filename, headers
if self.tempcache is not None:
self.tempcache[url] = result
tfp = open(filename, 'wb')
bs = 1024*8
size = -1
blocknum = 1

View file

@ -15,15 +15,13 @@ import test
import tempfile
def copy_test_suite():
dest = tempfile.mktemp()
os.mkdir(dest)
dest = tempfile.mkdtemp()
os.system("cp -r %s/* %s" % (test.__path__[0], dest))
print "Creating copy of test suite in", dest
return dest
def copy_library():
dest = tempfile.mktemp()
os.mkdir(dest)
dest = tempfile.mkdtemp()
libdir = os.path.split(test.__path__[0])[0]
print "Found standard library in", libdir
print "Creating copy of standard library in", dest

View file

@ -807,19 +807,19 @@ class FaqWizard:
f.close()
import tempfile
tfn = tempfile.mktemp()
f = open(tfn, 'w')
emit(LOGHEADER, self.ui, os.environ, date=date, _file=f)
f.close()
tf = tempfile.NamedTemporaryFile()
emit(LOGHEADER, self.ui, os.environ, date=date, _file=tfn)
tf.flush()
tf.seek(0)
command = interpolate(SH_CHECKIN, file=file, tfn=tfn)
command = interpolate(SH_CHECKIN, file=file, tfn=tf.name)
log("\n\n" + command)
p = os.popen(command)
output = p.read()
sts = p.close()
log("output: " + output)
log("done: " + str(sts))
log("TempFile:\n" + open(tfn).read() + "end")
log("TempFile:\n" + tf.read() + "end")
if not sts:
self.prologue(T_COMMITTED)

View file

@ -280,9 +280,11 @@ class IOBinding:
if self.get_saved():
filename = self.filename
else:
filename = tempfilename = tempfile.mktemp()
(tfd, tfn) = tempfile.mkstemp()
os.close(tfd)
filename = tfn
if not self.writefile(filename):
os.unlink(tempfilename)
os.unlink(tfn)
return "break"
edconf = idleconf.getsection('EditorWindow')
command = edconf.get('print-command')