Created
May 21, 2016 15:17
-
-
Save alex/0651ba377cb644df503a23e63aa5b9a9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/twisted/conch/client/default.py b/twisted/conch/client/default.py | |
index 42c3c7a..fc7834a 100644 | |
--- a/twisted/conch/client/default.py | |
+++ b/twisted/conch/client/default.py | |
@@ -11,6 +11,8 @@ you are sitting at an interactive terminal. For example, to programmatically | |
interact with a known_hosts database, use L{twisted.conch.client.knownhosts}. | |
""" | |
+from __future__ import print_function | |
+ | |
from twisted.python import log | |
from twisted.python.filepath import FilePath | |
@@ -90,7 +92,7 @@ def isInKnownHosts(host, pubKey, options): | |
retVal = 0 | |
if not options['known-hosts'] and not os.path.exists(os.path.expanduser('~/.ssh/')): | |
- print 'Creating ~/.ssh directory...' | |
+ print('Creating ~/.ssh directory...') | |
os.mkdir(os.path.expanduser('~/.ssh')) | |
kh_file = options['known-hosts'] or _KNOWN_HOSTS | |
try: | |
@@ -247,9 +249,9 @@ class SSHUserAuthClient(userauth.SSHUserAuthClient): | |
oldout, oldin = sys.stdout, sys.stdin | |
sys.stdin = sys.stdout = open('/dev/tty','r+') | |
if name: | |
- print name | |
+ print(name) | |
if instruction: | |
- print instruction | |
+ print(instruction) | |
for prompt, echo in prompts: | |
if echo: | |
responses.append(raw_input(prompt)) | |
diff --git a/twisted/conch/client/direct.py b/twisted/conch/client/direct.py | |
index f95a14a..4c52398 100644 | |
--- a/twisted/conch/client/direct.py | |
+++ b/twisted/conch/client/direct.py | |
@@ -1,6 +1,8 @@ | |
# Copyright (c) Twisted Matrix Laboratories. | |
# See LICENSE for details. | |
+from __future__ import print_function | |
+ | |
from twisted.internet import defer, protocol, reactor | |
from twisted.conch import error | |
@@ -79,7 +81,7 @@ class SSHClientTransport(transport.SSHClientTransport): | |
def receiveDebug(self, alwaysDisplay, message, lang): | |
log.msg('Received Debug Message: %s' % message) | |
if alwaysDisplay: # XXX what should happen here? | |
- print message | |
+ print(message) | |
def verifyHostKey(self, pubKey, fingerprint): | |
diff --git a/twisted/conch/insults/client.py b/twisted/conch/insults/client.py | |
index 89c79cd..1166e58 100644 | |
--- a/twisted/conch/insults/client.py | |
+++ b/twisted/conch/insults/client.py | |
@@ -2,6 +2,8 @@ | |
You don't really want to use this module. Try insults.py instead. | |
""" | |
+from __future__ import print_function | |
+ | |
from twisted.internet import protocol | |
class InsultsClient(protocol.Protocol): | |
@@ -94,7 +96,7 @@ class InsultsClient(protocol.Protocol): | |
"""Erase from the current position to the end of the screen. | |
""" | |
self.commandQueue.append(('eraseeos',)) | |
- | |
+ | |
def clearScreen(self): | |
"""Clear the screen, and return the cursor to 0, 0. | |
""" | |
@@ -124,7 +126,7 @@ class InsultsClient(protocol.Protocol): | |
elif command[0] == 'attributes': | |
redraw += '\x1b[%sm' % ';'.join(map(str, command[1])) | |
else: | |
- print command | |
+ print(command) | |
self.commandQueue = [] | |
self.transport.write(redraw) | |
diff --git a/twisted/conch/insults/helper.py b/twisted/conch/insults/helper.py | |
index 8ee67d1..3e5e304 100644 | |
--- a/twisted/conch/insults/helper.py | |
+++ b/twisted/conch/insults/helper.py | |
@@ -8,6 +8,8 @@ Partial in-memory terminal emulator | |
@author: Jp Calderone | |
""" | |
+from __future__ import print_function | |
+ | |
import re, string | |
from zope.interface import implementer | |
@@ -108,7 +110,7 @@ class TerminalBuffer(protocol.Protocol): | |
'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN', | |
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', | |
'F10', 'F11', 'F12'): | |
- exec '%s = object()' % (keyID,) | |
+ locals()[keyID] = object() | |
TAB = '\t' | |
BACKSPACE = '\x7f' | |
@@ -393,7 +395,7 @@ class TerminalBuffer(protocol.Protocol): | |
self.eraseDisplay() | |
def unhandledControlSequence(self, buf): | |
- print 'Could not handle', repr(buf) | |
+ print('Could not handle', repr(buf)) | |
def __str__(self): | |
lines = [] | |
diff --git a/twisted/conch/insults/insults.py b/twisted/conch/insults/insults.py | |
index 2b6514b..4c2ad1a 100644 | |
--- a/twisted/conch/insults/insults.py | |
+++ b/twisted/conch/insults/insults.py | |
@@ -942,7 +942,7 @@ class ClientProtocol(protocol.Protocol): | |
('B', 'Down'), | |
('C', 'Forward'), | |
('D', 'Backward')): | |
- exec ch + " = _makeSimple(ch, fName)" | |
+ locals()[ch] = _makeSimple(ch, fName) | |
del _makeSimple | |
def h(self, proto, handler, buf): | |
diff --git a/twisted/conch/insults/window.py b/twisted/conch/insults/window.py | |
index 9901327..a5fcfef 100644 | |
--- a/twisted/conch/insults/window.py | |
+++ b/twisted/conch/insults/window.py | |
@@ -386,10 +386,12 @@ class Canvas(Widget): | |
if self.y >= height: | |
self.y = height - 1 | |
- def __getitem__(self, (x, y)): | |
+ def __getitem__(self, pos): | |
+ (x, y) = pos | |
return self.contents[(self._width * y) + x] | |
- def __setitem__(self, (x, y), value): | |
+ def __setitem__(self, pos, value): | |
+ (x, y) = pos | |
self.contents[(self._width * y) + x] = value | |
def clear(self): | |
@@ -409,33 +411,35 @@ class Canvas(Widget): | |
def horizontalLine(terminal, y, left, right): | |
terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0) | |
terminal.cursorPosition(left, y) | |
- terminal.write(chr(0161) * (right - left)) | |
+ terminal.write(chr(0o161) * (right - left)) | |
terminal.selectCharacterSet(insults.CS_US, insults.G0) | |
def verticalLine(terminal, x, top, bottom): | |
terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0) | |
for n in xrange(top, bottom): | |
terminal.cursorPosition(x, n) | |
- terminal.write(chr(0170)) | |
+ terminal.write(chr(0o170)) | |
terminal.selectCharacterSet(insults.CS_US, insults.G0) | |
-def rectangle(terminal, (top, left), (width, height)): | |
+def rectangle(terminal, top_left, dimensions): | |
+ (top, left) = top_left | |
+ (width, height) = dimensions | |
terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0) | |
terminal.cursorPosition(top, left) | |
- terminal.write(chr(0154)) | |
- terminal.write(chr(0161) * (width - 2)) | |
- terminal.write(chr(0153)) | |
+ terminal.write(chr(0o154)) | |
+ terminal.write(chr(0o161) * (width - 2)) | |
+ terminal.write(chr(0o153)) | |
for n in range(height - 2): | |
terminal.cursorPosition(left, top + n + 1) | |
- terminal.write(chr(0170)) | |
+ terminal.write(chr(0o170)) | |
terminal.cursorForward(width - 2) | |
- terminal.write(chr(0170)) | |
+ terminal.write(chr(0o170)) | |
terminal.cursorPosition(0, top + height - 1) | |
- terminal.write(chr(0155)) | |
- terminal.write(chr(0161) * (width - 2)) | |
- terminal.write(chr(0152)) | |
+ terminal.write(chr(0o155)) | |
+ terminal.write(chr(0o161) * (width - 2)) | |
+ terminal.write(chr(0o152)) | |
terminal.selectCharacterSet(insults.CS_US, insults.G0) | |
diff --git a/twisted/conch/recvline.py b/twisted/conch/recvline.py | |
index cd6b5cc..2f71477 100644 | |
--- a/twisted/conch/recvline.py | |
+++ b/twisted/conch/recvline.py | |
@@ -60,7 +60,7 @@ class TransportSequence(object): | |
'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN', | |
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', | |
'F10', 'F11', 'F12'): | |
- exec '%s = object()' % (keyID,) | |
+ locals()[keyID] = object() | |
TAB = '\t' | |
BACKSPACE = '\x7f' | |
diff --git a/twisted/conch/scripts/cftp.py b/twisted/conch/scripts/cftp.py | |
index 1170fed..d4b3a7b 100644 | |
--- a/twisted/conch/scripts/cftp.py | |
+++ b/twisted/conch/scripts/cftp.py | |
@@ -5,7 +5,8 @@ | |
""" | |
Implementation module for the I{cftp} command. | |
""" | |
-from __future__ import division | |
+from __future__ import division, print_function | |
+ | |
import os, sys, getpass, struct, tty, fcntl, stat | |
import fnmatch, pwd, glob | |
@@ -57,8 +58,8 @@ def run(): | |
options = ClientOptions() | |
try: | |
options.parseOptions(args) | |
- except usage.UsageError, u: | |
- print 'ERROR: %s' % u | |
+ except usage.UsageError as u: | |
+ print('ERROR: %s' % u) | |
sys.exit(1) | |
if options['log']: | |
realout = sys.stdout | |
@@ -105,7 +106,7 @@ def _ebExit(f): | |
s = f.value.value | |
else: | |
s = str(f) | |
- print s | |
+ print(s) | |
#exitStatus = "conch: exiting with error %s" % f | |
try: | |
reactor.stop() | |
@@ -764,11 +765,11 @@ version Print the SFTP version. | |
def _abbrevSize(self, size): | |
# from http://mail.python.org/pipermail/python-list/1999-December/018395.html | |
_abbrevs = [ | |
- (1<<50L, 'PB'), | |
- (1<<40L, 'TB'), | |
- (1<<30L, 'GB'), | |
- (1<<20L, 'MB'), | |
- (1<<10L, 'kB'), | |
+ (1<<50, 'PB'), | |
+ (1<<40, 'TB'), | |
+ (1<<30, 'GB'), | |
+ (1<<20, 'MB'), | |
+ (1<<10, 'kB'), | |
(1, 'B') | |
] | |
@@ -856,12 +857,12 @@ version Print the SFTP version. | |
elif c == '\\': # quoted character | |
del line[i] | |
if line[i] not in '\'"\\': | |
- raise IndexError, "bad quote: \\%s" % line[i] | |
+ raise IndexError("bad quote: \\%s" % line[i]) | |
ret.append(line[i]) | |
else: | |
ret.append(line[i]) | |
except IndexError: | |
- raise IndexError, "unterminated quote" | |
+ raise IndexError("unterminated quote") | |
ret = line.split(None, 1) | |
if len(ret) == 1: | |
return ret[0], '' | |
@@ -928,4 +929,3 @@ class SSHSession(channel.SSHChannel): | |
if __name__ == '__main__': | |
run() | |
- | |
diff --git a/twisted/conch/scripts/ckeygen.py b/twisted/conch/scripts/ckeygen.py | |
index 46ee18e..6bb2674 100644 | |
--- a/twisted/conch/scripts/ckeygen.py | |
+++ b/twisted/conch/scripts/ckeygen.py | |
@@ -6,6 +6,8 @@ | |
Implementation module for the `ckeygen` command. | |
""" | |
+from __future__ import print_function | |
+ | |
import sys, os, getpass, socket | |
if getpass.getpass == getpass.unix_getpass: | |
try: | |
@@ -48,8 +50,8 @@ def run(): | |
options = GeneralOptions() | |
try: | |
options.parseOptions(sys.argv[1:]) | |
- except usage.UsageError, u: | |
- print 'ERROR: %s' % u | |
+ except usage.UsageError as u: | |
+ print('ERROR: %s' % u) | |
options.opt_help() | |
sys.exit(1) | |
log.discardLogs() | |
@@ -85,7 +87,7 @@ def generateRSAkey(options): | |
from cryptography.hazmat.backends import default_backend | |
from cryptography.hazmat.primitives.asymmetric import rsa | |
- print 'Generating public/private rsa key pair.' | |
+ print('Generating public/private rsa key pair.') | |
keyPrimitive = rsa.generate_private_key( | |
key_size=int(options['bits']), | |
public_exponent=65537, | |
@@ -100,7 +102,7 @@ def generateDSAkey(options): | |
from cryptography.hazmat.backends import default_backend | |
from cryptography.hazmat.primitives.asymmetric import dsa | |
- print 'Generating public/private dsa key pair.' | |
+ print('Generating public/private dsa key pair.') | |
keyPrimitive = dsa.generate_private_key( | |
key_size=int(options['bits']), | |
backed=default_backend(), | |
@@ -118,10 +120,10 @@ def printFingerprint(options): | |
options['filename'] += '.pub' | |
try: | |
key = keys.Key.fromFile(options['filename']) | |
- print '%s %s %s' % ( | |
+ print('%s %s %s' % ( | |
key.size(), | |
key.fingerprint(), | |
- os.path.basename(options['filename'])) | |
+ os.path.basename(options['filename']))) | |
except: | |
sys.exit('bad key') | |
@@ -155,7 +157,7 @@ def changePassPhrase(options): | |
p2 = getpass.getpass('Enter same passphrase again: ') | |
if p1 == p2: | |
break | |
- print 'Passphrases do not match. Try again.' | |
+ print('Passphrases do not match. Try again.') | |
options['newpass'] = p1 | |
try: | |
@@ -171,7 +173,7 @@ def changePassPhrase(options): | |
with open(options['filename'], 'w') as fd: | |
fd.write(newkeydata) | |
- print 'Your identification has been saved with the new passphrase.' | |
+ print('Your identification has been saved with the new passphrase.') | |
@@ -186,7 +188,7 @@ def displayPublicKey(options): | |
options['pass'] = getpass.getpass('Enter passphrase: ') | |
key = keys.Key.fromFile( | |
options['filename'], passphrase = options['pass']) | |
- print key.public().toString('openssh') | |
+ print(key.public().toString('openssh')) | |
@@ -209,7 +211,7 @@ def _saveKey(key, options): | |
options['filename'] = newPath.strip() or defaultPath | |
if os.path.exists(options['filename']): | |
- print '%s already exists.' % (options['filename'],) | |
+ print('%s already exists.' % (options['filename'],)) | |
yn = raw_input('Overwrite (y/n)? ') | |
if yn[0].lower() != 'y': | |
sys.exit() | |
@@ -222,7 +224,7 @@ def _saveKey(key, options): | |
p2 = getpass.getpass('Enter same passphrase again: ') | |
if p1 == p2: | |
break | |
- print 'Passphrases do not match. Try again.' | |
+ print('Passphrases do not match. Try again.') | |
options['pass'] = p1 | |
comment = '%s@%s' % (getpass.getuser(), socket.gethostname()) | |
@@ -234,10 +236,10 @@ def _saveKey(key, options): | |
filepath.FilePath(options['filename'] + '.pub').setContent( | |
key.public().toString('openssh', comment)) | |
- print 'Your identification has been saved in %s' % (options['filename'],) | |
- print 'Your public key has been saved in %s.pub' % (options['filename'],) | |
- print 'The key fingerprint is:' | |
- print key.fingerprint() | |
+ print('Your identification has been saved in %s' % (options['filename'],)) | |
+ print('Your public key has been saved in %s.pub' % (options['filename'],)) | |
+ print('The key fingerprint is:') | |
+ print(key.fingerprint()) | |
diff --git a/twisted/conch/scripts/conch.py b/twisted/conch/scripts/conch.py | |
index 91144ec..16c103f 100644 | |
--- a/twisted/conch/scripts/conch.py | |
+++ b/twisted/conch/scripts/conch.py | |
@@ -8,6 +8,9 @@ | |
#""" Implementation module for the `conch` command. | |
#""" | |
+ | |
+from __future__ import print_function | |
+ | |
from twisted.conch.client import connect, default, options | |
from twisted.conch.error import ConchError | |
from twisted.conch.ssh import connection, common | |
@@ -104,8 +107,8 @@ def run(): | |
options = ClientOptions() | |
try: | |
options.parseOptions(args) | |
- except usage.UsageError, u: | |
- print 'ERROR: %s' % u | |
+ except usage.UsageError as u: | |
+ print('ERROR: %s' % u) | |
options.opt_help() | |
sys.exit(1) | |
if options['log']: | |
@@ -141,7 +144,7 @@ def run(): | |
if (options['command'] and options['tty']) or not options['notty']: | |
signal.signal(signal.SIGWINCH, signal.SIG_DFL) | |
if sys.stdout.isatty() and not options['command']: | |
- print 'Connection to %s closed.' % options['host'] | |
+ print('Connection to %s closed.' % options['host']) | |
sys.exit(exitStatus) | |
def handleError(): | |
@@ -209,7 +212,7 @@ def onConnect(): | |
for i in range(3): | |
try: | |
os.close(i) | |
- except OSError, e: | |
+ except OSError as e: | |
import errno | |
if e.errno != errno.EBADF: | |
raise | |
@@ -505,4 +508,3 @@ def _enterRawMode(): | |
if __name__ == '__main__': | |
run() | |
- | |
diff --git a/twisted/conch/scripts/tkconch.py b/twisted/conch/scripts/tkconch.py | |
index 491dd9f..9763fc9 100644 | |
--- a/twisted/conch/scripts/tkconch.py | |
+++ b/twisted/conch/scripts/tkconch.py | |
@@ -6,6 +6,8 @@ | |
Implementation module for the `tkconch` command. | |
""" | |
+from __future__ import print_function | |
+ | |
import Tkinter, tkFileDialog, tkMessageBox | |
from twisted.conch import error | |
from twisted.conch.ui import tkvt100 | |
@@ -300,8 +302,8 @@ def run(): | |
options = GeneralOptions() | |
try: | |
options.parseOptions(args) | |
- except usage.UsageError, u: | |
- print 'ERROR: %s' % u | |
+ except usage.UsageError as u: | |
+ print('ERROR: %s' % u) | |
options.opt_help() | |
sys.exit(1) | |
for k,v in options.items(): | |
@@ -441,7 +443,7 @@ class SSHUserAuthClient(userauth.SSHUserAuthClient): | |
return None | |
try: | |
return defer.succeed(keys.Key.fromFile(file).keyObject) | |
- except keys.BadKeyError, e: | |
+ except keys.BadKeyError as e: | |
if e.args[0] == 'encrypted key with no password': | |
prompt = "Enter passphrase for key '%s': " % \ | |
self.usedFiles[-1] | |
@@ -543,7 +545,7 @@ class SSHSession(channel.SSHChannel): | |
def dataReceived(self, data): | |
if options['ansilog']: | |
- print repr(data) | |
+ print(repr(data)) | |
frame.write(data) | |
def extReceived(self, t, data): | |
diff --git a/twisted/conch/ssh/_kex.py b/twisted/conch/ssh/_kex.py | |
index e473b88..5c89495 100644 | |
--- a/twisted/conch/ssh/_kex.py | |
+++ b/twisted/conch/ssh/_kex.py | |
@@ -91,12 +91,12 @@ class _DHGroup1SHA1(object): | |
preference = 3 | |
hashProcessor = sha1 | |
# Diffie-Hellman primes from Oakley Group 2 (RFC 2409, 6.2). | |
- prime = long('17976931348623159077083915679378745319786029604875601170644' | |
+ prime = int('17976931348623159077083915679378745319786029604875601170644' | |
'44236841971802161585193689478337958649255415021805654859805036464405' | |
'48199239100050792877003355816639229553136239076508735759914822574862' | |
'57500742530207744771258955095793777842444242661733472762929938766870' | |
- '9205606050270810842907692932019128194467627007L') | |
- generator = 2L | |
+ '9205606050270810842907692932019128194467627007') | |
+ generator = 2 | |
@@ -110,7 +110,7 @@ class _DHGroup14SHA1(object): | |
preference = 4 | |
hashProcessor = sha1 | |
# Diffie-Hellman primes from Oakley Group 14 (RFC 3526, 3). | |
- prime = long('32317006071311007300338913926423828248817941241140239112842' | |
+ prime = int('32317006071311007300338913926423828248817941241140239112842' | |
'00975140074170663435422261968941736356934711790173790970419175460587' | |
'32091950288537589861856221532121754125149017745202702357960782362488' | |
'84246189477587641105928646099411723245426622522193230540919037680524' | |
@@ -119,8 +119,8 @@ class _DHGroup14SHA1(object): | |
'00977202194168647225871031411336429319536193471636533209717077448227' | |
'98858856536920864529663607725026895550592836275112117409697299806841' | |
'05543595848665832916421362182310789909994486524682624169720359118525' | |
- '07045361090559L') | |
- generator = 2L | |
+ '07045361090559') | |
+ generator = 2 | |
diff --git a/twisted/conch/ssh/connection.py b/twisted/conch/ssh/connection.py | |
index 26fe51d..2040422 100644 | |
--- a/twisted/conch/ssh/connection.py | |
+++ b/twisted/conch/ssh/connection.py | |
@@ -143,7 +143,7 @@ class SSHConnection(service.SSHService): | |
channel.localWindowSize, | |
channel.localMaxPacket)+channel.specificData) | |
log.callWithLogger(channel, channel.channelOpen, packet) | |
- except Exception, e: | |
+ except Exception as e: | |
log.err(e, 'channel open failed') | |
if isinstance(e, error.ConchError): | |
textualInfo, reason = e.args | |
@@ -630,7 +630,7 @@ for name, value in locals().copy().items(): | |
messages[value] = name # doesn't handle doubles | |
import string | |
-alphanums = string.letters + string.digits | |
+alphanums = string.ascii_letters + string.digits | |
TRANSLATE_TABLE = ''.join([chr(i) in alphanums and chr(i) or '_' | |
for i in range(256)]) | |
SSHConnection.protocolMessages = messages | |
diff --git a/twisted/conch/ssh/factory.py b/twisted/conch/ssh/factory.py | |
index 6f8f104..491bcb0 100644 | |
--- a/twisted/conch/ssh/factory.py | |
+++ b/twisted/conch/ssh/factory.py | |
@@ -13,7 +13,7 @@ from twisted.python import log | |
from twisted.conch import error | |
from twisted.conch.ssh import _kex | |
-import transport, userauth, connection | |
+from twisted.conch.ssh import transport, userauth, connection | |
import random | |
diff --git a/twisted/conch/ssh/filetransfer.py b/twisted/conch/ssh/filetransfer.py | |
index 8b50023..640c92d 100644 | |
--- a/twisted/conch/ssh/filetransfer.py | |
+++ b/twisted/conch/ssh/filetransfer.py | |
@@ -153,7 +153,7 @@ class FileTransferServer(FileTransferBase): | |
def _cbOpenFile(self, fileObj, requestId): | |
fileId = str(hash(fileObj)) | |
if fileId in self.openFiles: | |
- raise KeyError, 'id already open' | |
+ raise KeyError('id already open') | |
self.openFiles[fileId] = fileObj | |
self.sendPacket(FXP_HANDLE, requestId + NS(fileId)) | |
@@ -267,7 +267,7 @@ class FileTransferServer(FileTransferBase): | |
def _cbOpenDirectory(self, dirObj, requestId): | |
handle = str(hash(dirObj)) | |
if handle in self.openDirs: | |
- raise KeyError, "already opened this directory" | |
+ raise KeyError("already opened this directory") | |
self.openDirs[handle] = [dirObj, iter(dirObj)] | |
self.sendPacket(FXP_HANDLE, requestId + NS(handle)) | |
@@ -890,7 +890,7 @@ FILEXFER_ATTR_UIDGID = 0x00000002 | |
FILEXFER_ATTR_OWNERGROUP = FILEXFER_ATTR_UIDGID | |
FILEXFER_ATTR_PERMISSIONS = 0x00000004 | |
FILEXFER_ATTR_ACMODTIME = 0x00000008 | |
-FILEXFER_ATTR_EXTENDED = 0x80000000L | |
+FILEXFER_ATTR_EXTENDED = 0x80000000 | |
FILEXFER_TYPE_REGULAR = 1 | |
FILEXFER_TYPE_DIRECTORY = 2 | |
diff --git a/twisted/conch/ssh/userauth.py b/twisted/conch/ssh/userauth.py | |
index b204010..36c96a3 100644 | |
--- a/twisted/conch/ssh/userauth.py | |
+++ b/twisted/conch/ssh/userauth.py | |
@@ -187,12 +187,13 @@ class SSHUserAuthServer(service.SSHService): | |
return d | |
- def _cbFinishedAuth(self, (interface, avatar, logout)): | |
+ def _cbFinishedAuth(self, result): | |
""" | |
The callback when user has successfully been authenticated. For a | |
description of the arguments, see L{twisted.cred.portal.Portal.login}. | |
We start the service requested by the user. | |
""" | |
+ (interface, avatar, logout) = result | |
self.transport.avatar = avatar | |
self.transport.logoutFunction = logout | |
service = self.transport.factory.getService(self.transport, | |
diff --git a/twisted/conch/test/test_conch.py b/twisted/conch/test/test_conch.py | |
index c984c66..720573d 100644 | |
--- a/twisted/conch/test/test_conch.py | |
+++ b/twisted/conch/test/test_conch.py | |
@@ -20,7 +20,7 @@ from twisted.conch.ssh.session import ISession, SSHSession, wrapProtocol | |
try: | |
from twisted.conch.scripts.conch import SSHSession as StdioInteractingSession | |
-except ImportError, e: | |
+except ImportError as e: | |
StdioInteractingSession = None | |
_reason = str(e) | |
del e | |
diff --git a/twisted/conch/test/test_connection.py b/twisted/conch/test/test_connection.py | |
index bf093c8..348c68a 100644 | |
--- a/twisted/conch/test/test_connection.py | |
+++ b/twisted/conch/test/test_connection.py | |
@@ -354,7 +354,7 @@ class ConnectionTests(unittest.TestCase): | |
Like L{test_lookupChannelError}, but for the case where the failure code | |
is represented as a C{long} instead of a C{int}. | |
""" | |
- self._lookupChannelErrorTest(123L) | |
+ self._lookupChannelErrorTest(123) | |
def test_CHANNEL_OPEN_CONFIRMATION(self): | |
diff --git a/twisted/conch/test/test_filetransfer.py b/twisted/conch/test/test_filetransfer.py | |
index a632f46..e943ad3 100644 | |
--- a/twisted/conch/test/test_filetransfer.py | |
+++ b/twisted/conch/test/test_filetransfer.py | |
@@ -94,7 +94,7 @@ class SFTPTestBase(unittest.TestCase): | |
f = file(os.path.join(self.testDir, 'testfile1'),'w') | |
f.write('a'*10+'b'*10) | |
f.write(file('/dev/urandom').read(1024*64)) # random data | |
- os.chmod(os.path.join(self.testDir, 'testfile1'), 0644) | |
+ os.chmod(os.path.join(self.testDir, 'testfile1'), 0o644) | |
file(os.path.join(self.testDir, 'testRemoveFile'), 'w').write('a') | |
file(os.path.join(self.testDir, 'testRenameFile'), 'w').write('a') | |
file(os.path.join(self.testDir, '.testHiddenFile'), 'w').write('a') | |
diff --git a/twisted/conch/test/test_openssh_compat.py b/twisted/conch/test/test_openssh_compat.py | |
index 932c856..06da4d4 100644 | |
--- a/twisted/conch/test/test_openssh_compat.py | |
+++ b/twisted/conch/test/test_openssh_compat.py | |
@@ -85,11 +85,11 @@ class OpenSSHFactoryTests(TestCase): | |
keyFile = self.keysDir.child("ssh_host_two_key") | |
# Fake permission error by changing the mode | |
keyFile.chmod(0000) | |
- self.addCleanup(keyFile.chmod, 0777) | |
+ self.addCleanup(keyFile.chmod, 0o777) | |
# And restore the right mode when seteuid is called | |
savedSeteuid = os.seteuid | |
def seteuid(euid): | |
- keyFile.chmod(0777) | |
+ keyFile.chmod(0o777) | |
return savedSeteuid(euid) | |
self.patch(os, "seteuid", seteuid) | |
keys = self.factory.getPrivateKeys() | |
diff --git a/twisted/conch/test/test_scripts.py b/twisted/conch/test/test_scripts.py | |
index 7e32b1b..3e21d63 100644 | |
--- a/twisted/conch/test/test_scripts.py | |
+++ b/twisted/conch/test/test_scripts.py | |
@@ -28,7 +28,7 @@ except ImportError: | |
else: | |
try: | |
Tkinter.Tk().destroy() | |
- except Tkinter.TclError, e: | |
+ except Tkinter.TclError as e: | |
tkskip = "Can't test Tkinter: " + str(e) | |
else: | |
tkskip = None | |
diff --git a/twisted/conch/unix.py b/twisted/conch/unix.py | |
index 58173a7..3d4b03e 100644 | |
--- a/twisted/conch/unix.py | |
+++ b/twisted/conch/unix.py | |
@@ -464,7 +464,7 @@ class UnixSFTPFile: | |
mode = attrs["permissions"] | |
del attrs["permissions"] | |
else: | |
- mode = 0777 | |
+ mode = 0o777 | |
fd = server.avatar._runAsUser(os.open, filename, openFlags, mode) | |
if attrs: | |
server.avatar._runAsUser(server._setAttrs, filename, attrs) | |
diff --git a/twisted/internet/_dumbwin32proc.py b/twisted/internet/_dumbwin32proc.py | |
index ae388ec..1718f77 100644 | |
--- a/twisted/internet/_dumbwin32proc.py | |
+++ b/twisted/internet/_dumbwin32proc.py | |
@@ -6,6 +6,8 @@ | |
http://isometri.cc/strips/gates_in_the_head | |
""" | |
+from __future__ import print_function | |
+ | |
import os | |
# Win32 imports | |
@@ -35,7 +37,7 @@ from twisted.internet._baseprocess import BaseProcess | |
def debug(msg): | |
import sys | |
- print msg | |
+ print(msg) | |
sys.stdout.flush() | |
class _Reaper(_pollingfile._PollableResource): | |
@@ -177,7 +179,7 @@ class Process(_pollingfile._PollingTimer, BaseProcess): | |
try: | |
try: | |
doCreate() | |
- except TypeError, e: | |
+ except TypeError as e: | |
# win32process.CreateProcess cannot deal with mixed | |
# str/unicode environment, so we make it all Unicode | |
if e.args != ('All dictionary items must be strings, or ' | |
@@ -188,7 +190,7 @@ class Process(_pollingfile._PollingTimer, BaseProcess): | |
newenv[unicode(key)] = unicode(value) | |
env = newenv | |
doCreate() | |
- except pywintypes.error, pwte: | |
+ except pywintypes.error as pwte: | |
if not _invalidWin32App(pwte): | |
# This behavior isn't _really_ documented, but let's make it | |
# consistent with the behavior that is documented. | |
@@ -210,7 +212,7 @@ class Process(_pollingfile._PollingTimer, BaseProcess): | |
try: | |
# Let's try again. | |
doCreate() | |
- except pywintypes.error, pwte2: | |
+ except pywintypes.error as pwte2: | |
# d'oh, failed again! | |
if _invalidWin32App(pwte2): | |
raise OSError( | |
diff --git a/twisted/internet/_threadedselect.py b/twisted/internet/_threadedselect.py | |
index 1584259..03fd3d9 100644 | |
--- a/twisted/internet/_threadedselect.py | |
+++ b/twisted/internet/_threadedselect.py | |
@@ -164,7 +164,7 @@ class ThreadedSelectReactor(posixbase.PosixReactorBase): | |
# result) was passed | |
log.err() | |
self._preenDescriptorsInThread() | |
- except (select.error, IOError), se: | |
+ except (select.error, IOError) as se: | |
# select(2) encountered an error | |
if se.args[0] in (0, 2): | |
# windows does this if it got an empty list | |
diff --git a/twisted/internet/cfreactor.py b/twisted/internet/cfreactor.py | |
index ef6bf7d..a5aab77 100644 | |
--- a/twisted/internet/cfreactor.py | |
+++ b/twisted/internet/cfreactor.py | |
@@ -17,7 +17,7 @@ __all__ = [ | |
import sys | |
-from zope.interface import implements | |
+from zope.interface import implementer | |
from twisted.internet.interfaces import IReactorFDSet | |
from twisted.internet.posixbase import PosixReactorBase, _Waker | |
@@ -72,6 +72,7 @@ class _WakerPlus(_Waker): | |
+@implementer(IReactorFDSet) | |
class CFReactor(PosixReactorBase): | |
""" | |
The CoreFoundation reactor. | |
@@ -110,8 +111,6 @@ class CFReactor(PosixReactorBase): | |
Otherwise, it is C{None} | |
""" | |
- implements(IReactorFDSet) | |
- | |
def __init__(self, runLoop=None, runner=None): | |
self._fdmap = {} | |
self._idmap = {} | |
@@ -497,5 +496,3 @@ def install(runLoop=None, runner=None): | |
from twisted.internet.main import installReactor | |
installReactor(reactor) | |
return reactor | |
- | |
- | |
diff --git a/twisted/internet/inotify.py b/twisted/internet/inotify.py | |
index 85305dc..0dd6f52 100644 | |
--- a/twisted/internet/inotify.py | |
+++ b/twisted/internet/inotify.py | |
@@ -39,21 +39,21 @@ from twisted.python import log, _inotify | |
# from /usr/src/linux/include/linux/inotify.h | |
-IN_ACCESS = 0x00000001L # File was accessed | |
-IN_MODIFY = 0x00000002L # File was modified | |
-IN_ATTRIB = 0x00000004L # Metadata changed | |
-IN_CLOSE_WRITE = 0x00000008L # Writeable file was closed | |
-IN_CLOSE_NOWRITE = 0x00000010L # Unwriteable file closed | |
-IN_OPEN = 0x00000020L # File was opened | |
-IN_MOVED_FROM = 0x00000040L # File was moved from X | |
-IN_MOVED_TO = 0x00000080L # File was moved to Y | |
-IN_CREATE = 0x00000100L # Subfile was created | |
-IN_DELETE = 0x00000200L # Subfile was delete | |
-IN_DELETE_SELF = 0x00000400L # Self was deleted | |
-IN_MOVE_SELF = 0x00000800L # Self was moved | |
-IN_UNMOUNT = 0x00002000L # Backing fs was unmounted | |
-IN_Q_OVERFLOW = 0x00004000L # Event queued overflowed | |
-IN_IGNORED = 0x00008000L # File was ignored | |
+IN_ACCESS = 0x00000001 # File was accessed | |
+IN_MODIFY = 0x00000002 # File was modified | |
+IN_ATTRIB = 0x00000004 # Metadata changed | |
+IN_CLOSE_WRITE = 0x00000008 # Writeable file was closed | |
+IN_CLOSE_NOWRITE = 0x00000010 # Unwriteable file closed | |
+IN_OPEN = 0x00000020 # File was opened | |
+IN_MOVED_FROM = 0x00000040 # File was moved from X | |
+IN_MOVED_TO = 0x00000080 # File was moved to Y | |
+IN_CREATE = 0x00000100 # Subfile was created | |
+IN_DELETE = 0x00000200 # Subfile was delete | |
+IN_DELETE_SELF = 0x00000400 # Self was deleted | |
+IN_MOVE_SELF = 0x00000800 # Self was moved | |
+IN_UNMOUNT = 0x00002000 # Backing fs was unmounted | |
+IN_Q_OVERFLOW = 0x00004000 # Event queued overflowed | |
+IN_IGNORED = 0x00008000 # File was ignored | |
IN_ONLYDIR = 0x01000000 # only watch the path if it is a directory | |
IN_DONT_FOLLOW = 0x02000000 # don't follow a sym link | |
@@ -218,7 +218,7 @@ class INotify(FileDescriptor, object): | |
if self._fd >= 0: | |
try: | |
os.close(self._fd) | |
- except OSError, e: | |
+ except OSError as e: | |
log.err(e, "Couldn't close INotify file descriptor.") | |
diff --git a/twisted/internet/iocpreactor/tcp.py b/twisted/internet/iocpreactor/tcp.py | |
index 00f6b93..99bc79d 100644 | |
--- a/twisted/internet/iocpreactor/tcp.py | |
+++ b/twisted/internet/iocpreactor/tcp.py | |
@@ -439,8 +439,8 @@ class Port(_SocketCloser, _LogOwner): | |
else: | |
addr = (self.interface, self.port) | |
skt.bind(addr) | |
- except socket.error, le: | |
- raise error.CannotListenError, (self.interface, self.port, le) | |
+ except socket.error as le: | |
+ raise error.CannotListenError(self.interface, self.port, le) | |
self.addrLen = _iocp.maxAddrLen(skt.fileno()) | |
diff --git a/twisted/internet/iocpreactor/udp.py b/twisted/internet/iocpreactor/udp.py | |
index 2cadb10..e4d3771 100644 | |
--- a/twisted/internet/iocpreactor/udp.py | |
+++ b/twisted/internet/iocpreactor/udp.py | |
@@ -109,7 +109,7 @@ class Port(abstract.FileHandle): | |
try: | |
skt = self.createSocket() | |
skt.bind((self.interface, self.port)) | |
- except socket.error, le: | |
+ except socket.error as le: | |
raise error.CannotListenError(self.interface, self.port, le) | |
# Make sure that if we listened on port 0, we update that to | |
@@ -176,7 +176,7 @@ class Port(abstract.FileHandle): | |
assert addr in (None, self._connectedAddr) | |
try: | |
return self.socket.send(datagram) | |
- except socket.error, se: | |
+ except socket.error as se: | |
no = se.args[0] | |
if no == errno.WSAEINTR: | |
return self.write(datagram) | |
@@ -202,7 +202,7 @@ class Port(abstract.FileHandle): | |
addr[0], "IPv4 port write() called with IPv6 address") | |
try: | |
return self.socket.sendto(datagram, addr) | |
- except socket.error, se: | |
+ except socket.error as se: | |
no = se.args[0] | |
if no == errno.WSAEINTR: | |
return self.write(datagram, addr) | |
@@ -394,7 +394,7 @@ class MulticastMixin: | |
cmd = socket.IP_DROP_MEMBERSHIP | |
try: | |
self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface) | |
- except socket.error, e: | |
+ except socket.error as e: | |
return failure.Failure(error.MulticastJoinError(addr, interface, | |
*e.args)) | |
diff --git a/twisted/internet/test/test_iocp.py b/twisted/internet/test/test_iocp.py | |
index 711da2f..d8824fe 100644 | |
--- a/twisted/internet/test/test_iocp.py | |
+++ b/twisted/internet/test/test_iocp.py | |
@@ -27,7 +27,7 @@ except ImportError: | |
try: | |
socket(AF_INET6, SOCK_STREAM).close() | |
-except error, e: | |
+except error as e: | |
ipv6Skip = str(e) | |
else: | |
ipv6Skip = None | |
@@ -54,7 +54,8 @@ class SupportTests(unittest.TestCase): | |
client.setblocking(False) | |
try: | |
client.connect((localhost, port.getsockname()[1])) | |
- except error, (errnum, message): | |
+ except error as e: | |
+ (errnum, message) = e | |
self.assertIn(errnum, (errno.EINPROGRESS, errno.EWOULDBLOCK)) | |
server = socket(family, SOCK_STREAM) | |
@@ -147,4 +148,3 @@ class IOCPReactorTests(unittest.TestCase): | |
self.assertEqual(fd.counter, EVENTS_PER_LOOP) | |
ir.doIteration(0) | |
self.assertEqual(fd.counter, EVENTS_PER_LOOP + 1) | |
- | |
diff --git a/twisted/mail/imap4.py b/twisted/mail/imap4.py | |
index 7fba48d..abbe3f9 100644 | |
--- a/twisted/mail/imap4.py | |
+++ b/twisted/mail/imap4.py | |
@@ -599,7 +599,7 @@ class IMAP4Server(basic.LineReceiver, policies.TimeoutMixin): | |
f = getattr(self, 'parse_' + self.parseState) | |
try: | |
f(line) | |
- except Exception, e: | |
+ except Exception as e: | |
self.sendUntaggedResponse('BAD Server error: ' + str(e)) | |
log.err() | |
@@ -621,11 +621,11 @@ class IMAP4Server(basic.LineReceiver, policies.TimeoutMixin): | |
cmd = cmd.upper() | |
try: | |
return self.dispatchCommand(tag, cmd, rest) | |
- except IllegalClientResponse, e: | |
+ except IllegalClientResponse as e: | |
self.sendBadResponse(tag, 'Illegal syntax: ' + str(e)) | |
- except IllegalOperation, e: | |
+ except IllegalOperation as e: | |
self.sendNegativeResponse(tag, 'Illegal operation: ' + str(e)) | |
- except IllegalMailboxEncoding, e: | |
+ except IllegalMailboxEncoding as e: | |
self.sendNegativeResponse(tag, 'Illegal mailbox name: ' + str(e)) | |
def parse_pending(self, line): | |
diff --git a/twisted/mail/maildir.py b/twisted/mail/maildir.py | |
index b7ea648..2a3c2f3 100644 | |
--- a/twisted/mail/maildir.py | |
+++ b/twisted/mail/maildir.py | |
@@ -97,11 +97,11 @@ def initializeMaildir(dir): | |
@param dir: The path name for a user directory. | |
""" | |
if not os.path.isdir(dir): | |
- os.mkdir(dir, 0700) | |
+ os.mkdir(dir, 0o700) | |
for subdir in ['new', 'cur', 'tmp', '.Trash']: | |
- os.mkdir(os.path.join(dir, subdir), 0700) | |
+ os.mkdir(os.path.join(dir, subdir), 0o700) | |
for subdir in ['new', 'cur', 'tmp']: | |
- os.mkdir(os.path.join(dir, '.Trash', subdir), 0700) | |
+ os.mkdir(os.path.join(dir, '.Trash', subdir), 0o700) | |
# touch | |
open(os.path.join(dir, '.Trash', 'maildirfolder'), 'w').close() | |
@@ -459,10 +459,10 @@ class _MaildirMailboxAppendMessageTask: | |
try: | |
self.osrename(self.tmpname, newname) | |
break | |
- except OSError, (err, estr): | |
+ except OSError as e: | |
import errno | |
# if the newname exists, retry with a new newname. | |
- if err != errno.EEXIST: | |
+ if e.errno != errno.EEXIST: | |
self.fail() | |
newname = None | |
break | |
@@ -484,7 +484,7 @@ class _MaildirMailboxAppendMessageTask: | |
while True: | |
self.tmpname = os.path.join(self.mbox.path, "tmp", _generateMaildirName()) | |
try: | |
- self.fh = self.osopen(self.tmpname, attr, 0600) | |
+ self.fh = self.osopen(self.tmpname, attr, 0o600) | |
return None | |
except OSError: | |
tries += 1 | |
@@ -626,10 +626,10 @@ class MaildirMailbox(pop3.Mailbox): | |
for (real, trash) in self.deleted.items(): | |
try: | |
os.rename(trash, real) | |
- except OSError, (err, estr): | |
+ except OSError as e: | |
import errno | |
# If the file has been deleted from disk, oh well! | |
- if err != errno.ENOENT: | |
+ if e.errno != errno.ENOENT: | |
raise | |
# This is a pass | |
else: | |
diff --git a/twisted/mail/pop3.py b/twisted/mail/pop3.py | |
index 933dd6c..7958ed2 100644 | |
--- a/twisted/mail/pop3.py | |
+++ b/twisted/mail/pop3.py | |
@@ -574,7 +574,7 @@ class POP3(basic.LineOnlyReceiver, policies.TimeoutMixin): | |
""" | |
try: | |
return self.processCommand(*line.split(' ')) | |
- except (ValueError, AttributeError, POP3Error, TypeError), e: | |
+ except (ValueError, AttributeError, POP3Error, TypeError) as e: | |
log.err() | |
self.failResponse('bad protocol or server: %s: %s' % (e.__class__.__name__, e)) | |
diff --git a/twisted/mail/protocols.py b/twisted/mail/protocols.py | |
index b4dbfad..5bb91fa 100644 | |
--- a/twisted/mail/protocols.py | |
+++ b/twisted/mail/protocols.py | |
@@ -21,10 +21,11 @@ from twisted.cred.error import UnauthorizedLogin | |
from twisted.mail import relay | |
-from zope.interface import implements | |
+from zope.interface import implementer | |
+@implementer(smtp.IMessageDelivery) | |
class DomainDeliveryBase: | |
""" | |
A base class for message delivery using the domains of a mail service. | |
@@ -37,7 +38,6 @@ class DomainDeliveryBase: | |
@ivar protocolName: The protocol being used to deliver the mail. | |
Sub-classes should set this appropriately. | |
""" | |
- implements(smtp.IMessageDelivery) | |
service = None | |
protocolName = None | |
diff --git a/twisted/mail/scripts/mailmail.py b/twisted/mail/scripts/mailmail.py | |
index 98e27cb..ee1c415 100644 | |
--- a/twisted/mail/scripts/mailmail.py | |
+++ b/twisted/mail/scripts/mailmail.py | |
@@ -6,6 +6,8 @@ | |
Implementation module for the I{mailmail} command. | |
""" | |
+from __future__ import print_function | |
+ | |
import os | |
import sys | |
import rfc822 | |
@@ -70,7 +72,7 @@ def parseOptions(argv): | |
# Add a non-standard option for querying the version of this tool. | |
if '--version' in argv: | |
- print 'mailmail version:', version | |
+ print('mailmail version:', version) | |
raise SystemExit() | |
# -bp lists queue information. Screw that. | |
diff --git a/twisted/mail/smtp.py b/twisted/mail/smtp.py | |
index edb38c1..f12b88f 100644 | |
--- a/twisted/mail/smtp.py | |
+++ b/twisted/mail/smtp.py | |
@@ -11,7 +11,7 @@ import binascii | |
import warnings | |
from email.base64MIME import encode as encode_base64 | |
-from zope.interface import implements, Interface | |
+from zope.interface import implementer, Interface | |
from twisted.copyright import longversion | |
from twisted.protocols import basic | |
@@ -318,7 +318,7 @@ def messageid(uniq=None, N=idGenerator().next): | |
""" | |
datetime = time.strftime('%Y%m%d%H%M%S', time.gmtime()) | |
pid = os.getpid() | |
- rand = random.randrange(2**31L-1) | |
+ rand = random.randrange(2**31-1) | |
if uniq is None: | |
uniq = '' | |
else: | |
@@ -389,7 +389,7 @@ class Address: | |
while atl: | |
if atl[0] == '<': | |
if atl[-1] != '>': | |
- raise AddressError, "Unbalanced <>" | |
+ raise AddressError("Unbalanced <>") | |
atl = atl[1:-1] | |
elif atl[0] == '@': | |
atl = atl[1:] | |
@@ -399,15 +399,15 @@ class Address: | |
# remove it | |
atl = atl[1:] | |
if not atl: | |
- raise AddressError, "Malformed source route" | |
+ raise AddressError("Malformed source route") | |
atl = atl[1:] # remove : | |
elif domain: | |
- raise AddressError, "Too many @" | |
+ raise AddressError("Too many @") | |
else: | |
# Now in domain | |
domain = [''] | |
elif len(atl[0]) == 1 and not self.atomre.match(atl[0]) and atl[0] != '.': | |
- raise AddressError, "Parse error at %r of %r" % (atl[0], (addr, atl)) | |
+ raise AddressError("Parse error at %r of %r" % (atl[0], (addr, atl))) | |
else: | |
if not domain: | |
local.append(atl[0]) | |
@@ -642,7 +642,7 @@ class SMTP(basic.LineOnlyReceiver, policies.TimeoutMixin): | |
try: | |
addr = Address(m.group('path'), self.host) | |
- except AddressError, e: | |
+ except AddressError as e: | |
self.sendCode(553, str(e)) | |
return | |
@@ -680,7 +680,7 @@ class SMTP(basic.LineOnlyReceiver, policies.TimeoutMixin): | |
try: | |
user = User(m.group('path'), self._helo, self, self._from) | |
- except AddressError, e: | |
+ except AddressError as e: | |
self.sendCode(553, str(e)) | |
return | |
@@ -735,7 +735,7 @@ class SMTP(basic.LineOnlyReceiver, policies.TimeoutMixin): | |
if rcvdhdr: | |
msg.lineReceived(rcvdhdr) | |
msgs.append(msg) | |
- except SMTPServerError, e: | |
+ except SMTPServerError as e: | |
self.sendCode(e.code, e.resp) | |
self.mode = COMMAND | |
self._disconnect(msgs) | |
@@ -819,7 +819,7 @@ class SMTP(basic.LineOnlyReceiver, policies.TimeoutMixin): | |
for message in self.__messages: | |
message.lineReceived(line) | |
- except SMTPServerError, e: | |
+ except SMTPServerError as e: | |
self.datafailed = e | |
for message in self.__messages: | |
message.connectionLost() | |
@@ -1987,9 +1987,8 @@ class LOGINCredentials(_lcredentials): | |
+@implementer(IClientAuthentication) | |
class PLAINAuthenticator: | |
- implements(IClientAuthentication) | |
- | |
def __init__(self, user): | |
self.user = user | |
diff --git a/twisted/mail/test/pop3testserver.py b/twisted/mail/test/pop3testserver.py | |
index fd85821..2a1aaf0 100644 | |
--- a/twisted/mail/test/pop3testserver.py | |
+++ b/twisted/mail/test/pop3testserver.py | |
@@ -4,6 +4,8 @@ | |
# Copyright (c) Twisted Matrix Laboratories. | |
# See LICENSE for details. | |
+from __future__ import print_function | |
+ | |
from twisted.internet.protocol import Factory | |
from twisted.protocols import basic | |
from twisted.internet import reactor | |
@@ -39,7 +41,7 @@ CAPABILITIES = [ | |
CAPABILITIES_SSL = "STLS" | |
CAPABILITIES_UIDL = "UIDL" | |
- | |
+ | |
INVALID_RESPONSE = "-ERR Unknown request" | |
VALID_RESPONSE = "+OK Command Completed" | |
AUTH_DECLINED = "-ERR LOGIN failed" | |
@@ -227,7 +229,7 @@ slow - Wait 20 seconds after the connection is made to return a Server Greeting | |
""" | |
def printMessage(msg): | |
- print "Server Starting in %s mode" % msg | |
+ print("Server Starting in %s mode" % msg) | |
def processArg(arg): | |
@@ -288,11 +290,11 @@ def processArg(arg): | |
printMessage("Slow Greeting") | |
elif arg.lower() == '--help': | |
- print usage | |
+ print(usage) | |
sys.exit() | |
else: | |
- print usage | |
+ print(usage) | |
sys.exit() | |
def main(): | |
diff --git a/twisted/mail/test/test_mail.py b/twisted/mail/test/test_mail.py | |
index 994ef01..684478f 100644 | |
--- a/twisted/mail/test/test_mail.py | |
+++ b/twisted/mail/test/test_mail.py | |
@@ -1986,7 +1986,7 @@ rm -f process.alias.out | |
while read i; do | |
echo $i >> process.alias.out | |
done""") | |
- os.chmod(sh.path, 0700) | |
+ os.chmod(sh.path, 0o700) | |
a = mail.alias.ProcessAlias(sh.path, None, None) | |
m = a.createMessageReceiver() | |
diff --git a/twisted/mail/test/test_pop3.py b/twisted/mail/test/test_pop3.py | |
index 0cbcd16..2014dea 100644 | |
--- a/twisted/mail/test/test_pop3.py | |
+++ b/twisted/mail/test/test_pop3.py | |
@@ -5,6 +5,8 @@ | |
Test cases for Ltwisted.mail.pop3} module. | |
""" | |
+from __future__ import print_function | |
+ | |
import StringIO | |
import hmac | |
import base64 | |
@@ -191,8 +193,8 @@ class MyPOP3Downloader(pop3.POP3Client): | |
parts = line.split() | |
code = parts[0] | |
if code != '+OK': | |
- print parts | |
- raise AssertionError, 'code is ' + code | |
+ print(parts) | |
+ raise AssertionError('code is ' + code) | |
self.lines = [] | |
self.retr(1) | |
@@ -205,7 +207,7 @@ class MyPOP3Downloader(pop3.POP3Client): | |
def handle_QUIT(self, line): | |
if line[:3] != '+OK': | |
- raise AssertionError, 'code is ' + line | |
+ raise AssertionError('code is ' + line) | |
class POP3Tests(unittest.TestCase): | |
diff --git a/twisted/mail/test/test_smtp.py b/twisted/mail/test/test_smtp.py | |
index 31b9bd4..2379999 100644 | |
--- a/twisted/mail/test/test_smtp.py | |
+++ b/twisted/mail/test/test_smtp.py | |
@@ -496,7 +496,7 @@ To: foo | |
data = transport.value() | |
transport.clear() | |
if not re.match(expect, data): | |
- raise AssertionError, (send, expect, data) | |
+ raise AssertionError(send, expect, data) | |
if data[:3] == '354': | |
for line in msg.splitlines(): | |
if line and line[0] == '.': | |
@@ -509,7 +509,7 @@ To: foo | |
transport.clear() | |
resp, msgdata = msgexpect | |
if not re.match(resp, data): | |
- raise AssertionError, (resp, data) | |
+ raise AssertionError(resp, data) | |
for recip in msgdata[2]: | |
expected = list(msgdata[:]) | |
expected[2] = [recip] | |
diff --git a/twisted/manhole/_inspectro.py b/twisted/manhole/_inspectro.py | |
index fc9a305..23e1697 100644 | |
--- a/twisted/manhole/_inspectro.py | |
+++ b/twisted/manhole/_inspectro.py | |
@@ -5,6 +5,8 @@ | |
"""An input/output window for the glade reactor inspector. | |
""" | |
+from __future__ import print_function | |
+ | |
import time | |
import gtk | |
import gobject | |
@@ -231,14 +233,14 @@ class Inspectro: | |
def do(self, command): | |
filename = '<inspector>' | |
try: | |
- print repr(command) | |
+ print(repr(command)) | |
try: | |
code = compile(command, filename, 'eval') | |
except: | |
code = compile(command, filename, 'single') | |
val = eval(code, self.ns, self.ns) | |
if val is not None: | |
- print repr(val) | |
+ print(repr(val)) | |
self.ns['_'] = val | |
except: | |
log.err() | |
@@ -258,7 +260,7 @@ class LoggingProtocol(policies.ProtocolWrapper): | |
logging = True | |
logViewer = None | |
- | |
+ | |
def __init__(self, *args): | |
policies.ProtocolWrapper.__init__(self, *args) | |
self.inLog = [] | |
@@ -290,9 +292,9 @@ class LoggingFactory(policies.WrappingFactory): | |
protocol = LoggingProtocol | |
logging = True | |
- | |
+ | |
def buildProtocol(self, addr): | |
- p = self.protocol(self, self.wrappedFactory.buildProtocol(addr)) | |
+ p = self.protocol(self, self.wrappedFactory.buildProtocol(addr)) | |
p.logging = self.logging | |
return p | |
@@ -305,7 +307,7 @@ class LoggingFactory(policies.WrappingFactory): | |
class LogViewer: | |
"""Display log of network traffic.""" | |
- | |
+ | |
def __init__(self, p): | |
self.p = p | |
vals = [time.time()] | |
@@ -345,7 +347,7 @@ class LogViewer: | |
r.sort() | |
for i in r: | |
self.model.append(i) | |
- | |
+ | |
def updateIn(self, (time, data)): | |
self.model.append((str(time - self.startTime), "R", repr(data)[1:-1])) | |
@@ -366,4 +368,3 @@ if __name__ == '__main__': | |
import sys | |
log.startLogging(sys.stdout) | |
main() | |
- | |
diff --git a/twisted/manhole/explorer.py b/twisted/manhole/explorer.py | |
index b52693c..fc239aa 100644 | |
--- a/twisted/manhole/explorer.py | |
+++ b/twisted/manhole/explorer.py | |
@@ -23,9 +23,6 @@ from twisted.spread import pb | |
from twisted.python import reflect | |
-True=(1==1) | |
-False=not True | |
- | |
class Pool(UserDict.UserDict): | |
def getExplorer(self, object, identifier): | |
oid = id(object) | |
@@ -537,7 +534,7 @@ class CRUFT_WatchyThingie: | |
objects which are members of this one. | |
""" | |
if type(object) is not types.InstanceType: | |
- raise TypeError, "Sorry, can only place a watch on Instances." | |
+ raise TypeError("Sorry, can only place a watch on Instances.") | |
# uninstallers = [] | |
diff --git a/twisted/manhole/gladereactor.py b/twisted/manhole/gladereactor.py | |
index 6fc7cfd..e0982e0 100644 | |
--- a/twisted/manhole/gladereactor.py | |
+++ b/twisted/manhole/gladereactor.py | |
@@ -31,7 +31,7 @@ class GladeReactor(sup): | |
from _inspectro import LoggingFactory | |
factory = LoggingFactory(factory) | |
return sup.listenTCP(self, port, factory, backlog, interface) | |
- | |
+ | |
def connectTCP(self, host, port, factory, timeout=30, bindAddress=None): | |
from _inspectro import LoggingFactory | |
factory = LoggingFactory(factory) | |
@@ -52,7 +52,7 @@ class GladeReactor(sup): | |
factory = LoggingFactory(factory) | |
return sup.connectUNIX(self, address, factory, timeout) | |
- def listenUNIX(self, address, factory, backlog=50, mode=0666): | |
+ def listenUNIX(self, address, factory, backlog=50, mode=0o666): | |
from _inspectro import LoggingFactory | |
factory = LoggingFactory(factory) | |
return sup.listenUNIX(self, address, factory, backlog, mode) | |
@@ -67,7 +67,7 @@ class GladeReactor(sup): | |
from _inspectro import LogViewer | |
if hasattr(data, "protocol") and not data.protocol.logViewer: | |
LogViewer(data.protocol) | |
- | |
+ | |
def on_inspect_clicked(self, w): | |
store, iter = self.servers.get_selection().get_selected() | |
data = store[iter] | |
@@ -105,7 +105,7 @@ class GladeReactor(sup): | |
self.xml.get_widget('disconnect').set_sensitive(0) | |
else: | |
data = store[iter] | |
- self.toggle_suspend(not | |
+ self.toggle_suspend(not | |
data[COLUMN_DESCRIPTION].endswith('(suspended)')) | |
self.xml.get_widget("suspend").set_sensitive(1) | |
self.xml.get_widget('disconnect').set_sensitive(1) | |
@@ -147,7 +147,7 @@ class GladeReactor(sup): | |
gtk.TreeViewColumn('Writing', | |
gtk.CellRendererToggle(), | |
active=3)]: | |
- | |
+ | |
self.servers.append_column(col) | |
col.set_resizable(1) | |
sup.__init__(self) | |
@@ -177,7 +177,7 @@ class GladeReactor(sup): | |
x[3] += write | |
x[2] = max(x[2],0) | |
x[3] = max(x[3],0) | |
- | |
+ | |
if not (x[2] or x[3]): | |
x[0] = x[0] + '(disconnected)' | |
self.callLater(5, self._goAway, reader) | |
diff --git a/twisted/manhole/ui/gtk2manhole.py b/twisted/manhole/ui/gtk2manhole.py | |
index 9985980..8ae8933 100644 | |
--- a/twisted/manhole/ui/gtk2manhole.py | |
+++ b/twisted/manhole/ui/gtk2manhole.py | |
@@ -6,6 +6,8 @@ | |
Manhole client with a GTK v2.x front-end. | |
""" | |
+from __future__ import print_function | |
+ | |
__version__ = '$Revision: 1.9 $'[11:-2] | |
from twisted import copyright | |
@@ -233,7 +235,7 @@ class ConsoleInput: | |
self, 'key_%s' % ksym, lambda *a, **kw: None)(entry, event) | |
if self.__debug: | |
- print ksym | |
+ print(ksym) | |
return rvalue | |
def getText(self): | |
@@ -250,7 +252,7 @@ class ConsoleInput: | |
# Figure out if that Return meant "next line" or "execute." | |
try: | |
c = code.compile_command(text) | |
- except SyntaxError, e: | |
+ except SyntaxError as e: | |
# This could conceivably piss you off if the client's python | |
# doesn't accept keywords that are known to the manhole's | |
# python. | |
@@ -258,7 +260,7 @@ class ConsoleInput: | |
buffer.place(point) | |
# TODO: Componentize! | |
self.toplevel.output.append(str(e), "exception") | |
- except (OverflowError, ValueError), e: | |
+ except (OverflowError, ValueError) as e: | |
self.toplevel.output.append(str(e), "exception") | |
else: | |
if c is not None: | |
diff --git a/twisted/names/srvconnect.py b/twisted/names/srvconnect.py | |
index cf10b0d..2fac6dd 100644 | |
--- a/twisted/names/srvconnect.py | |
+++ b/twisted/names/srvconnect.py | |
@@ -4,7 +4,7 @@ | |
from functools import reduce | |
-from zope.interface import implements | |
+from zope.interface import implementer | |
from twisted.internet import error, interfaces | |
from twisted.names import client, dns | |
@@ -31,11 +31,10 @@ class _SRVConnector_ClientFactoryWrapper: | |
+@implementer(interfaces.IConnector) | |
class SRVConnector: | |
"""A connector that looks up DNS SRV records. See RFC2782.""" | |
- implements(interfaces.IConnector) | |
- | |
stopAfterDNS=0 | |
def __init__(self, reactor, service, domain, factory, | |
@@ -103,7 +102,8 @@ class SRVConnector: | |
self.servers = [] | |
self.orderedServers = [] | |
- def _cbGotServers(self, (answers, auth, add)): | |
+ def _cbGotServers(self, response): | |
+ (answers, auth, add) = response | |
if len(answers) == 1 and answers[0].type == dns.SRV \ | |
and answers[0].payload \ | |
and answers[0].payload.target == dns.Name('.'): | |
@@ -172,7 +172,7 @@ class SRVConnector: | |
p, w, host, port = chosen | |
return host, port | |
- raise RuntimeError, 'Impossible %s pickServer result.' % self.__class__.__name__ | |
+ raise RuntimeError('Impossible %s pickServer result.' % self.__class__.__name__) | |
def _reallyConnect(self): | |
if self.stopAfterDNS: | |
diff --git a/twisted/news/news.py b/twisted/news/news.py | |
index 3eae700..e56a02f 100644 | |
--- a/twisted/news/news.py | |
+++ b/twisted/news/news.py | |
@@ -6,6 +6,8 @@ | |
Maintainer: Jp Calderone | |
""" | |
+from __future__ import print_function | |
+ | |
from twisted.news import nntp | |
from twisted.internet import protocol, reactor | |
@@ -13,12 +15,12 @@ import time | |
class NNTPFactory(protocol.ServerFactory): | |
"""A factory for NNTP server protocols.""" | |
- | |
+ | |
protocol = nntp.NNTPServer | |
- | |
+ | |
def __init__(self, backend): | |
self.backend = backend | |
- | |
+ | |
def buildProtocol(self, connection): | |
p = self.protocol() | |
p.factory = self | |
@@ -37,9 +39,9 @@ class UsenetClientFactory(protocol.ClientFactory): | |
def clientConnectionFailed(self, connector, reason): | |
- print 'Connection failed: ', reason | |
- | |
- | |
+ print('Connection failed: ', reason) | |
+ | |
+ | |
def updateChecks(self, addr): | |
self.lastChecks[addr] = time.mktime(time.gmtime()) | |
diff --git a/twisted/news/tap.py b/twisted/news/tap.py | |
index a4cf542..aadb3c1 100644 | |
--- a/twisted/news/tap.py | |
+++ b/twisted/news/tap.py | |
@@ -1,6 +1,7 @@ | |
# Copyright (c) Twisted Matrix Laboratories. | |
# See LICENSE for details. | |
+from __future__ import print_function | |
from twisted.news import news, database | |
from twisted.application import strports | |
@@ -18,7 +19,7 @@ class DBOptions(usage.Options): | |
["groups", "g", "groups.list", "File containing group list"], | |
["servers", "s", "servers.list", "File containing server list"] | |
] | |
- | |
+ | |
def postOptions(self): | |
# XXX - Hmmm. | |
self['groups'] = [g.strip() for g in open(self['groups']).readlines() if not g.startswith('#')] | |
@@ -28,7 +29,7 @@ class DBOptions(usage.Options): | |
__import__(self['module']) | |
except ImportError: | |
log.msg("Warning: Cannot import %s" % (self['module'],)) | |
- | |
+ | |
f = open(self['schema'], 'w') | |
f.write( | |
database.NewsStorageAugmentation.schema + '\n' + | |
@@ -36,7 +37,7 @@ class DBOptions(usage.Options): | |
database.makeOverviewSQL() | |
) | |
f.close() | |
- | |
+ | |
info = { | |
'host': self['dbhost'], 'user': self['dbuser'], | |
'database': self['database'], 'dbapiName': self['module'] | |
@@ -54,7 +55,7 @@ class PickleOptions(usage.Options): | |
["moderators", "m", "moderators.list", | |
"File containing moderators list"], | |
] | |
- | |
+ | |
subCommands = None | |
def postOptions(self): | |
@@ -73,7 +74,7 @@ class PickleOptions(usage.Options): | |
class Options(usage.Options): | |
synopsis = "[options]" | |
- | |
+ | |
groups = None | |
servers = None | |
subscriptions = None | |
@@ -120,7 +121,7 @@ class Options(usage.Options): | |
def makeService(config): | |
if not len(config.groups): | |
raise usage.UsageError("No newsgroups specified") | |
- | |
+ | |
db = database.NewsShelf(config['mailhost'], config['datadir']) | |
for (g, m) in config.groups: | |
if m: | |
@@ -129,7 +130,7 @@ def makeService(config): | |
else: | |
db.addGroup(g, 'y') | |
for s in config.subscriptions: | |
- print s | |
+ print(s) | |
db.addSubscription(s) | |
s = config['port'] | |
if config['interface']: | |
diff --git a/twisted/pair/ethernet.py b/twisted/pair/ethernet.py | |
index b432c6f..dc7f6d7 100644 | |
--- a/twisted/pair/ethernet.py | |
+++ b/twisted/pair/ethernet.py | |
@@ -32,16 +32,16 @@ class EthernetHeader: | |
class EthernetProtocol(protocol.AbstractDatagramProtocol): | |
implements(IEthernetProtocol) | |
- | |
+ | |
def __init__(self): | |
self.etherProtos = {} | |
def addProto(self, num, proto): | |
proto = raw.IRawPacketProtocol(proto) | |
if num < 0: | |
- raise TypeError, 'Added protocol must be positive or zero' | |
+ raise TypeError('Added protocol must be positive or zero') | |
if num >= 2**16: | |
- raise TypeError, 'Added protocol must fit in 16 bits' | |
+ raise TypeError('Added protocol must fit in 16 bits') | |
if num not in self.etherProtos: | |
self.etherProtos[num] = [] | |
self.etherProtos[num].append(proto) | |
diff --git a/twisted/pair/ip.py b/twisted/pair/ip.py | |
index de03bd4..0f37ed9 100644 | |
--- a/twisted/pair/ip.py | |
+++ b/twisted/pair/ip.py | |
@@ -29,7 +29,7 @@ class IPHeader: | |
self.dont_fragment = (frag_off & 0x4000 != 0) | |
self.more_fragments = (frag_off & 0x2000 != 0) | |
-MAX_SIZE = 2L**32 | |
+MAX_SIZE = 2**32 | |
class IPProtocol(protocol.AbstractDatagramProtocol): | |
implements(raw.IRawPacketProtocol) | |
@@ -40,9 +40,9 @@ class IPProtocol(protocol.AbstractDatagramProtocol): | |
def addProto(self, num, proto): | |
proto = raw.IRawDatagramProtocol(proto) | |
if num < 0: | |
- raise TypeError, 'Added protocol must be positive or zero' | |
+ raise TypeError('Added protocol must be positive or zero') | |
if num >= MAX_SIZE: | |
- raise TypeError, 'Added protocol must fit in 32 bits' | |
+ raise TypeError('Added protocol must fit in 32 bits') | |
if num not in self.ipProtos: | |
self.ipProtos[num] = [] | |
self.ipProtos[num].append(proto) | |
diff --git a/twisted/pair/rawudp.py b/twisted/pair/rawudp.py | |
index 1425e6b..f7b7809 100644 | |
--- a/twisted/pair/rawudp.py | |
+++ b/twisted/pair/rawudp.py | |
@@ -25,11 +25,11 @@ class RawUDPProtocol(protocol.AbstractDatagramProtocol): | |
def addProto(self, num, proto): | |
if not isinstance(proto, protocol.DatagramProtocol): | |
- raise TypeError, 'Added protocol must be an instance of DatagramProtocol' | |
+ raise TypeError('Added protocol must be an instance of DatagramProtocol') | |
if num < 0: | |
- raise TypeError, 'Added protocol must be positive or zero' | |
+ raise TypeError('Added protocol must be positive or zero') | |
if num >= 2**16: | |
- raise TypeError, 'Added protocol must fit in 16 bits' | |
+ raise TypeError('Added protocol must fit in 16 bits') | |
if num not in self.udpProtos: | |
self.udpProtos[num] = [] | |
self.udpProtos[num].append(proto) | |
diff --git a/twisted/pair/test/test_ethernet.py b/twisted/pair/test/test_ethernet.py | |
index 7554d06..5816e58 100644 | |
--- a/twisted/pair/test/test_ethernet.py | |
+++ b/twisted/pair/test/test_ethernet.py | |
@@ -180,7 +180,7 @@ class EthernetTests(unittest.TestCase): | |
except components.CannotAdapt: | |
pass | |
else: | |
- raise AssertionError, 'addProto must raise an exception for bad protocols' | |
+ raise AssertionError('addProto must raise an exception for bad protocols') | |
def testAddingBadProtos_TooSmall(self): | |
@@ -188,13 +188,13 @@ class EthernetTests(unittest.TestCase): | |
e = ethernet.EthernetProtocol() | |
try: | |
e.addProto(-1, MyProtocol([])) | |
- except TypeError, e: | |
+ except TypeError as e: | |
if e.args == ('Added protocol must be positive or zero',): | |
pass | |
else: | |
raise | |
else: | |
- raise AssertionError, 'addProto must raise an exception for bad protocols' | |
+ raise AssertionError('addProto must raise an exception for bad protocols') | |
def testAddingBadProtos_TooBig(self): | |
@@ -202,23 +202,23 @@ class EthernetTests(unittest.TestCase): | |
e = ethernet.EthernetProtocol() | |
try: | |
e.addProto(2**16, MyProtocol([])) | |
- except TypeError, e: | |
+ except TypeError as e: | |
if e.args == ('Added protocol must fit in 16 bits',): | |
pass | |
else: | |
raise | |
else: | |
- raise AssertionError, 'addProto must raise an exception for bad protocols' | |
+ raise AssertionError('addProto must raise an exception for bad protocols') | |
def testAddingBadProtos_TooBig2(self): | |
"""Adding a protocol with a number >=2**16 raises an exception.""" | |
e = ethernet.EthernetProtocol() | |
try: | |
e.addProto(2**16+1, MyProtocol([])) | |
- except TypeError, e: | |
+ except TypeError as e: | |
if e.args == ('Added protocol must fit in 16 bits',): | |
pass | |
else: | |
raise | |
else: | |
- raise AssertionError, 'addProto must raise an exception for bad protocols' | |
+ raise AssertionError('addProto must raise an exception for bad protocols') | |
diff --git a/twisted/pair/test/test_ip.py b/twisted/pair/test/test_ip.py | |
index e7cc444..5fb7b93 100644 | |
--- a/twisted/pair/test/test_ip.py | |
+++ b/twisted/pair/test/test_ip.py | |
@@ -371,7 +371,7 @@ class IPTests(unittest.TestCase): | |
except components.CannotAdapt: | |
pass | |
else: | |
- raise AssertionError, 'addProto must raise an exception for bad protocols' | |
+ raise AssertionError('addProto must raise an exception for bad protocols') | |
def testAddingBadProtos_TooSmall(self): | |
@@ -379,37 +379,37 @@ class IPTests(unittest.TestCase): | |
e = ip.IPProtocol() | |
try: | |
e.addProto(-1, MyProtocol([])) | |
- except TypeError, e: | |
+ except TypeError as e: | |
if e.args == ('Added protocol must be positive or zero',): | |
pass | |
else: | |
raise | |
else: | |
- raise AssertionError, 'addProto must raise an exception for bad protocols' | |
+ raise AssertionError('addProto must raise an exception for bad protocols') | |
def testAddingBadProtos_TooBig(self): | |
"""Adding a protocol with a number >=2**32 raises an exception.""" | |
e = ip.IPProtocol() | |
try: | |
- e.addProto(2L**32, MyProtocol([])) | |
- except TypeError, e: | |
+ e.addProto(2**32, MyProtocol([])) | |
+ except TypeError as e: | |
if e.args == ('Added protocol must fit in 32 bits',): | |
pass | |
else: | |
raise | |
else: | |
- raise AssertionError, 'addProto must raise an exception for bad protocols' | |
+ raise AssertionError('addProto must raise an exception for bad protocols') | |
def testAddingBadProtos_TooBig2(self): | |
"""Adding a protocol with a number >=2**32 raises an exception.""" | |
e = ip.IPProtocol() | |
try: | |
- e.addProto(2L**32+1, MyProtocol([])) | |
- except TypeError, e: | |
+ e.addProto(2**32+1, MyProtocol([])) | |
+ except TypeError as e: | |
if e.args == ('Added protocol must fit in 32 bits',): | |
pass | |
else: | |
raise | |
else: | |
- raise AssertionError, 'addProto must raise an exception for bad protocols' | |
+ raise AssertionError('addProto must raise an exception for bad protocols') | |
diff --git a/twisted/persisted/dirdbm.py b/twisted/persisted/dirdbm.py | |
index 26bbc1b..e762e3a 100644 | |
--- a/twisted/persisted/dirdbm.py | |
+++ b/twisted/persisted/dirdbm.py | |
@@ -39,11 +39,11 @@ except NameError: | |
class DirDBM: | |
"""A directory with a DBM interface. | |
- | |
+ | |
This class presents a hash-like interface to a directory of small, | |
flat files. It can only use strings as keys or values. | |
""" | |
- | |
+ | |
def __init__(self, name): | |
""" | |
@type name: str | |
@@ -70,38 +70,38 @@ class DirDBM: | |
os.remove(f) | |
else: | |
os.rename(f, old) | |
- | |
+ | |
def _encode(self, k): | |
"""Encode a key so it can be used as a filename. | |
""" | |
# NOTE: '_' is NOT in the base64 alphabet! | |
return base64.encodestring(k).replace('\n', '_').replace("/", "-") | |
- | |
+ | |
def _decode(self, k): | |
"""Decode a filename to get the key. | |
""" | |
return base64.decodestring(k.replace('_', '\n').replace("-", "/")) | |
- | |
+ | |
def _readFile(self, path): | |
"""Read in the contents of a file. | |
- | |
+ | |
Override in subclasses to e.g. provide transparently encrypted dirdbm. | |
""" | |
f = _open(path, "rb") | |
s = f.read() | |
f.close() | |
return s | |
- | |
+ | |
def _writeFile(self, path, data): | |
"""Write data to a file. | |
- | |
+ | |
Override in subclasses to e.g. provide transparently encrypted dirdbm. | |
""" | |
f = _open(path, "wb") | |
f.write(data) | |
f.flush() | |
f.close() | |
- | |
+ | |
def __len__(self): | |
""" | |
@return: The number of key/value pairs in this Shelf | |
@@ -115,14 +115,14 @@ class DirDBM: | |
@type k: str | |
@param k: key to set | |
- | |
+ | |
@type v: str | |
@param v: value to associate with C{k} | |
""" | |
assert type(k) == types.StringType, "DirDBM key must be a string" | |
assert type(v) == types.StringType, "DirDBM value must be a string" | |
k = self._encode(k) | |
- | |
+ | |
# we create a new file with extension .new, write the data to it, and | |
# if the write succeeds delete the old file and rename the new one. | |
old = os.path.join(self.dname, k) | |
@@ -143,10 +143,10 @@ class DirDBM: | |
""" | |
C{dirdbm[k]} | |
Get the contents of a file in this directory as a string. | |
- | |
+ | |
@type k: str | |
@param k: key to lookup | |
- | |
+ | |
@return: The value associated with C{k} | |
@raise KeyError: Raised when there is no such key | |
""" | |
@@ -155,16 +155,16 @@ class DirDBM: | |
try: | |
return self._readFile(path) | |
except: | |
- raise KeyError, k | |
+ raise KeyError(k) | |
def __delitem__(self, k): | |
""" | |
C{del dirdbm[foo]} | |
Delete a file in this directory. | |
- | |
+ | |
@type k: str | |
@param k: key to delete | |
- | |
+ | |
@raise KeyError: Raised when there is no such key | |
""" | |
assert type(k) == types.StringType, "DirDBM key must be a string" | |
@@ -202,7 +202,7 @@ class DirDBM: | |
""" | |
@type key: str | |
@param key: The key to test | |
- | |
+ | |
@return: A true value if this dirdbm has the specified key, a faluse | |
value otherwise. | |
""" | |
@@ -214,7 +214,7 @@ class DirDBM: | |
""" | |
@type key: str | |
@param key: The key to lookup | |
- | |
+ | |
@param value: The value to associate with key if key is not already | |
associated with a value. | |
""" | |
@@ -227,9 +227,9 @@ class DirDBM: | |
""" | |
@type key: str | |
@param key: The key to lookup | |
- | |
+ | |
@param default: The value to return if the given key does not exist | |
- | |
+ | |
@return: The value associated with C{key} or C{default} if not | |
C{self.has_key(key)} | |
""" | |
@@ -244,7 +244,7 @@ class DirDBM: | |
@type key: str | |
@param key: The key to test | |
- | |
+ | |
@return: A true value if C{self.has_key(key)}, a false value otherwise. | |
""" | |
assert type(key) == types.StringType, "DirDBM key must be a string" | |
@@ -261,21 +261,21 @@ class DirDBM: | |
""" | |
for key, val in dict.items(): | |
self[key]=val | |
- | |
+ | |
def copyTo(self, path): | |
""" | |
Copy the contents of this dirdbm to the dirdbm at C{path}. | |
- | |
+ | |
@type path: C{str} | |
@param path: The path of the dirdbm to copy to. If a dirdbm | |
exists at the destination path, it is cleared first. | |
- | |
+ | |
@rtype: C{DirDBM} | |
@return: The dirdbm this dirdbm was copied to. | |
""" | |
path = os.path.abspath(path) | |
assert path != self.dname | |
- | |
+ | |
d = self.__class__(path) | |
d.clear() | |
for k in self.keys(): | |
@@ -297,7 +297,7 @@ class DirDBM: | |
def getModificationTime(self, key): | |
""" | |
Returns modification time of an entry. | |
- | |
+ | |
@return: Last modification date (seconds since epoch) of entry C{key} | |
@raise KeyError: Raised when there is no such key | |
""" | |
@@ -306,16 +306,16 @@ class DirDBM: | |
if os.path.isfile(path): | |
return os.path.getmtime(path) | |
else: | |
- raise KeyError, key | |
+ raise KeyError(key) | |
class Shelf(DirDBM): | |
"""A directory with a DBM shelf interface. | |
- | |
+ | |
This class presents a hash-like interface to a directory of small, | |
flat files. Keys must be strings, but values can be any given object. | |
""" | |
- | |
+ | |
def __setitem__(self, k, v): | |
""" | |
C{shelf[foo] = bar} | |
@@ -333,10 +333,10 @@ class Shelf(DirDBM): | |
""" | |
C{dirdbm[foo]} | |
Get and unpickle the contents of a file in this directory. | |
- | |
+ | |
@type k: str | |
@param k: The key to lookup | |
- | |
+ | |
@return: The value associated with the given key | |
@raise KeyError: Raised if the given key does not exist | |
""" | |
@@ -346,7 +346,7 @@ class Shelf(DirDBM): | |
def open(file, flag = None, mode = None): | |
""" | |
This is for 'anydbm' compatibility. | |
- | |
+ | |
@param file: The parameter to pass to the DirDBM constructor. | |
@param flag: ignored | |
diff --git a/twisted/protocols/shoutcast.py b/twisted/protocols/shoutcast.py | |
index 317d5e8..25d89b4 100644 | |
--- a/twisted/protocols/shoutcast.py | |
+++ b/twisted/protocols/shoutcast.py | |
@@ -27,20 +27,20 @@ class ShoutcastClient(http.HTTPClient): | |
self.metaint = None | |
self.metamode = "mp3" | |
self.databuffer = "" | |
- | |
+ | |
def connectionMade(self): | |
self.sendCommand("GET", self.path) | |
self.sendHeader("User-Agent", self.userAgent) | |
self.sendHeader("Icy-MetaData", "1") | |
self.endHeaders() | |
- | |
+ | |
def lineReceived(self, line): | |
# fix shoutcast crappiness | |
if not self.firstLine and line: | |
if len(line.split(": ", 1)) == 1: | |
line = line.replace(":", ": ", 1) | |
http.HTTPClient.lineReceived(self, line) | |
- | |
+ | |
def handleHeader(self, key, value): | |
if key.lower() == 'icy-metaint': | |
self.metaint = int(value) | |
@@ -67,7 +67,7 @@ class ShoutcastClient(http.HTTPClient): | |
self.remaining = ord(self.databuffer[0]) * 16 | |
self.databuffer = self.databuffer[1:] | |
self.metamode = "meta" | |
- | |
+ | |
def handle_mp3(self): | |
if len(self.databuffer) > self.metaint: | |
self.gotMP3Data(self.databuffer[:self.metaint]) | |
@@ -75,7 +75,7 @@ class ShoutcastClient(http.HTTPClient): | |
self.metamode = "length" | |
else: | |
return 1 | |
- | |
+ | |
def handle_meta(self): | |
if len(self.databuffer) >= self.remaining: | |
if self.remaining: | |
@@ -97,15 +97,15 @@ class ShoutcastClient(http.HTTPClient): | |
value = value[1:-1] | |
meta.append((key, value)) | |
return meta | |
- | |
+ | |
def gotMetaData(self, metadata): | |
"""Called with a list of (key, value) pairs of metadata, | |
if metadata is available on the server. | |
Will only be called on non-empty metadata. | |
""" | |
- raise NotImplementedError, "implement in subclass" | |
- | |
+ raise NotImplementedError("implement in subclass") | |
+ | |
def gotMP3Data(self, data): | |
"""Called with chunk of MP3 data.""" | |
- raise NotImplementedError, "implement in subclass" | |
+ raise NotImplementedError("implement in subclass") | |
diff --git a/twisted/protocols/sip.py b/twisted/protocols/sip.py | |
index 8c0e04d..f987ac9 100644 | |
--- a/twisted/protocols/sip.py | |
+++ b/twisted/protocols/sip.py | |
@@ -340,7 +340,7 @@ def parseViaHeader(value): | |
result = {} | |
pname, pversion, transport = protocolinfo.split("/") | |
if pname != "SIP" or pversion != "2.0": | |
- raise ValueError, "wrong protocol or version: %r" % value | |
+ raise ValueError("wrong protocol or version: %r" % value) | |
result["transport"] = transport | |
if ":" in by: | |
host, port = by.split(":") | |
@@ -556,7 +556,7 @@ class Message: | |
def creationFinished(self): | |
if (self.length != None) and (self.length != len(self.body)): | |
- raise ValueError, "wrong body length" | |
+ raise ValueError("wrong body length") | |
self.finished = 1 | |
def toString(self): | |
@@ -655,7 +655,7 @@ class MessagesParser(basic.LineReceiver): | |
self.reset() | |
else: | |
# we have enough data and message wasn't finished? something is wrong | |
- raise RuntimeError, "this should never happen" | |
+ raise RuntimeError("this should never happen") | |
def dataReceived(self, data): | |
try: | |
diff --git a/twisted/python/components.py b/twisted/python/components.py | |
index 8d71ca6..bf1c29e 100644 | |
--- a/twisted/python/components.py | |
+++ b/twisted/python/components.py | |
@@ -9,13 +9,14 @@ Component architecture for Twisted, based on Zope3 components. | |
Using the Zope3 API directly is strongly recommended. Everything | |
you need is in the top-level of the zope.interface package, e.g.:: | |
- from zope.interface import Interface, implements | |
+ from zope.interface import Interface, implementer | |
class IFoo(Interface): | |
pass | |
+ @implementer(IFoo) | |
class Foo: | |
- implements(IFoo) | |
+ pass | |
print IFoo.implementedBy(Foo) # True | |
print IFoo.providedBy(Foo()) # True | |
diff --git a/twisted/python/finalize.py b/twisted/python/finalize.py | |
index 8b99bf6..2b2314f 100644 | |
--- a/twisted/python/finalize.py | |
+++ b/twisted/python/finalize.py | |
@@ -3,6 +3,8 @@ | |
A module for externalized finalizers. | |
""" | |
+from __future__ import print_function | |
+ | |
import weakref | |
garbageKey = 0 | |
@@ -24,7 +26,7 @@ def register(inst): | |
if __name__ == '__main__': | |
def fin(): | |
- print 'I am _so_ dead.' | |
+ print('I am _so_ dead.') | |
class Finalizeable: | |
""" | |
@@ -43,4 +45,4 @@ if __name__ == '__main__': | |
del f | |
import gc | |
gc.collect() | |
- print 'deled' | |
+ print('deled') | |
diff --git a/twisted/python/release.py b/twisted/python/release.py | |
index 2454792..bf9f922 100644 | |
--- a/twisted/python/release.py | |
+++ b/twisted/python/release.py | |
@@ -9,6 +9,8 @@ Don't use this outside of Twisted. | |
Maintainer: Christopher Armstrong | |
""" | |
+from __future__ import print_function | |
+ | |
import os | |
@@ -43,7 +45,7 @@ def sh(command, null=True, prompt=False): | |
ask before running it. If the command returns something other | |
than 0, I'll raise C{CommandFailed(command)}. | |
""" | |
- print "--$", command | |
+ print("--$", command) | |
if prompt: | |
if raw_input("run ?? ").startswith('n'): | |
diff --git a/twisted/python/shortcut.py b/twisted/python/shortcut.py | |
index b60f858..9aa0dfd 100644 | |
--- a/twisted/python/shortcut.py | |
+++ b/twisted/python/shortcut.py | |
@@ -35,9 +35,9 @@ class Shortcut: | |
@param iconidx: If iconpath is set, optional index of the icon desired | |
""" | |
- def __init__(self, | |
+ def __init__(self, | |
path=None, | |
- arguments=None, | |
+ arguments=None, | |
description=None, | |
workingdir=None, | |
iconpath=None, | |
@@ -46,9 +46,9 @@ class Shortcut: | |
shell.CLSID_ShellLink, None, | |
pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink | |
) | |
- data = map(None, | |
+ data = map(None, | |
['"%s"' % os.path.abspath(path), arguments, description, | |
- os.path.abspath(workingdir), os.path.abspath(iconpath)], | |
+ os.path.abspath(workingdir), os.path.abspath(iconpath)], | |
("SetPath", "SetArguments", "SetDescription", | |
"SetWorkingDirectory") ) | |
for value, function in data: | |
@@ -61,16 +61,16 @@ class Shortcut: | |
def load( self, filename ): | |
"""Read a shortcut file from disk.""" | |
self._base.QueryInterface(pythoncom.IID_IPersistFile).Load(filename) | |
- | |
+ | |
def save( self, filename ): | |
"""Write the shortcut to disk. | |
The file should be named something.lnk. | |
""" | |
self._base.QueryInterface(pythoncom.IID_IPersistFile).Save(filename, 0) | |
- | |
+ | |
def __getattr__( self, name ): | |
if name != "_base": | |
return getattr(self._base, name) | |
- raise AttributeError, "%s instance has no attribute %s" % \ | |
- (self.__class__.__name__, name) | |
+ raise AttributeError("%s instance has no attribute %s" % \ | |
+ (self.__class__.__name__, name)) | |
diff --git a/twisted/python/test/test_shellcomp.py b/twisted/python/test/test_shellcomp.py | |
index b7732ea..6deea0c 100755 | |
--- a/twisted/python/test/test_shellcomp.py | |
+++ b/twisted/python/test/test_shellcomp.py | |
@@ -76,13 +76,13 @@ def test_genZshFunction(self, cmdName, optionsFQPN): | |
# dependencies (pyOpenSSL, etc) so we have to skip them. | |
try: | |
o = reflect.namedAny(optionsFQPN)() | |
- except Exception, e: | |
+ except Exception as e: | |
raise unittest.SkipTest("Couldn't import or instantiate " | |
"Options class: %s" % (e,)) | |
try: | |
o.parseOptions(["", "--_shell-completion", "zsh:2"]) | |
- except ImportError, e: | |
+ except ImportError as e: | |
# this can happen for commands which don't have all | |
# the necessary dependencies installed. skip test. | |
# skip | |
@@ -103,7 +103,7 @@ def test_genZshFunction(self, cmdName, optionsFQPN): | |
try: | |
o.parseOptions([cmd, "", "--_shell-completion", | |
"zsh:3"]) | |
- except ImportError, e: | |
+ except ImportError as e: | |
# this can happen for commands which don't have all | |
# the necessary dependencies installed. skip test. | |
raise unittest.SkipTest("ImportError calling parseOptions() " | |
@@ -468,7 +468,7 @@ class FighterAceOptions(usage.Options): | |
'4' '5'])}, | |
extraActions=[CompleteFiles(descr='saved game file to load')] | |
) | |
- | |
+ | |
def opt_silly(self): | |
# A silly option which nobody can explain | |
""" """ | |
diff --git a/twisted/runner/inetdconf.py b/twisted/runner/inetdconf.py | |
index ddea924..0d3b5dc 100644 | |
--- a/twisted/runner/inetdconf.py | |
+++ b/twisted/runner/inetdconf.py | |
@@ -42,24 +42,24 @@ class UnknownService(Exception): | |
class SimpleConfFile: | |
"""Simple configuration file parser superclass. | |
- Filters out comments and empty lines (which includes lines that only | |
+ Filters out comments and empty lines (which includes lines that only | |
contain comments). | |
To use this class, override parseLine or parseFields. | |
""" | |
- | |
+ | |
commentChar = '#' | |
defaultFilename = None | |
- | |
+ | |
def parseFile(self, file=None): | |
"""Parse a configuration file | |
- | |
+ | |
If file is None and self.defaultFilename is set, it will open | |
defaultFilename and use it. | |
""" | |
if file is None and self.defaultFilename: | |
file = open(self.defaultFilename,'r') | |
- | |
+ | |
for line in file.readlines(): | |
# Strip out comments | |
comment = line.find(self.commentChar) | |
@@ -77,15 +77,15 @@ class SimpleConfFile: | |
def parseLine(self, line): | |
"""Override this. | |
- | |
+ | |
By default, this will split the line on whitespace and call | |
self.parseFields (catching any errors). | |
""" | |
try: | |
self.parseFields(*line.split()) | |
except ValueError: | |
- raise InvalidInetdConfError, 'Invalid line: ' + repr(line) | |
- | |
+ raise InvalidInetdConfError('Invalid line: ' + repr(line)) | |
+ | |
def parseFields(self, *fields): | |
"""Override this.""" | |
@@ -101,7 +101,7 @@ class InetdService: | |
group = None | |
program = None | |
programArgs = None | |
- | |
+ | |
def __init__(self, name, port, socketType, protocol, wait, user, group, | |
program, programArgs): | |
self.name = name | |
@@ -119,10 +119,10 @@ class InetdConf(SimpleConfFile): | |
"""Configuration parser for a traditional UNIX inetd(8)""" | |
defaultFilename = '/etc/inetd.conf' | |
- | |
+ | |
def __init__(self, knownServices=None): | |
self.services = [] | |
- | |
+ | |
if knownServices is None: | |
knownServices = ServicesConf() | |
knownServices.parseFile() | |
@@ -146,20 +146,20 @@ class InetdConf(SimpleConfFile): | |
port = int(serviceName) | |
serviceName = 'unknown' | |
except: | |
- raise UnknownService, "Unknown service: %s (%s)" \ | |
- % (serviceName, protocol) | |
+ raise UnknownService("Unknown service: %s (%s)" \ | |
+ % (serviceName, protocol)) | |
self.services.append(InetdService(serviceName, port, socketType, | |
protocol, wait, user, group, program, | |
programArgs)) | |
- | |
- | |
+ | |
+ | |
class ServicesConf(SimpleConfFile): | |
"""/etc/services parser | |
- | |
+ | |
@ivar services: dict mapping service names to (port, protocol) tuples. | |
""" | |
- | |
+ | |
defaultFilename = '/etc/services' | |
def __init__(self): | |
@@ -170,8 +170,8 @@ class ServicesConf(SimpleConfFile): | |
port, protocol = portAndProtocol.split('/') | |
port = long(port) | |
except: | |
- raise InvalidServicesConfError, 'Invalid port/protocol:' + \ | |
- repr(portAndProtocol) | |
+ raise InvalidServicesConfError('Invalid port/protocol:' + \ | |
+ repr(portAndProtocol)) | |
self.services[(name, protocol)] = port | |
for alias in aliases: | |
@@ -199,10 +199,8 @@ class RPCServicesConf(SimpleConfFile): | |
try: | |
port = long(port) | |
except: | |
- raise InvalidRPCServicesConfError, 'Invalid port:' + repr(port) | |
+ raise InvalidRPCServicesConfError('Invalid port:' + repr(port)) | |
self.services[name] = port | |
for alias in aliases: | |
self.services[alias] = port | |
- | |
- | |
diff --git a/twisted/scripts/_twistw.py b/twisted/scripts/_twistw.py | |
index 9bf1348..5f5c322 100644 | |
--- a/twisted/scripts/_twistw.py | |
+++ b/twisted/scripts/_twistw.py | |
@@ -2,6 +2,8 @@ | |
# Copyright (c) Twisted Matrix Laboratories. | |
# See LICENSE for details. | |
+from __future__ import print_function | |
+ | |
from twisted.python import log | |
from twisted.application import app, service, internet | |
from twisted import copyright | |
@@ -18,8 +20,8 @@ class ServerOptions(app.ServerOptions): | |
def opt_version(self): | |
"""Print version information and exit. | |
""" | |
- print 'twistd (the Twisted Windows runner) %s' % copyright.version | |
- print copyright.copyright | |
+ print('twistd (the Twisted Windows runner) %s' % copyright.version) | |
+ print(copyright.copyright) | |
sys.exit() | |
diff --git a/twisted/scripts/htmlizer.py b/twisted/scripts/htmlizer.py | |
index 4357809..5acd8da 100644 | |
--- a/twisted/scripts/htmlizer.py | |
+++ b/twisted/scripts/htmlizer.py | |
@@ -5,6 +5,8 @@ | |
"""HTML pretty-printing for Python source code.""" | |
+from __future__ import print_function | |
+ | |
__version__ = '$Revision: 1.8 $'[11:-2] | |
from twisted.python import htmlizer, usage | |
@@ -45,8 +47,8 @@ def run(): | |
options = Options() | |
try: | |
options.parseOptions() | |
- except usage.UsageError, e: | |
- print str(e) | |
+ except usage.UsageError as e: | |
+ print(str(e)) | |
sys.exit(1) | |
filename = options['filename'] | |
if options.get('stylesheet') is not None: | |
diff --git a/twisted/scripts/manhole.py b/twisted/scripts/manhole.py | |
index 06adffb..e82603d 100644 | |
--- a/twisted/scripts/manhole.py | |
+++ b/twisted/scripts/manhole.py | |
@@ -5,6 +5,8 @@ | |
Start a L{twisted.manhole} client. | |
""" | |
+from __future__ import print_function | |
+ | |
import sys | |
from twisted.python import usage | |
@@ -13,9 +15,9 @@ def run(): | |
config = MyOptions() | |
try: | |
config.parseOptions() | |
- except usage.UsageError, e: | |
- print str(e) | |
- print str(config) | |
+ except usage.UsageError as e: | |
+ print(str(e)) | |
+ print(str(config)) | |
sys.exit(1) | |
run_gtk2(config) | |
diff --git a/twisted/spread/pb.py b/twisted/spread/pb.py | |
index 548c6a7..66d78bc 100644 | |
--- a/twisted/spread/pb.py | |
+++ b/twisted/spread/pb.py | |
@@ -887,7 +887,7 @@ class Broker(banana.Banana): | |
if object is None: | |
raise Error("Invalid Object ID") | |
netResult = object.remoteMessageReceived(self, message, netArgs, netKw) | |
- except Error, e: | |
+ except Error as e: | |
if answerRequired: | |
# If the error is Jellyable or explicitly allowed via our | |
# security options, send it back and let the code on the | |
diff --git a/twisted/tap/socks.py b/twisted/tap/socks.py | |
index a418f0c..fa449fd 100644 | |
--- a/twisted/tap/socks.py | |
+++ b/twisted/tap/socks.py | |
@@ -7,6 +7,8 @@ | |
I am a support module for making SOCKSv4 servers with twistd. | |
""" | |
+from __future__ import print_function | |
+ | |
from twisted.protocols import socks | |
from twisted.python import usage | |
from twisted.application import internet | |
@@ -27,12 +29,12 @@ class Options(usage.Options): | |
def makeService(config): | |
if config["interface"] != "127.0.0.1": | |
- print "WARNING:" | |
- print " You have chosen to listen on a non-local interface." | |
- print " This may allow intruders to access your local network" | |
- print " if you run this on a firewall." | |
+ print() | |
+ print("WARNING:") | |
+ print(" You have chosen to listen on a non-local interface.") | |
+ print(" This may allow intruders to access your local network") | |
+ print(" if you run this on a firewall.") | |
+ print() | |
t = socks.SOCKSv4Factory(config['log']) | |
portno = int(config['port']) | |
return internet.TCPServer(portno, t, interface=config['interface']) | |
diff --git a/twisted/test/test_banana.py b/twisted/test/test_banana.py | |
index 2274bfc..3055249 100644 | |
--- a/twisted/test/test_banana.py | |
+++ b/twisted/test/test_banana.py | |
@@ -15,7 +15,7 @@ from twisted.test.proto_helpers import StringTransport | |
class MathTests(unittest.TestCase): | |
def test_int2b128(self): | |
- funkylist = range(0,100) + range(1000,1100) + range(1000000,1000100) + [1024 **10l] | |
+ funkylist = range(0,100) + range(1000,1100) + range(1000000,1000100) + [1024 **10] | |
for i in funkylist: | |
x = StringIO.StringIO() | |
banana.int2b128(i, x.write) | |
@@ -157,7 +157,7 @@ class BananaTests(BananaTestBase): | |
banana without changing value and should come out represented | |
as an C{int} (regardless of the type which was encoded). | |
""" | |
- for value in (10151, 10151L): | |
+ for value in (10151, 10151): | |
self.enc.sendEncoded(value) | |
self.enc.dataReceived(self.io.getvalue()) | |
self.assertEqual(self.result, 10151) | |
@@ -249,9 +249,9 @@ class BananaTests(BananaTestBase): | |
def test_negativeLong(self): | |
- self.enc.sendEncoded(-1015l) | |
+ self.enc.sendEncoded(-1015) | |
self.enc.dataReceived(self.io.getvalue()) | |
- assert self.result == -1015l, "should be -1015l, got %s" % self.result | |
+ assert self.result == -1015, "should be -1015l, got %s" % self.result | |
def test_integer(self): | |
@@ -287,7 +287,7 @@ class BananaTests(BananaTestBase): | |
foo = [1, 2, [3, 4], [30.5, 40.2], 5, | |
["six", "seven", ["eight", 9]], [10], | |
# TODO: currently the C implementation's a bit buggy... | |
- sys.maxint * 3l, sys.maxint * 2l, sys.maxint * -2l] | |
+ sys.maxint * 3, sys.maxint * 2, sys.maxint * -2] | |
self.enc.sendEncoded(foo) | |
self.feed(self.io.getvalue()) | |
assert self.result == foo, "%s!=%s" % (repr(self.result), repr(foo)) | |
diff --git a/twisted/test/test_nmea.py b/twisted/test/test_nmea.py | |
index 35bb18d..f292d23 100644 | |
--- a/twisted/test/test_nmea.py | |
+++ b/twisted/test/test_nmea.py | |
@@ -27,7 +27,7 @@ class ResultHarvester: | |
l = len(self.results) | |
try: | |
function(*args, **kwargs) | |
- except Exception, e: | |
+ except Exception as e: | |
self.results.append(e) | |
if l == len(self.results): | |
self.results.append(NotImplementedError()) | |
diff --git a/twisted/test/test_pbfailure.py b/twisted/test/test_pbfailure.py | |
index 5712b05..cac2156 100644 | |
--- a/twisted/test/test_pbfailure.py | |
+++ b/twisted/test/test_pbfailure.py | |
@@ -379,7 +379,7 @@ class PBFailureTests(PBConnTestCase): | |
def generatorFunc(): | |
try: | |
yield None | |
- except pb.RemoteError, exc: | |
+ except pb.RemoteError as exc: | |
exception.append(exc) | |
else: | |
self.fail("RemoteError not raised") | |
diff --git a/twisted/trial/_dist/workertrial.py b/twisted/trial/_dist/workertrial.py | |
index 4e768e6..0cdc43b 100644 | |
--- a/twisted/trial/_dist/workertrial.py | |
+++ b/twisted/trial/_dist/workertrial.py | |
@@ -83,7 +83,7 @@ def main(_fdopen=os.fdopen): | |
while True: | |
try: | |
r = protocolIn.read(1) | |
- except IOError, e: | |
+ except IOError as e: | |
if e.args[0] == errno.EINTR: | |
sys.exc_clear() | |
continue | |
diff --git a/twisted/web/domhelpers.py b/twisted/web/domhelpers.py | |
index 60a90f9..90878cb 100644 | |
--- a/twisted/web/domhelpers.py | |
+++ b/twisted/web/domhelpers.py | |
@@ -57,7 +57,7 @@ def get(node, nodeId): | |
""" | |
result = _get(node, nodeId) | |
if result: return result | |
- raise NodeLookupError, nodeId | |
+ raise NodeLookupError(nodeId) | |
def getIfExists(node, nodeId): | |
""" | |
diff --git a/twisted/web/sux.py b/twisted/web/sux.py | |
index 0d86ed6..ec027b5 100644 | |
--- a/twisted/web/sux.py | |
+++ b/twisted/web/sux.py | |
@@ -20,6 +20,8 @@ does not: | |
option, they're not on by default). | |
""" | |
+from __future__ import print_function | |
+ | |
from twisted.internet.protocol import Protocol | |
from twisted.python.reflect import prefixedMethodNames | |
@@ -595,19 +597,19 @@ class XMLParser(Protocol): | |
'''Encountered an opening tag. | |
Default behaviour is to print.''' | |
- print 'begin', name, attributes | |
+ print('begin', name, attributes) | |
def gotText(self, data): | |
'''Encountered text | |
Default behaviour is to print.''' | |
- print 'text:', repr(data) | |
+ print('text:', repr(data)) | |
def gotEntityReference(self, entityRef): | |
'''Encountered mnemonic entity reference | |
Default behaviour is to print.''' | |
- print 'entityRef: &%s;' % entityRef | |
+ print('entityRef: &%s;' % entityRef) | |
def gotComment(self, comment): | |
'''Encountered comment. | |
@@ -627,10 +629,10 @@ class XMLParser(Protocol): | |
This is really grotty: it basically just gives you everything between | |
'<!DOCTYPE' and '>' as an argument. | |
""" | |
- print '!DOCTYPE', repr(doctype) | |
+ print('!DOCTYPE', repr(doctype)) | |
def gotTagEnd(self, name): | |
'''Encountered closing tag | |
Default behaviour is to print.''' | |
- print 'end', name | |
+ print('end', name) | |
diff --git a/twisted/words/im/pbsupport.py b/twisted/words/im/pbsupport.py | |
index 04d14e9..af02622 100644 | |
--- a/twisted/words/im/pbsupport.py | |
+++ b/twisted/words/im/pbsupport.py | |
@@ -6,6 +6,8 @@ | |
L{twisted.words} support for Instance Messenger. | |
""" | |
+from __future__ import print_function | |
+ | |
from twisted.internet import defer | |
from twisted.internet import error | |
from twisted.python import log | |
@@ -44,7 +46,7 @@ class TwistedWordsPerson(basesupport.AbstractPerson): | |
return self.account.client.perspective.callRemote('directMessage',self.name, text) | |
def metadataFailed(self, result, text): | |
- print "result:",result,"text:",text | |
+ print("result:", result, "text:", text) | |
return self.account.client.perspective.directMessage(self.name, text) | |
def setStatus(self, status): | |
@@ -77,7 +79,7 @@ class TwistedWordsGroup(basesupport.AbstractGroup): | |
self.name) | |
def metadataFailed(self, result, text): | |
- print "result:",result,"text:",text | |
+ print("result:", result, "text:", text) | |
return self.account.client.perspective.callRemote('groupMessage', | |
self.name, text) | |
@@ -101,7 +103,7 @@ class TwistedWordsClient(pb.Referenceable, basesupport.AbstractClientMixin): | |
_logonDeferred=None): | |
self.accountName = "%s (%s:%s)" % (acct.accountName, serviceName, perspectiveName) | |
self.name = perspectiveName | |
- print "HELLO I AM A PB SERVICE", serviceName, perspectiveName | |
+ print("HELLO I AM A PB SERVICE", serviceName, perspectiveName) | |
self.chat = chatui | |
self.account = acct | |
self._logonDeferred = _logonDeferred | |
@@ -119,19 +121,19 @@ class TwistedWordsClient(pb.Referenceable, basesupport.AbstractClientMixin): | |
self.perspective.callRemote('addContact', name) | |
def remote_receiveGroupMembers(self, names, group): | |
- print 'received group members:', names, group | |
+ print('received group members:', names, group) | |
self.getGroupConversation(group).setGroupMembers(names) | |
def remote_receiveGroupMessage(self, sender, group, message, metadata=None): | |
- print 'received a group message', sender, group, message, metadata | |
+ print('received a group message', sender, group, message, metadata) | |
self.getGroupConversation(group).showGroupMessage(sender, message, metadata) | |
def remote_memberJoined(self, member, group): | |
- print 'member joined', member, group | |
+ print('member joined', member, group) | |
self.getGroupConversation(group).memberJoined(member) | |
def remote_memberLeft(self, member, group): | |
- print 'member left' | |
+ print('member left') | |
self.getGroupConversation(group).memberLeft(member) | |
def remote_notifyStatusChanged(self, name, status): | |
@@ -162,12 +164,12 @@ class TwistedWordsClient(pb.Referenceable, basesupport.AbstractClientMixin): | |
self.perspective.callRemote('getGroupMembers', name) | |
def _cbGroupLeft(self, result, name): | |
- print 'left',name | |
+ print('left', name) | |
groupConv = self.chat.getGroupConversation(self.getGroup(name), 1) | |
groupConv.showGroupMessage("sys", "you left") | |
def connected(self, perspective): | |
- print 'Connected Words Client!', perspective | |
+ print('Connected Words Client!', perspective) | |
if self._logonDeferred is not None: | |
self._logonDeferred.callback(self) | |
self.perspective = perspective | |
@@ -227,15 +229,15 @@ class PBAccount(basesupport.AbstractAccount): | |
def _startLogOn(self, chatui): | |
- print 'Connecting...', | |
+ print('Connecting...',) | |
d = pb.getObjectAt(self.host, self.port) | |
d.addCallbacks(self._cbConnected, self._ebConnected, | |
callbackArgs=(chatui,)) | |
return d | |
def _cbConnected(self, root, chatui): | |
- print 'Connected!' | |
- print 'Identifying...', | |
+ print('Connected!') | |
+ print('Identifying...', end="") | |
d = pb.authIdentity(root, self.username, self.password) | |
d.addCallbacks(self._cbIdent, self._ebConnected, | |
callbackArgs=(chatui,)) | |
@@ -243,9 +245,9 @@ class PBAccount(basesupport.AbstractAccount): | |
def _cbIdent(self, ident, chatui): | |
if not ident: | |
- print 'falsely identified.' | |
+ print('falsely identified.') | |
return self._ebConnected(Failure(Exception("username or password incorrect"))) | |
- print 'Identified!' | |
+ print('Identified!') | |
dl = [] | |
for handlerClass, sname, pname in self.services: | |
d = defer.Deferred() | |
@@ -255,6 +257,5 @@ class PBAccount(basesupport.AbstractAccount): | |
return defer.DeferredList(dl) | |
def _ebConnected(self, error): | |
- print 'Not connected.' | |
+ print('Not connected.') | |
return error | |
- | |
diff --git a/twisted/words/protocols/irc.py b/twisted/words/protocols/irc.py | |
index 04bfea9..639746b 100644 | |
--- a/twisted/words/protocols/irc.py | |
+++ b/twisted/words/protocols/irc.py | |
@@ -47,10 +47,10 @@ from twisted.protocols import basic | |
from twisted.python import log, reflect, _textattributes | |
NUL = chr(0) | |
-CR = chr(015) | |
-NL = chr(012) | |
+CR = chr(0o15) | |
+NL = chr(0o12) | |
LF = NL | |
-SPC = chr(040) | |
+SPC = chr(0o40) | |
# This includes the CRLF terminator characters. | |
MAX_COMMAND_LENGTH = 512 | |
@@ -2546,8 +2546,8 @@ class IRCClient(basic.LineReceiver): | |
def ctcpReply_PING(self, user, channel, data): | |
nick = user.split('!', 1)[0] | |
if (not self._pings) or (not self._pings.has_key((nick, data))): | |
- raise IRCBadMessage,\ | |
- "Bogus PING response from %s: %s" % (user, data) | |
+ raise IRCBadMessage( | |
+ "Bogus PING response from %s: %s" % (user, data)) | |
t0 = self._pings[(nick, data)] | |
self.pong(user, time.time() - t0) | |
@@ -2703,8 +2703,7 @@ def dccParseAddress(address): | |
try: | |
address = long(address) | |
except ValueError: | |
- raise IRCBadMessage,\ | |
- "Indecipherable address %r" % (address,) | |
+ raise IRCBadMessage("Indecipherable address %r" % (address,)) | |
else: | |
address = ( | |
(address >> 24) & 0xFF, | |
@@ -3633,7 +3632,7 @@ def stripFormatting(text): | |
# CTCP constants and helper functions | |
-X_DELIM = chr(001) | |
+X_DELIM = chr(0o01) | |
def ctcpExtract(message): | |
""" | |
@@ -3677,7 +3676,7 @@ def ctcpExtract(message): | |
# CTCP escaping | |
-M_QUOTE= chr(020) | |
+M_QUOTE= chr(0o20) | |
mQuoteTable = { | |
NUL: M_QUOTE + '0', | |
diff --git a/twisted/words/protocols/jabber/jid.py b/twisted/words/protocols/jabber/jid.py | |
index 9911cee..747e15c 100644 | |
--- a/twisted/words/protocols/jabber/jid.py | |
+++ b/twisted/words/protocols/jabber/jid.py | |
@@ -82,23 +82,23 @@ def prep(user, host, resource): | |
try: | |
user = nodeprep.prepare(unicode(user)) | |
except UnicodeError: | |
- raise InvalidFormat, "Invalid character in username" | |
+ raise InvalidFormat("Invalid character in username") | |
else: | |
user = None | |
if not host: | |
- raise InvalidFormat, "Server address required." | |
+ raise InvalidFormat("Server address required.") | |
else: | |
try: | |
host = nameprep.prepare(unicode(host)) | |
except UnicodeError: | |
- raise InvalidFormat, "Invalid character in hostname" | |
+ raise InvalidFormat("Invalid character in hostname") | |
if resource: | |
try: | |
resource = resourceprep.prepare(unicode(resource)) | |
except UnicodeError: | |
- raise InvalidFormat, "Invalid character in resource" | |
+ raise InvalidFormat("Invalid character in resource") | |
else: | |
resource = None | |
diff --git a/twisted/words/protocols/jabber/sasl.py b/twisted/words/protocols/jabber/sasl.py | |
index 0ea201d..5fc4724 100644 | |
--- a/twisted/words/protocols/jabber/sasl.py | |
+++ b/twisted/words/protocols/jabber/sasl.py | |
@@ -86,7 +86,7 @@ def fromBase64(s): | |
try: | |
return b64decode(s) | |
- except Exception, e: | |
+ except Exception as e: | |
raise SASLIncorrectEncodingError(str(e)) | |
diff --git a/twisted/words/protocols/jabber/xmpp_stringprep.py b/twisted/words/protocols/jabber/xmpp_stringprep.py | |
index cfdc39c..ff3d0c8 100644 | |
--- a/twisted/words/protocols/jabber/xmpp_stringprep.py | |
+++ b/twisted/words/protocols/jabber/xmpp_stringprep.py | |
@@ -133,12 +133,12 @@ class Profile: | |
for c in string: | |
for table in self.prohibiteds: | |
if table.lookup(c): | |
- raise UnicodeError, "Invalid character %s" % repr(c) | |
+ raise UnicodeError("Invalid character %s" % repr(c)) | |
def check_unassigneds(self, string): | |
for c in string: | |
if stringprep.in_table_a1(c): | |
- raise UnicodeError, "Unassigned code point %s" % repr(c) | |
+ raise UnicodeError("Unassigned code point %s" % repr(c)) | |
def check_bidirectionals(self, string): | |
found_LCat = False | |
@@ -151,11 +151,11 @@ class Profile: | |
found_LCat = True | |
if found_LCat and found_RandALCat: | |
- raise UnicodeError, "Violation of BIDI Requirement 2" | |
+ raise UnicodeError("Violation of BIDI Requirement 2") | |
if found_RandALCat and not (stringprep.in_table_d1(string[0]) and | |
stringprep.in_table_d1(string[-1])): | |
- raise UnicodeError, "Violation of BIDI Requirement 3" | |
+ raise UnicodeError("Violation of BIDI Requirement 3") | |
class NamePrep: | |
@@ -206,15 +206,15 @@ class NamePrep: | |
def check_prohibiteds(self, string): | |
for c in string: | |
if c in self.prohibiteds: | |
- raise UnicodeError, "Invalid character %s" % repr(c) | |
+ raise UnicodeError("Invalid character %s" % repr(c)) | |
def nameprep(self, label): | |
label = idna.nameprep(label) | |
self.check_prohibiteds(label) | |
if label[0] == '-': | |
- raise UnicodeError, "Invalid leading hyphen-minus" | |
+ raise UnicodeError("Invalid leading hyphen-minus") | |
if label[-1] == '-': | |
- raise UnicodeError, "Invalid trailing hyphen-minus" | |
+ raise UnicodeError("Invalid trailing hyphen-minus") | |
return label | |
diff --git a/twisted/words/xish/domish.py b/twisted/words/xish/domish.py | |
index 3be7ed6..e3958f4 100644 | |
--- a/twisted/words/xish/domish.py | |
+++ b/twisted/words/xish/domish.py | |
@@ -586,8 +586,8 @@ else: | |
def parse(self, buffer): | |
try: | |
self.dataReceived(buffer) | |
- except sux.ParseError, e: | |
- raise ParserError, str(e) | |
+ except sux.ParseError as e: | |
+ raise ParserError(str(e)) | |
def findUri(self, prefix): | |
@@ -690,7 +690,7 @@ else: | |
# Ensure the document hasn't already ended | |
if self.rootElem is None: | |
# XXX: Write more legible explanation | |
- raise ParserError, "Element closed after end of document." | |
+ raise ParserError("Element closed after end of document.") | |
# Fix up name | |
prefix, name = _splitPrefix(name) | |
@@ -703,7 +703,7 @@ else: | |
if self.currElem is None: | |
# Ensure element name and uri matches | |
if self.rootElem.name != name or self.rootElem.uri != uri: | |
- raise ParserError, "Mismatched root elements" | |
+ raise ParserError("Mismatched root elements") | |
self.DocumentEndEvent() | |
self.rootElem = None | |
@@ -713,7 +713,7 @@ else: | |
# element | |
if self.currElem.name != name or self.currElem.uri != uri: | |
# XXX: Write more legible explanation | |
- raise ParserError, "Malformed element close" | |
+ raise ParserError("Malformed element close") | |
# Pop prefix and default NS stack | |
self.prefixStack.pop() | |
@@ -752,8 +752,8 @@ class ExpatElementStream: | |
def parse(self, buffer): | |
try: | |
self.parser.Parse(buffer) | |
- except self.error, e: | |
- raise ParserError, str(e) | |
+ except self.error as e: | |
+ raise ParserError(str(e)) | |
def _onStartElement(self, name, attrs): | |
# Generate a qname tuple from the provided name. See | |
@@ -844,5 +844,3 @@ class ExpatElementStream: | |
## def parseFile(filename): | |
## return FileParser().parse(filename) | |
- | |
- | |
diff --git a/twisted/words/xish/xpathparser.g b/twisted/words/xish/xpathparser.g | |
index 02c67c9..bf84488 100644 | |
--- a/twisted/words/xish/xpathparser.g | |
+++ b/twisted/words/xish/xpathparser.g | |
@@ -33,6 +33,8 @@ produced by Yapps, and a context class that keeps track of the parse stack. | |
These have been copied from the Yapps runtime. | |
""" | |
+from __future__ import print_function | |
+ | |
import sys, re | |
class SyntaxError(Exception): | |
@@ -285,8 +287,8 @@ def print_line_with_pointer(text, p): | |
p = p - 7 | |
# Now print the string, along with an indicator | |
- print >>sys.stderr, '> ',text | |
- print >>sys.stderr, '> ',' '*p + '^' | |
+ print('> ', text, file=sys.stderr) | |
+ print('> ', ' ' * p + '^', file=sys.stderr) | |
def print_error(input, err, scanner): | |
"""Print error messages, the parser stack, and the input text -- for human-readable error messages.""" | |
@@ -294,7 +296,7 @@ def print_error(input, err, scanner): | |
# Figure out the line number | |
line_number = scanner.get_line_number() | |
column_number = scanner.get_column_number() | |
- print >>sys.stderr, '%d:%d: %s' % (line_number, column_number, err.msg) | |
+ print('%d:%d: %s' % (line_number, column_number, err.msg), file=sys.stderr) | |
context = err.context | |
if not context: | |
@@ -302,7 +304,7 @@ def print_error(input, err, scanner): | |
while context: | |
# TODO: add line number | |
- print >>sys.stderr, 'while parsing %s%s:' % (context.rule, tuple(context.args)) | |
+ print('while parsing %s%s:' % (context.rule, tuple(context.args)), file=sys.stderr) | |
print_line_with_pointer(input, context.scanner.get_prev_char_pos(context.tokenpos)) | |
context = context.parent | |
@@ -313,8 +315,8 @@ def wrap_error_reporter(parser, rule): | |
input = parser._scanner.input | |
print_error(input, e, parser._scanner) | |
except NoMoreTokens: | |
- print >>sys.stderr, 'Could not complete parsing; stopped around here:' | |
- print >>sys.stderr, parser._scanner | |
+ print('Could not complete parsing; stopped around here:', file=sys.stderr) | |
+ print(parser._scanner, file=sys.stderr) | |
from twisted.words.xish.xpath import AttribValue, BooleanValue, CompareValue | |
diff --git a/twisted/words/xish/xpathparser.py b/twisted/words/xish/xpathparser.py | |
index 312f6ec..0f4e0fc 100644 | |
--- a/twisted/words/xish/xpathparser.py | |
+++ b/twisted/words/xish/xpathparser.py | |
@@ -309,7 +309,7 @@ def print_error(input, err, scanner): | |
def wrap_error_reporter(parser, rule): | |
try: | |
return getattr(parser, rule)() | |
- except SyntaxError, e: | |
+ except SyntaxError as e: | |
input = parser._scanner.input | |
print_error(input, e, parser._scanner) | |
except NoMoreTokens: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment