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

View File

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

View File

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

View File

@ -238,7 +238,7 @@ def main():
if name.endswith('.py'): if name.endswith('.py'):
name = name[:-3] name = name[:-3]
while name[0].islower(): 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?') name = something('What should the name of the plugin be?')
if name.endswith('.py'): if name.endswith('.py'):
name = name[:-3] name = name[:-3]
@ -247,12 +247,12 @@ def main():
error('A file or directory named %s already exists; remove or ' error('A file or directory named %s already exists; remove or '
'rename it and run this program again.' % name) '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 Sometimes you'll want a callback to be threaded. If its methods
(command or regexp-based, either one) will take a significant amount (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 of time to run, you'll want to thread them so they don't block the
entire bot.""").strip()) entire bot.""").strip()))
print print()
threaded = yn('Does your plugin need to be threaded?') threaded = yn('Does your plugin need to be threaded?')
realName = something(textwrap.dedent(""" realName = something(textwrap.dedent("""
@ -270,7 +270,7 @@ def main():
if name.endswith('.py'): if name.endswith('.py'):
name = name[:-3] name = name[:-3]
while name[0].islower(): 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?') name = something('What should the name of the plugin be?')
if name.endswith('.py'): if name.endswith('.py'):
name = name[:-3] name = name[:-3]
@ -300,13 +300,13 @@ def main():
writeFile('__init__.py', writeFile('__init__.py',
'# Stub so local is a module, used for third-party modules\n') '# 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__': if __name__ == '__main__':
try: try:
main() main()
except KeyboardInterrupt: except KeyboardInterrupt:
print print()
output("""It looks like you cancelled out of this script before it was output("""It looks like you cancelled out of this script before it was
finished. Obviously, nothing was written, but just run this script finished. Obviously, nothing was written, but just run this script
again whenever you want to generate a template for a plugin.""") 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 supybot.databases: sqlite anydbm cdb flat pickle
""") """)
fd.close() fd.close()
except EnvironmentError, e: except EnvironmentError as 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
@ -224,12 +224,12 @@ class PluginDoc(object):
def genDoc(m, options): def genDoc(m, options):
Plugin = PluginDoc(m) 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, path = os.path.join(options.outputDir, '%s.%s' % (Plugin.name,
options.format)) options.format))
try: try:
fd = open(path, 'w') fd = open(path, 'w')
except EnvironmentError, e: except EnvironmentError as 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)
if f is None: if f is None:
@ -283,7 +283,7 @@ if __name__ == '__main__':
pluginName = pluginName[:-3] pluginName = pluginName[:-3]
try: try:
pluginModule = plugin.loadPluginModule(pluginName) pluginModule = plugin.loadPluginModule(pluginName)
except ImportError, e: except ImportError as e:
s = 'Failed to load plugin %s: %s\n' \ s = 'Failed to load plugin %s: %s\n' \
'%s(pluginDirs: %s)' % (pluginName, e, s, '%s(pluginDirs: %s)' % (pluginName, e, s,
conf.supybot.directories.plugins()) conf.supybot.directories.plugins())

View File

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