Use open() instead of file().

This commit is contained in:
Valentin Lorentz 2012-08-04 13:13:16 +02:00
parent 505fd580f8
commit d52e501ae8
15 changed files with 42 additions and 42 deletions

View File

@ -199,7 +199,7 @@ class SqliteKarmaDB(object):
def load(self, channel, filename): def load(self, channel, filename):
filename = conf.supybot.directories.data.dirize(filename) filename = conf.supybot.directories.data.dirize(filename)
fd = file(filename) fd = open(filename)
reader = csv.reader(fd) reader = csv.reader(fd)
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()

View File

@ -153,7 +153,7 @@ class Status(callbacks.Plugin):
cmd = 'ps -o rss -p %s' % pid cmd = 'ps -o rss -p %s' % pid
try: try:
inst = subprocess.Popen(cmd.split(), close_fds=True, inst = subprocess.Popen(cmd.split(), close_fds=True,
stdin=file(os.devnull), stdin=open(os.devnull),
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
except OSError: except OSError:

View File

@ -212,7 +212,7 @@ class Unix(callbacks.Plugin):
inst = subprocess.Popen(args, close_fds=True, inst = subprocess.Popen(args, close_fds=True,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=file(os.devnull)) stdin=open(os.devnull))
except OSError, e: except OSError, e:
irc.error(_('It seems the configured fortune command was ' irc.error(_('It seems the configured fortune command was '
'not available.'), Raise=True) 'not available.'), Raise=True)
@ -242,8 +242,8 @@ class Unix(callbacks.Plugin):
try: try:
inst = subprocess.Popen([wtfCmd, something], close_fds=True, inst = subprocess.Popen([wtfCmd, something], close_fds=True,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=file(os.devnull), stderr=open(os.devnull),
stdin=file(os.devnull)) stdin=open(os.devnull))
except OSError: except OSError:
irc.error(_('It seems the configured wtf command was not ' irc.error(_('It seems the configured wtf command was not '
'available.'), Raise=True) 'available.'), Raise=True)
@ -292,7 +292,7 @@ class Unix(callbacks.Plugin):
try: try:
inst = subprocess.Popen(args, stdout=subprocess.PIPE, inst = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=file(os.devnull)) stdin=open(os.devnull))
except OSError, e: except OSError, e:
irc.error('It seems the configured ping command was ' irc.error('It seems the configured ping command was '
'not available (%s).' % e, Raise=True) 'not available (%s).' % e, Raise=True)
@ -325,7 +325,7 @@ class Unix(callbacks.Plugin):
inst = subprocess.Popen(args, close_fds=True, inst = subprocess.Popen(args, close_fds=True,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=file(os.devnull)) stdin=open(os.devnull))
except OSError, e: except OSError, e:
irc.error('It seems the configured uptime command was ' irc.error('It seems the configured uptime command was '
'not available.', Raise=True) 'not available.', Raise=True)
@ -353,7 +353,7 @@ class Unix(callbacks.Plugin):
inst = subprocess.Popen(args, close_fds=True, inst = subprocess.Popen(args, close_fds=True,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=file(os.devnull)) stdin=open(os.devnull))
except OSError, e: except OSError, e:
irc.error('It seems the configured uptime command was ' irc.error('It seems the configured uptime command was '
'not available.', Raise=True) 'not available.', Raise=True)
@ -382,7 +382,7 @@ class Unix(callbacks.Plugin):
try: try:
inst = subprocess.Popen(args, stdout=subprocess.PIPE, inst = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=file(os.devnull)) stdin=open(os.devnull))
except OSError, e: except OSError, e:
irc.error('It seems the requested command was ' irc.error('It seems the requested command was '
'not available (%s).' % e, Raise=True) 'not available (%s).' % e, Raise=True)

View File

@ -267,7 +267,7 @@ class ChannelUserDB(ChannelUserDictionary):
ChannelUserDictionary.__init__(self) ChannelUserDictionary.__init__(self)
self.filename = filename self.filename = filename
try: try:
fd = file(self.filename) fd = open(self.filename)
except EnvironmentError, e: except EnvironmentError, e:
log.warning('Couldn\'t open %s: %s.', self.filename, e) log.warning('Couldn\'t open %s: %s.', self.filename, e)
return return
@ -564,7 +564,7 @@ class PeriodicFileDownloader(object):
return return
confDir = conf.supybot.directories.data() confDir = conf.supybot.directories.data()
newFilename = os.path.join(confDir, utils.file.mktemp()) newFilename = os.path.join(confDir, utils.file.mktemp())
outfd = file(newFilename, 'wb') outfd = open(newFilename, 'wb')
start = time.time() start = time.time()
s = infd.read(4096) s = infd.read(4096)
while s: while s:

View File

@ -184,7 +184,7 @@ if __name__ == '__main__':
i18n.getLocaleFromRegistryFilename(registryFilename) i18n.getLocaleFromRegistryFilename(registryFilename)
try: try:
# The registry *MUST* be opened before importing log or conf. # The registry *MUST* be opened before importing log or conf.
registry.open(registryFilename) registry.open_registry(registryFilename)
shutil.copy(registryFilename, registryFilename + '.bak') shutil.copy(registryFilename, registryFilename + '.bak')
except registry.InvalidRegistryFile, e: except registry.InvalidRegistryFile, e:
s = '%s in %s. Please fix this error and start supybot again.' % \ s = '%s in %s. Please fix this error and start supybot again.' % \
@ -290,7 +290,7 @@ if __name__ == '__main__':
pidFile = conf.supybot.pidFile() pidFile = conf.supybot.pidFile()
if pidFile: if pidFile:
try: try:
fd = file(pidFile, 'w') fd = open(pidFile, 'w')
pid = os.getpid() pid = os.getpid()
fd.write('%s%s' % (pid, os.linesep)) fd.write('%s%s' % (pid, os.linesep))
fd.close() fd.close()
@ -319,10 +319,10 @@ if __name__ == '__main__':
'userdata.conf') 'userdata.conf')
# Let's open this now since we've got our directories setup. # Let's open this now since we've got our directories setup.
if not os.path.exists(userdataFilename): if not os.path.exists(userdataFilename):
fd = file(userdataFilename, 'w') fd = open(userdataFilename, 'w')
fd.write('\n') fd.write('\n')
fd.close() fd.close()
registry.open(userdataFilename) registry.open_registry(userdataFilename)
import supybot.irclib as irclib import supybot.irclib as irclib
import supybot.ircmsgs as ircmsgs import supybot.ircmsgs as ircmsgs

View File

@ -33,7 +33,7 @@
VERBOSE = False VERBOSE = False
def readPid(filename): def readPid(filename):
fd = file(filename) fd = open(filename)
try: try:
return int(fd.read().strip()) return int(fd.read().strip())
finally: finally:

View File

@ -266,7 +266,7 @@ def main():
os.mkdir(pathname) os.mkdir(pathname)
def writeFile(filename, s): def writeFile(filename, s):
fd = file(os.path.join(pathname, filename), 'w') fd = open(os.path.join(pathname, filename), 'w')
try: try:
fd.write(s) fd.write(s)
finally: finally:

View File

@ -46,7 +46,7 @@ if not os.path.exists('doc-conf'):
registryFilename = os.path.join('doc-conf', 'doc.conf') registryFilename = os.path.join('doc-conf', 'doc.conf')
try: try:
fd = file(registryFilename, 'w') fd = open(registryFilename, 'w')
fd.write(""" fd.write("""
supybot.directories.data: doc-data supybot.directories.data: doc-data
supybot.directories.conf: doc-conf supybot.directories.conf: doc-conf
@ -62,7 +62,7 @@ except EnvironmentError, e:
error('Unable to open %s for writing.' % registryFilename) error('Unable to open %s for writing.' % registryFilename)
import supybot.registry as registry import supybot.registry as registry
registry.open(registryFilename) registry.open_registry(registryFilename)
import supybot.log as log import supybot.log as log
import supybot.conf as conf import supybot.conf as conf
@ -228,7 +228,7 @@ def genDoc(m, options):
path = os.path.join(options.outputDir, '%s.%s' % (Plugin.name, path = os.path.join(options.outputDir, '%s.%s' % (Plugin.name,
options.format)) options.format))
try: try:
fd = file(path, 'w') fd = open(path, 'w')
except EnvironmentError, e: except EnvironmentError, e:
error('Unable to open %s for writing.' % path) error('Unable to open %s for writing.' % path)
f = getattr(Plugin, 'render%s' % options.format.upper(), None) f = getattr(Plugin, 'render%s' % options.format.upper(), None)

View File

@ -43,7 +43,7 @@ if not os.path.exists('test-conf'):
os.mkdir('test-conf') os.mkdir('test-conf')
registryFilename = os.path.join('test-conf', 'test.conf') registryFilename = os.path.join('test-conf', 'test.conf')
fd = file(registryFilename, 'w') fd = open(registryFilename, 'w')
fd.write(""" fd.write("""
supybot.directories.data: test-data supybot.directories.data: test-data
supybot.directories.conf: test-conf supybot.directories.conf: test-conf
@ -62,7 +62,7 @@ supybot.databases.users.allowUnregistration: True
fd.close() fd.close()
import supybot.registry as registry import supybot.registry as registry
registry.open(registryFilename) registry.open_registry(registryFilename)
import supybot.log as log import supybot.log as log
import supybot.conf as conf import supybot.conf as conf
@ -159,7 +159,7 @@ if __name__ == '__main__':
if options.trace: if options.trace:
traceFilename = conf.supybot.directories.log.dirize('trace.log') traceFilename = conf.supybot.directories.log.dirize('trace.log')
fd = file(traceFilename, 'w') fd = open(traceFilename, 'w')
sys.settrace(utils.gen.callTracer(fd)) sys.settrace(utils.gen.callTracer(fd))
atexit.register(fd.close) atexit.register(fd.close)
atexit.register(lambda : sys.settrace(None)) atexit.register(lambda : sys.settrace(None))

View File

@ -42,7 +42,7 @@ import supybot.world as world
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.registry as registry import supybot.registry as registry
import supybot.unpreserve as unpreserve import supybot.unpreserve as unpreserve
from utils.iter import imap, ilen, ifilter from itertools import imap, ifilter
def isCapability(capability): def isCapability(capability):
return len(capability.split(None, 1)) == 1 return len(capability.split(None, 1)) == 1
@ -844,7 +844,7 @@ class IgnoresDB(object):
def open(self, filename): def open(self, filename):
self.filename = filename self.filename = filename
fd = file(self.filename) fd = open(self.filename)
for line in utils.file.nonCommentNonEmptyLines(fd): for line in utils.file.nonCommentNonEmptyLines(fd):
try: try:
line = line.rstrip('\r\n') line = line.rstrip('\r\n')

View File

@ -62,12 +62,12 @@ class NonExistentRegistryEntry(RegistryException):
_cache = utils.InsensitivePreservingDict() _cache = utils.InsensitivePreservingDict()
_lastModified = 0 _lastModified = 0
def open(filename, clear=False): def open_registry(filename, clear=False):
"""Initializes the module by loading the registry file into memory.""" """Initializes the module by loading the registry file into memory."""
global _lastModified global _lastModified
if clear: if clear:
_cache.clear() _cache.clear()
_fd = file(filename) _fd = open(filename)
fd = utils.file.nonCommentNonEmptyLines(_fd) fd = utils.file.nonCommentNonEmptyLines(_fd)
acc = '' acc = ''
slashEnd = re.compile(r'\\*$') slashEnd = re.compile(r'\\*$')

View File

@ -40,7 +40,7 @@ class Reader(object):
return s.lower() return s.lower()
def readFile(self, filename): def readFile(self, filename):
self.read(file(filename)) self.read(open(filename))
def read(self, fd): def read(self, fd):
lineno = 0 lineno = 0

View File

@ -39,9 +39,9 @@ from iter import ifilter
import crypt import crypt
def contents(filename): def contents(filename):
return file(filename).read() return open(filename).read()
def open(filename, mode='wb', *args, **kwargs): def open_mkdir(filename, mode='wb', *args, **kwargs):
"""filename -> file object. """filename -> file object.
Returns a file object for filename, creating as many directories as may be Returns a file object for filename, creating as many directories as may be
@ -53,15 +53,15 @@ def open(filename, mode='wb', *args, **kwargs):
raise ValueError, 'utils.file.open expects to write.' raise ValueError, 'utils.file.open expects to write.'
(dirname, basename) = os.path.split(filename) (dirname, basename) = os.path.split(filename)
os.makedirs(dirname) os.makedirs(dirname)
return file(filename, mode, *args, **kwargs) return open(filename, mode, *args, **kwargs)
def copy(src, dst): def copy(src, dst):
"""src, dst -> None """src, dst -> None
Copies src to dst, using this module's 'open' function to open dst. Copies src to dst, using this module's 'open' function to open dst.
""" """
srcfd = file(src) srcfd = open(src)
dstfd = open(dst, 'wb') dstfd = open_mkdir(dst, 'wb')
shutil.copyfileobj(srcfd, dstfd) shutil.copyfileobj(srcfd, dstfd)
def writeLine(fd, line): def writeLine(fd, line):
@ -70,14 +70,14 @@ def writeLine(fd, line):
fd.write('\n') fd.write('\n')
def readLines(filename): def readLines(filename):
fd = file(filename) fd = open(filename)
try: try:
return [line.rstrip('\r\n') for line in fd.readlines()] return [line.rstrip('\r\n') for line in fd.readlines()]
finally: finally:
fd.close() fd.close()
def touch(filename): def touch(filename):
fd = file(filename, 'w') fd = open(filename, 'w')
fd.close() fd.close()
def mktemp(suffix=''): def mktemp(suffix=''):
@ -190,7 +190,7 @@ class AtomicFile(file):
# rename a file (and shutil.move will use os.rename if # rename a file (and shutil.move will use os.rename if
# possible), we first check if we have the write permission # possible), we first check if we have the write permission
# and only then do we write. # and only then do we write.
fd = file(self.filename, 'a') fd = open(self.filename, 'a')
fd.close() fd.close()
shutil.move(self.tempFilename, self.filename) shutil.move(self.tempFilename, self.filename)

View File

@ -84,7 +84,7 @@ class TransactionMixin(python.Object):
raise InvalidCwd(expected) raise InvalidCwd(expected)
def _journalCommands(self): def _journalCommands(self):
journal = file(self._journalName) journal = open(self._journalName)
for line in journal: for line in journal:
line = line.rstrip('\n') line = line.rstrip('\n')
(command, rest) = line.split(None, 1) (command, rest) = line.split(None, 1)
@ -112,8 +112,8 @@ class Transaction(TransactionMixin):
raise FailedAcquisition(self.txnDir, e) raise FailedAcquisition(self.txnDir, e)
os.mkdir(self.dirize(self.ORIGINALS)) os.mkdir(self.dirize(self.ORIGINALS))
os.mkdir(self.dirize(self.REPLACEMENTS)) os.mkdir(self.dirize(self.REPLACEMENTS))
self._journal = file(self._journalName, 'a') self._journal = open(self._journalName, 'a')
cwd = file(self.dirize('cwd'), 'w') cwd = open(self.dirize('cwd'), 'w')
cwd.write(os.getcwd()) cwd.write(os.getcwd())
cwd.close() cwd.close()
@ -179,7 +179,7 @@ class Transaction(TransactionMixin):
self._journalCommand('append', filename, length) self._journalCommand('append', filename, length)
replacement = self._replacement(filename) replacement = self._replacement(filename)
File.copy(filename, replacement) File.copy(filename, replacement)
return file(replacement, 'a') return open(replacement, 'a')
def commit(self, removeWhenComplete=True): def commit(self, removeWhenComplete=True):
self._journal.close() self._journal.close()
@ -218,7 +218,7 @@ class Rollback(TransactionMixin):
shutil.copy(self._original(filename), filename) shutil.copy(self._original(filename), filename)
def rollbackAppend(self, filename, length): def rollbackAppend(self, filename, length):
fd = file(filename, 'a') fd = open(filename, 'a')
fd.truncate(int(length)) fd.truncate(int(length))
fd.close() fd.close()

View File

@ -171,7 +171,7 @@ class ValuesTestCase(SupyTestCase):
conf.supybot.reply.whenAddressedBy.chars.set('\\') conf.supybot.reply.whenAddressedBy.chars.set('\\')
filename = conf.supybot.directories.conf.dirize('backslashes.conf') filename = conf.supybot.directories.conf.dirize('backslashes.conf')
registry.close(conf.supybot, filename) registry.close(conf.supybot, filename)
registry.open(filename) registry.open_registry(filename)
self.assertEqual(conf.supybot.reply.whenAddressedBy.chars(), '\\') self.assertEqual(conf.supybot.reply.whenAddressedBy.chars(), '\\')
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: