Fix scripts to work with Python 3 without 2to3.

This commit is contained in:
Valentin Lorentz 2013-04-27 16:16:08 +02:00
parent 7fcda679d8
commit 4090793468
7 changed files with 48 additions and 45 deletions

View File

@ -42,7 +42,10 @@ import sys
import atexit
import shutil
import signal
import cStringIO as StringIO
if sys.version_info[0] < 3:
import cStringIO as StringIO
else:
from io import StringIO
if sys.version_info < (2, 6, 0):
sys.stderr.write('This program requires Python >= 2.6.0')
@ -50,7 +53,7 @@ if sys.version_info < (2, 6, 0):
sys.exit(-1)
def _termHandler(signalNumber, stackFrame):
raise SystemExit, 'Signal #%s.' % signalNumber
raise SystemExit('Signal #%s.' % signalNumber)
signal.signal(signal.SIGTERM, _termHandler)
@ -102,7 +105,7 @@ def main():
'Ctrl-C at console.'
irc.queueMsg(ircmsgs.quit(quitmsg))
irc.die()
except SystemExit, e:
except SystemExit as e:
s = str(e)
if s:
log.info('Exiting due to %s', s)
@ -110,17 +113,17 @@ def main():
except:
try: # Ok, now we're *REALLY* paranoid!
log.exception('Exception raised out of drivers.run:')
except Exception, e:
print 'Exception raised in log.exception. This is *really*'
print 'bad. Hopefully it won\'t happen again, but tell us'
print 'about it anyway, this is a significant problem.'
print 'Anyway, here\'s the exception: %s' % \
utils.gen.exnToString(e)
except Exception as e:
print('Exception raised in log.exception. This is *really*')
print('bad. Hopefully it won\'t happen again, but tell us')
print('about it anyway, this is a significant problem.')
print('Anyway, here\'s the exception: %s' % \
utils.gen.exnToString(e))
except:
print 'Oh, this really sucks. Not only did log.exception'
print 'raise an exception, but freaking-a, it was a string'
print 'exception. People who raise string exceptions should'
print 'die a slow, painful death.'
print('Oh, this really sucks. Not only did log.exception')
print('raise an exception, but freaking-a, it was a string')
print('exception. People who raise string exceptions should')
print('die a slow, painful death.')
httpserver.stopServer()
now = time.time()
seconds = now - world.startedAt
@ -186,7 +189,7 @@ if __name__ == '__main__':
# The registry *MUST* be opened before importing log or conf.
registry.open_registry(registryFilename)
shutil.copy(registryFilename, registryFilename + '.bak')
except registry.InvalidRegistryFile, e:
except registry.InvalidRegistryFile as e:
s = '%s in %s. Please fix this error and start supybot again.' % \
(e, registryFilename)
s = textwrap.fill(s)
@ -194,14 +197,14 @@ if __name__ == '__main__':
sys.stderr.write(os.linesep)
raise
sys.exit(-1)
except EnvironmentError, e:
except EnvironmentError as e:
sys.stderr.write(str(e))
sys.stderr.write(os.linesep)
sys.exit(-1)
try:
import supybot.log as log
except supybot.registry.InvalidRegistryValue, e:
except supybot.registry.InvalidRegistryValue as e:
# This is raised here because supybot.log imports supybot.conf.
name = e.value._name
errmsg = textwrap.fill('%s: %s' % (name, e),
@ -245,7 +248,7 @@ if __name__ == '__main__':
child = os.fork()
if child != 0:
if options.debug:
print 'Parent exiting, child PID: %s' % child
print('Parent exiting, child PID: %s' % child)
# We must us os._exit instead of sys.exit so atexit handlers
# don't run. They shouldn't be dangerous, but they're ugly.
os._exit(0)
@ -297,10 +300,10 @@ if __name__ == '__main__':
def removePidFile():
try:
os.remove(pidFile)
except EnvironmentError, e:
except EnvironmentError as e:
log.error('Could not remove pid file: %s', e)
atexit.register(removePidFile)
except EnvironmentError, e:
except EnvironmentError as e:
log.critical('Error opening/writing pid file %s: %s', pidFile, e)
sys.exit(-1)

View File

@ -118,7 +118,7 @@ def main():
ircdb.users.flush()
#os.system('cat %s' % filename) # Was this here just for debugging?
ircdb.users.close()
print 'User %s added.' % name
print('User %s added.' % name)
if __name__ == '__main__':
try:

View File

@ -103,7 +103,7 @@ if __name__ == '__main__':
try:
pid = readPid(options.pidfile)
debug('Found pidFile with proper pid contents of %s' % pid)
except ValueError, e:
except ValueError as e:
foundBot = False
if pid is not None:
@ -118,7 +118,7 @@ if __name__ == '__main__':
# so we go ahead and refuse to start it.
try:
open(options.pidfile, 'r+')
except EnvironmentError, e:
except EnvironmentError as e:
debug('pidfile (%s) is not writable: %s' % (options.pidfile, e))
sys.exit(-1)
debug('Bot not found, starting.')

View File

@ -238,7 +238,7 @@ def main():
if name.endswith('.py'):
name = name[:-3]
while name[0].islower():
print 'Plugin names must begin with a capital letter.'
print('Plugin names must begin with a capital letter.')
name = something('What should the name of the plugin be?')
if name.endswith('.py'):
name = name[:-3]
@ -247,12 +247,12 @@ def main():
error('A file or directory named %s already exists; remove or '
'rename it and run this program again.' % name)
print textwrap.fill(textwrap.dedent("""
print(textwrap.fill(textwrap.dedent("""
Sometimes you'll want a callback to be threaded. If its methods
(command or regexp-based, either one) will take a significant amount
of time to run, you'll want to thread them so they don't block the
entire bot.""").strip())
print
entire bot.""").strip()))
print()
threaded = yn('Does your plugin need to be threaded?')
realName = something(textwrap.dedent("""
@ -270,7 +270,7 @@ def main():
if name.endswith('.py'):
name = name[:-3]
while name[0].islower():
print 'Plugin names must begin with a capital.'
print('Plugin names must begin with a capital.')
name = something('What should the name of the plugin be?')
if name.endswith('.py'):
name = name[:-3]
@ -300,13 +300,13 @@ def main():
writeFile('__init__.py',
'# Stub so local is a module, used for third-party modules\n')
print 'Your new plugin template is in the %s directory.' % name
print('Your new plugin template is in the %s directory.' % name)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print
print()
output("""It looks like you cancelled out of this script before it was
finished. Obviously, nothing was written, but just run this script
again whenever you want to generate a template for a plugin.""")

View File

@ -58,7 +58,7 @@ supybot.log.plugins.individualLogfiles: False
supybot.databases: sqlite anydbm cdb flat pickle
""")
fd.close()
except EnvironmentError, e:
except EnvironmentError as e:
error('Unable to open %s for writing.' % registryFilename)
import supybot.registry as registry
@ -224,12 +224,12 @@ class PluginDoc(object):
def genDoc(m, options):
Plugin = PluginDoc(m)
print 'Generating documentation for %s...' % Plugin.name
print('Generating documentation for %s...' % Plugin.name)
path = os.path.join(options.outputDir, '%s.%s' % (Plugin.name,
options.format))
try:
fd = open(path, 'w')
except EnvironmentError, e:
except EnvironmentError as e:
error('Unable to open %s for writing.' % path)
f = getattr(Plugin, 'render%s' % options.format.upper(), None)
if f is None:
@ -283,7 +283,7 @@ if __name__ == '__main__':
pluginName = pluginName[:-3]
try:
pluginModule = plugin.loadPluginModule(pluginName)
except ImportError, e:
except ImportError as e:
s = 'Failed to load plugin %s: %s\n' \
'%s(pluginDirs: %s)' % (pluginName, e, s,
conf.supybot.directories.plugins())

View File

@ -195,7 +195,7 @@ if __name__ == '__main__':
pluginName = pluginName[:-3]
try:
pluginModule = plugin.loadPluginModule(pluginName)
except (ImportError, callbacks.Error), e:
except (ImportError, callbacks.Error) as e:
sys.stderr.write('Failed to load plugin %s: %s\n' % (pluginName,e))
sys.stderr.write('(pluginDirs: %s)\n' %
conf.supybot.directories.plugins())
@ -205,7 +205,7 @@ if __name__ == '__main__':
suite = unittest.TestSuite(test.suites)
runner = unittest.TextTestRunner(verbosity=2)
print 'Testing began at %s (pid %s)' % (time.ctime(), os.getpid())
print('Testing began at %s (pid %s)' % (time.ctime(), os.getpid()))
if options.clean:
shutil.rmtree(conf.supybot.directories.log())
shutil.rmtree(conf.supybot.directories.conf())
@ -213,7 +213,7 @@ if __name__ == '__main__':
result = runner.run(suite)
if hasattr(unittest, 'asserts'):
print 'Total asserts: %s' % unittest.asserts
print('Total asserts: %s' % unittest.asserts)
if result.wasSuccessful():
sys.exit(0)

View File

@ -92,7 +92,7 @@ def loadPlugin(name):
to load when we load the plugin. We'll skip over it for now, but
you can always add it later.""")
return None
except Exception, e:
except Exception as e:
output("""We encountered a bit of trouble trying to load plugin %r.
Python told us %r. We'll skip over it for now, you can always add it
later.""" % (name, utils.gen.exnToString(e)))
@ -140,7 +140,7 @@ def getDirectoryName(default, basedir=os.curdir, prompt=True):
try:
os.makedirs(dir)
done = True
except OSError, e:
except OSError as e:
# 17 is File exists for Linux (and likely other POSIX systems)
# 183 is the same for Windows
if e.args[0] == 17 or (os.name == 'nt' and e.args[0] == 183):
@ -385,7 +385,7 @@ def main():
try:
i = int(port)
if not (0 < i < 65536):
raise ValueError
raise ValueError()
except ValueError:
output("""That's not a valid port.""")
port = 0
@ -468,7 +468,7 @@ def main():
try:
network.channels.set(channels)
break
except registry.InvalidRegistryValue, e:
except registry.InvalidRegistryValue as e:
output(""""%s" is an invalid IRC channel. Be sure to prefix
the channel with # (or +, or !, or &, but no one uses those
channels, really). Be sure the channel key (if you are
@ -484,7 +484,7 @@ def main():
output("""Beginning configuration for %s...""" %
module.Class.__name__)
module.configure(advanced)
print # Blank line :)
print() # Blank line :)
output("""Done!""")
else:
conf.registerPlugin(module.__name__, currentValue=True)
@ -603,7 +603,7 @@ def main():
c = anything('What would you like your bot\'s prefix '
'character(s) to be?')
conf.supybot.reply.whenAddressedBy.chars.set(c)
except registry.InvalidRegistryValue, e:
except registry.InvalidRegistryValue as e:
output(str(e))
c = ''
else:
@ -704,9 +704,9 @@ if __name__ == '__main__':
# We may still be using bold text when exiting during a prompt
if questions.useBold:
import supybot.ansi as ansi
print ansi.RESET
print
print
print(ansi.RESET)
print()
print()
output("""Well, it looks like you canceled out of the wizard before
it was done. Unfortunately, I didn't get to write anything to file.
Please run the wizard again to completion.""")