From ee1747fcb4f46e4f53661806f996a280c36ea154 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Sat, 29 Aug 2009 13:04:48 -0500 Subject: [PATCH] make all syntax compatible with 3.1 and 2.5 --HG-- branch : trunk --- py/_testing/test_initpkg.py | 2 +- py/_testing/test_oldmagic.py | 18 ++++++------- py/bin/env.py | 4 +-- py/cmdline/pycleanup.py | 6 ++--- py/cmdline/pycountloc.py | 10 +++---- py/cmdline/pylookup.py | 6 ++--- py/cmdline/pyrest.py | 9 ++++--- py/cmdline/pysvnwcrevert.py | 2 +- py/cmdline/pywhich.py | 6 ++--- py/cmdline/testing/test_generic.py | 7 ++--- py/code/oldmagic.py | 2 +- py/execnet/channel.py | 4 +-- py/execnet/gateway.py | 2 +- py/execnet/gwmanage.py | 3 ++- py/execnet/inputoutput.py | 5 ++-- py/execnet/multi.py | 2 +- py/execnet/rsync.py | 5 ++-- py/execnet/script/loop_socketserver.py | 3 ++- py/execnet/script/shell.py | 21 ++++++++------- py/execnet/script/socketserver.py | 26 +++++++++++++------ py/execnet/script/socketserverservice.py | 6 ++--- py/execnet/testing/test_gateway.py | 8 +++--- py/log/testing/test_warning.py | 8 +++--- py/path/gateway/channeltest.py | 2 +- py/path/testing/test_local.py | 18 ++++++------- py/path/testing/test_svnauth.py | 8 +++--- py/rest/convert.py | 2 +- py/rest/directive.py | 4 +-- py/rest/latex.py | 15 ++++++----- py/rest/resthtml.py | 12 ++++++--- py/rest/rst.py | 4 +-- py/rest/testing/test_rst.py | 10 +++---- py/test/compat.py | 2 +- py/test/dist/testing/test_dsession.py | 6 ++--- py/test/dist/testing/test_nodemanage.py | 2 +- py/test/dist/testing/test_txnode.py | 8 +++--- py/test/dist/txnode.py | 2 +- py/test/looponfail/remote.py | 9 ++++--- py/test/looponfail/util.py | 2 +- py/test/plugin/pytest_pylint.py | 4 +-- py/test/plugin/pytest_restdoc.py | 20 +++++++------- py/test/plugin/test_pytest_runner.py | 8 +++--- py/test/plugin/test_pytest_terminal.py | 2 +- .../import_test/package/test_import.py | 13 +++++----- py/test/testing/test_collect.py | 4 +-- py/test/testing/test_compat.py | 2 +- py/test/testing/test_config.py | 4 +-- py/test/testing/test_funcargs.py | 2 +- py/test/testing/test_genitems.py | 4 +-- py/test/testing/test_outcome.py | 2 +- py/test/testing/test_pickling.py | 4 +-- py/test/testing/test_pluginmanager.py | 2 +- py/test/testing/test_session.py | 2 +- py/thread/pool.py | 3 ++- py/thread/testing/test_io.py | 8 +++--- py/thread/testing/test_pool.py | 4 +-- py/xmlobj/html.py | 7 ++++- py/xmlobj/misc.py | 15 ++++++++--- py/xmlobj/visit.py | 24 +++++++++++------ py/xmlobj/xml.py | 2 +- 60 files changed, 230 insertions(+), 177 deletions(-) diff --git a/py/_testing/test_initpkg.py b/py/_testing/test_initpkg.py index 17cd5c2d8..271246c01 100644 --- a/py/_testing/test_initpkg.py +++ b/py/_testing/test_initpkg.py @@ -85,7 +85,7 @@ def test_importall(): yield check_import, modpath def check_import(modpath): - print "checking import", modpath + py.builtin.print_("checking import", modpath) assert __import__(modpath) # diff --git a/py/_testing/test_oldmagic.py b/py/_testing/test_oldmagic.py index 6c3386fb7..93ed976e9 100644 --- a/py/_testing/test_oldmagic.py +++ b/py/_testing/test_oldmagic.py @@ -25,7 +25,7 @@ def test_invoke_compile(recwarn, monkeypatch): return 1 \n""", '', 'exec') d = {} - exec co in d + py.builtin.exec_(co, d) assert py.code.Source(d['f']) finally: py.magic.revoke(compile=True) @@ -100,12 +100,12 @@ class Testautopath: d = {'__file__' : str(testpath)} oldsyspath = sys.path[:] try: - exec self.getauto in d + py.test.exec_(self.getauto, d) conf = d['autopath'] assert conf.dirpath() == self.initdir2 assert conf.pkgdir == self.initdir assert str(self.root) in sys.path - exec self.getauto in d + py.test.exec_(self.getauto in d) assert conf is not d['autopath'] finally: sys.path[:] = oldsyspath @@ -116,12 +116,12 @@ class Testautopath: d = {'__file__' : str(testpath)} oldsyspath = sys.path[:] try: - exec self.getauto in d + py.test.exec_(self.getauto, d) conf = d['autopath'] assert conf == self.initdir2.join('autoconfiguretest.py') assert conf.pkgdir == self.initdir assert str(self.root) in sys.path - exec self.getauto in d + py.test.exec_(self.getauto, d) assert conf is not d['autopath'] finally: sys.path[:] = oldsyspath @@ -131,13 +131,13 @@ class Testautopath: d = {'__file__' : str(testpath)} oldsyspath = sys.path[:] try: - exec self.getauto in d + py.test.exec_(self.getauto, d) conf = d['autopath'] assert conf.dirpath() == self.root assert conf.pkgdir == self.root syspath = sys.path[:] assert str(self.root) in syspath - exec self.getauto in d + py.test.exec_(self.getauto, d) assert conf is not d['autopath'] finally: sys.path[:] = oldsyspath @@ -149,7 +149,7 @@ class Testautopath: oldsyspath = sys.path[:] try: d = {} - exec self.getauto in d + py.test.exec_(self.getauto, d) conf = d['autopath'] assert conf.dirpath() == self.initdir2 assert conf.pkgdir == self.initdir @@ -167,7 +167,7 @@ class Testautopath: try: py.test.raises(ValueError,''' d = {} - exec self.getauto in d + py.test.exec_(self.getauto, d) ''') finally: sys.path[:] = oldsyspath diff --git a/py/bin/env.py b/py/bin/env.py index 5e130d1b2..bb0e08550 100644 --- a/py/bin/env.py +++ b/py/bin/env.py @@ -29,5 +29,5 @@ def setenv(name, value): assert False, 'Shell not supported.' return cmd -print prepend_path('PATH', bindir) -print prepend_path('PYTHONPATH', rootdir) +print(prepend_path('PATH', bindir)) +print(prepend_path('PYTHONPATH', rootdir)) diff --git a/py/cmdline/pycleanup.py b/py/cmdline/pycleanup.py index 3e249977a..701fc25fd 100755 --- a/py/cmdline/pycleanup.py +++ b/py/cmdline/pycleanup.py @@ -27,10 +27,10 @@ def main(): for arg in args: path = py.path.local(arg) - print "cleaning path", path, "of extensions", ext + py.builtin.print_("cleaning path", path, "of extensions", ext) for x in path.visit(shouldremove, lambda x: x.check(dotfile=0, link=0)): if options.dryrun: - print "would remove", x + py.builtin.print_("would remove", x) else: - print "removing", x + py.builtin.print_("removing", x) x.remove() diff --git a/py/cmdline/pycountloc.py b/py/cmdline/pycountloc.py index ee909c8d5..28c0c172f 100755 --- a/py/cmdline/pycountloc.py +++ b/py/cmdline/pycountloc.py @@ -85,10 +85,10 @@ def countloc(paths=None): items = counter.file2numlines.items() items.sort(lambda x,y: cmp(x[1], y[1])) for x, y in items: - print "%3d %30s" % (y,x) + print("%3d %30s" % (y,x)) - print "%30s %3d" %("number of testfiles", numtestfiles) - print "%30s %3d" %("number of non-empty testlines", numtestlines) - print "%30s %3d" %("number of files", numfiles) - print "%30s %3d" %("number of non-empty lines", numlines) + print("%30s %3d" %("number of testfiles", numtestfiles)) + print("%30s %3d" %("number of non-empty testlines", numtestlines)) + print("%30s %3d" %("number of files", numfiles)) + print("%30s %3d" %("number of non-empty lines", numlines)) diff --git a/py/cmdline/pylookup.py b/py/cmdline/pylookup.py index e00b57acf..1658a0d73 100755 --- a/py/cmdline/pylookup.py +++ b/py/cmdline/pylookup.py @@ -44,7 +44,7 @@ def main(): if options.ignorecase: s = s.lower() if s.find(string) != -1: - print >>sys.stdout, "%s: filename matches %r" %(x, string) + sys.stdout.write("%s: filename matches %r" %(x, string) + "\n") try: s = x.read() @@ -75,5 +75,5 @@ def main(): else: context = (options.context)/2 for count in range(max(0, i-context), min(len(lines) - 1, i+context+1)): - print "%s:%d: %s" %(x.relto(curdir), count+1, lines[count].rstrip()) - print "-" * terminal_width + print("%s:%d: %s" %(x.relto(curdir), count+1, lines[count].rstrip())) + print("-" * terminal_width) diff --git a/py/cmdline/pyrest.py b/py/cmdline/pyrest.py index 9c639b2be..b9b8a99ab 100755 --- a/py/cmdline/pyrest.py +++ b/py/cmdline/pyrest.py @@ -17,7 +17,7 @@ import py if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()): def log(msg): - print msg + print(msg) else: def log(msg): pass @@ -37,8 +37,9 @@ def main(): try: from py.__.rest import directive, resthtml from py.__.rest.latex import process_rest_file, process_configfile - except ImportError, e: - print str(e) + except ImportError: + e = sys.exc_info()[1] + print(str(e)) sys.exit(1) (options, args) = parser.parse_args() @@ -70,7 +71,7 @@ def main(): if options.topdf: cfg = p.new(ext=".rst2pdfconfig") if cfg.check(): - print "using config file %s" % (cfg, ) + print("using config file %s" % (cfg, )) process_configfile(cfg, options.debug) else: process_rest_file(p.localpath, diff --git a/py/cmdline/pysvnwcrevert.py b/py/cmdline/pysvnwcrevert.py index bb394a9ac..3e1bb4774 100755 --- a/py/cmdline/pysvnwcrevert.py +++ b/py/cmdline/pysvnwcrevert.py @@ -19,7 +19,7 @@ the following 'svn up' won't just crash. import sys, py def kill(p, root): - print '< %s' % (p.relto(root),) + print('< %s' % (p.relto(root),)) p.remove(rec=1) def svnwcrevert(path, root=None, precious=[]): diff --git a/py/cmdline/pywhich.py b/py/cmdline/pywhich.py index 2acd33651..644ba8436 100755 --- a/py/cmdline/pywhich.py +++ b/py/cmdline/pywhich.py @@ -13,11 +13,11 @@ def main(): try: mod = __import__(name) except ImportError: - print >>sys.stderr, "could not import:", name + sys.stderr.write("could not import: " + name + "\n") else: try: location = mod.__file__ except AttributeError: - print >>sys.stderr, "module (has no __file__):", mod + sys.stderr.write("module (has no __file__): " + mod) else: - print location + print(location) diff --git a/py/cmdline/testing/test_generic.py b/py/cmdline/testing/test_generic.py index 1f6218322..a3efee0ec 100644 --- a/py/cmdline/testing/test_generic.py +++ b/py/cmdline/testing/test_generic.py @@ -26,19 +26,20 @@ def checkprocess(script): cmd = "%s" %(script, ) # XXX distributed testing's rsync does not support # syncing executable bits - script.chmod(0777) + script.chmod(int("777", 8)) if script.basename.startswith("py.lookup") or \ script.basename.startswith("py.which"): cmd += " sys" - print "executing", script + py.builtin.print_("executing", script) try: old = script.dirpath().chdir() try: py.process.cmdexec(cmd) finally: old.chdir() - except py.process.cmdexec.Error, e: + except py.process.cmdexec.Error: + e = sys.exc_info()[1] if cmd.find("py.rest") != -1 and \ e.out.find("module named") != -1: return diff --git a/py/code/oldmagic.py b/py/code/oldmagic.py index 6cfbc5d2b..7dc06de73 100644 --- a/py/code/oldmagic.py +++ b/py/code/oldmagic.py @@ -53,7 +53,7 @@ def revert(namespace, name): ) nref = (namespace, name) if nref not in patched or not patched[nref]: - raise ValueError, "No original value stored for %s.%s" % nref + raise ValueError("No original value stored for %s.%s" % nref) current = getattr(namespace, name) orig = patched[nref].pop() setattr(namespace, name, orig) diff --git a/py/execnet/channel.py b/py/execnet/channel.py index 088fa97e2..bf479f10e 100644 --- a/py/execnet/channel.py +++ b/py/execnet/channel.py @@ -144,7 +144,7 @@ class Channel(object): """ self._receiveclosed.wait(timeout=timeout) # wait for non-"opened" state if not self._receiveclosed.isSet(): - raise IOError, "Timeout" + raise IOError("Timeout") error = self._getremoteerror() if error: raise error @@ -155,7 +155,7 @@ class Channel(object): Note that an item needs to be marshallable. """ if self.isclosed(): - raise IOError, "cannot send to %r" %(self,) + raise IOError("cannot send to %r" %(self,)) if isinstance(item, Channel): data = Message.CHANNEL_NEW(self.id, item.id) else: diff --git a/py/execnet/gateway.py b/py/execnet/gateway.py index 91f697bfd..2b35ac119 100644 --- a/py/execnet/gateway.py +++ b/py/execnet/gateway.py @@ -237,7 +237,7 @@ class Gateway(object): try: co = compile(source+'\n', '', 'exec', __future__.CO_GENERATOR_ALLOWED) - exec co in loc + py.test.exec_(co, loc) finally: close() self._trace("execution finished:", repr(source)[:50]) diff --git a/py/execnet/gwmanage.py b/py/execnet/gwmanage.py index 6003ea491..38b212268 100644 --- a/py/execnet/gwmanage.py +++ b/py/execnet/gwmanage.py @@ -123,4 +123,5 @@ class HostRSync(py.execnet.RSync): if self._verbose: path = os.path.basename(self._sourcedir) + "/" + modified_rel_path remotepath = gateway.spec.chdir - print '%s:%s <= %s' % (gateway.remoteaddress, remotepath, path) + py.builtin.print_('%s:%s <= %s' % + (gateway.remoteaddress, remotepath, path)) diff --git a/py/execnet/inputoutput.py b/py/execnet/inputoutput.py index 6d764547a..439719626 100644 --- a/py/execnet/inputoutput.py +++ b/py/execnet/inputoutput.py @@ -14,8 +14,9 @@ class SocketIO: try: sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_IP, socket.IP_TOS, 0x10) # IPTOS_LOWDELAY - except socket.error, e: - print "WARNING: Cannot set socket option:", str(e) + except socket.error: + e = sys.exc_info()[1] + py.builtin.print_("WARNING: Cannot set socket option:", str(e)) self.readable = self.writeable = True def read(self, numbytes): diff --git a/py/execnet/multi.py b/py/execnet/multi.py index f08a02db3..ba4a48f47 100644 --- a/py/execnet/multi.py +++ b/py/execnet/multi.py @@ -63,6 +63,6 @@ class MultiChannel: if first is None: first = py.std.sys.exc_info() if first: - raise first[0], first[1], first[2] + py.builtin._reraise(first[0], first[1], first[2]) diff --git a/py/execnet/rsync.py b/py/execnet/rsync.py index 8ff30688f..6e34363c4 100644 --- a/py/execnet/rsync.py +++ b/py/execnet/rsync.py @@ -88,7 +88,8 @@ class RSync(object): def _report_send_file(self, gateway, modified_rel_path): if self._verbose: - print '%s <= %s' % (gateway.remoteaddress, modified_rel_path) + py.builtin.print_('%s <= %s' % (gateway.remoteaddress, + modified_rel_path)) def send(self, raises=True): """ Sends a sourcedir to all added targets. Flag indicates @@ -194,7 +195,7 @@ class RSync(object): elif stat.S_ISLNK(st.st_mode): self._send_link_structure(path) else: - raise ValueError, "cannot sync %r" % (path,) + raise ValueError("cannot sync %r" % (path,)) REMOTE_SOURCE = py.path.local(__file__).dirpath().\ join('rsync_remote.py').open().read() + "\nf()" diff --git a/py/execnet/script/loop_socketserver.py b/py/execnet/script/loop_socketserver.py index 00d31b349..44896b67b 100644 --- a/py/execnet/script/loop_socketserver.py +++ b/py/execnet/script/loop_socketserver.py @@ -8,6 +8,7 @@ if __name__ == '__main__': while 1: cmdlist = ["python", script] cmdlist.extend(sys.argv[1:]) - print "starting subcommand:", " ".join(cmdlist) + text = "starting subcommand: " + " ".join(cmdlist) + print(text) process = subprocess.Popen(cmdlist) process.wait() diff --git a/py/execnet/script/shell.py b/py/execnet/script/shell.py index 29846d4a2..9196f419f 100755 --- a/py/execnet/script/shell.py +++ b/py/execnet/script/shell.py @@ -9,7 +9,7 @@ import sys, os, socket, select try: clientsock except NameError: - print "client side starting" + print("client side starting") import sys host, port = sys.argv[1].split(':') port = int(port) @@ -17,7 +17,7 @@ except NameError: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.sendall(repr(myself)+'\n') - print "send boot string" + print("send boot string") inputlist = [ sock, sys.stdin ] try: while 1: @@ -31,11 +31,11 @@ except NameError: sys.stdout.flush() except: import traceback - print traceback.print_exc() + print(traceback.print_exc()) sys.exit(1) -print "server side starting" +print("server side starting") # server side # from traceback import print_exc @@ -47,7 +47,7 @@ class promptagent(Thread): self.clientsock = clientsock def run(self): - print "Entering thread prompt loop" + print("Entering thread prompt loop") clientfile = self.clientsock.makefile('w') filein = self.clientsock.makefile('r') @@ -58,22 +58,23 @@ class promptagent(Thread): clientfile.write('%s %s >>> ' % loc) clientfile.flush() line = filein.readline() - if len(line)==0: raise EOFError,"nothing" + if len(line)==0: raise EOFError("nothing") #print >>sys.stderr,"got line: " + line if line.strip(): oldout, olderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = clientfile, clientfile try: try: - exec compile(line + '\n','', 'single') + exec(compile(line + '\n','', 'single')) except: print_exc() finally: sys.stdout=oldout sys.stderr=olderr clientfile.flush() - except EOFError,e: - print >>sys.stderr, "connection close, prompt thread returns" + except EOFError: + e = sys.exc_info()[1] + sys.stderr.write("connection close, prompt thread returns") break #print >>sys.stdout, "".join(apply(format_exception,sys.exc_info())) @@ -81,4 +82,4 @@ class promptagent(Thread): prompter = promptagent(clientsock) prompter.start() -print "promptagent - thread started" +print("promptagent - thread started") diff --git a/py/execnet/script/socketserver.py b/py/execnet/script/socketserver.py index 5f7b7b3f3..7c3997830 100755 --- a/py/execnet/script/socketserver.py +++ b/py/execnet/script/socketserver.py @@ -22,12 +22,22 @@ if debug: # and not os.isatty(sys.stdin.fileno()): #import py #compile = py.code.compile +def print_(*args): + print(" ".join(args)) + +if sys.version_info > (3, 0): + exec("""def exec_(source, locs): + exec(source, locs)""") +else: + exec("""def exec_(source, locs): + exec source, locs""") + def exec_from_one_connection(serversock): - print progname, 'Entering Accept loop', serversock.getsockname() + print_(progname, 'Entering Accept loop', serversock.getsockname()) clientsock,address = serversock.accept() - print progname, 'got new connection from %s %s' % address + print_(progname, 'got new connection from %s %s' % address) clientfile = clientsock.makefile('r+',0) - print "reading line" + print_("reading line") # rstrip so that we can use \r\n for telnet testing source = clientfile.readline().rstrip() clientfile.close() @@ -35,11 +45,11 @@ def exec_from_one_connection(serversock): source = eval(source) if source: co = compile(source+'\n', source, 'exec') - print progname, 'compiled source, executing' + print_(progname, 'compiled source, executing') try: - exec co in g + exec_(co, g) finally: - print progname, 'finished executing code' + print_(progname, 'finished executing code') # background thread might hold a reference to this (!?) #clientsock.close() @@ -73,11 +83,11 @@ def startserver(serversock, loop=False): traceback.print_exc() else: excinfo = sys.exc_info() - print "got exception", excinfo[1] + print_("got exception", excinfo[1]) if not loop: break finally: - print "leaving socketserver execloop" + print_("leaving socketserver execloop") serversock.shutdown(2) if __name__ == '__main__': diff --git a/py/execnet/script/socketserverservice.py b/py/execnet/script/socketserverservice.py index 761d1d3db..e1d6cab7a 100644 --- a/py/execnet/script/socketserverservice.py +++ b/py/execnet/script/socketserverservice.py @@ -59,10 +59,10 @@ class SocketServerService(win32serviceutil.ServiceFramework): 0, # category servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_, '')) - print "Begin: %s" % (self._svc_display_name_) + print("Begin: %s" % (self._svc_display_name_)) hostport = ':8888' - print 'Starting py.execnet SocketServer on %s' % hostport + print('Starting py.execnet SocketServer on %s' % hostport) serversock = socketserver.bind_and_listen(hostport) thread = threading.Thread(target=socketserver.startserver, args=(serversock,), @@ -83,7 +83,7 @@ class SocketServerService(win32serviceutil.ServiceFramework): 0, # category servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_, '')) - print "End: %s" % appname + print("End: %s" % appname) if __name__ == '__main__': diff --git a/py/execnet/testing/test_gateway.py b/py/execnet/testing/test_gateway.py index d52f7ec31..bcfc50eac 100644 --- a/py/execnet/testing/test_gateway.py +++ b/py/execnet/testing/test_gateway.py @@ -162,7 +162,8 @@ class BasicRemoteExecution: channel = self.gw.remote_exec('def foo():\n return foobar()\nfoo()\n') try: channel.receive() - except channel.RemoteError, e: + except channel.RemoteError: + e = sys.exc_info()[1] assert str(e).startswith('Traceback (most recent call last):') assert str(e).find('NameError: global name \'foobar\' ' 'is not defined') > -1 @@ -174,7 +175,8 @@ class BasicRemoteExecution: channel = self.gw.remote_exec('def foo()\n return 1\nfoo()\n') try: channel.receive() - except channel.RemoteError, e: + except channel.RemoteError: + e = sys.exc_info()[1] assert str(e).startswith('Traceback (most recent call last):') assert str(e).find('SyntaxError') > -1 @@ -274,7 +276,7 @@ class BasicRemoteExecution: if subchannel and subchannel.isclosed(): break counter -= 1 - print counter + print(counter) if not counter: py.test.fail("timed out waiting for the answer[%d]" % len(l)) time.sleep(0.04) # busy-wait diff --git a/py/log/testing/test_warning.py b/py/log/testing/test_warning.py index 6a0b586b9..01b197b74 100644 --- a/py/log/testing/test_warning.py +++ b/py/log/testing/test_warning.py @@ -8,8 +8,8 @@ def test_apiwarn_functional(): capture = py.io.StdCapture() py.log._apiwarn("x.y.z", "something") out, err = capture.reset() - print "out", out - print "err", err + py.builtin.print_("out", out) + py.builtin.print_("err", err) assert err.find("x.y.z") != -1 lno = test_apiwarn_functional.func_code.co_firstlineno + 2 exp = "%s:%s" % (mypath, lno) @@ -57,8 +57,8 @@ def test_function(): capture = py.io.StdCapture() py.log._apiwarn("x.y.z", "something", function=test_function) out, err = capture.reset() - print "out", out - print "err", err + py.builtin.print_("out", out) + py.builtin.print_("err", err) assert err.find("x.y.z") != -1 lno = test_function.func_code.co_firstlineno exp = "%s:%s" % (mypath, lno) diff --git a/py/path/gateway/channeltest.py b/py/path/gateway/channeltest.py index 9d77ef01f..f6d951d48 100644 --- a/py/path/gateway/channeltest.py +++ b/py/path/gateway/channeltest.py @@ -62,4 +62,4 @@ if __name__ == '__main__': """) c.send(channel) c.send(srv.p2c(py.path.local('/tmp'))) - print c.receive() + print(c.receive()) diff --git a/py/path/testing/test_local.py b/py/path/testing/test_local.py index 519f4b070..b5cca273f 100644 --- a/py/path/testing/test_local.py +++ b/py/path/testing/test_local.py @@ -42,7 +42,7 @@ class TestLocalPath(LocalSetup, CommonFSTests): def test_remove_removes_readonly_dir(self): readonly_dir = self.tmpdir.join('readonlydir').ensure(dir=1) - readonly_dir.chmod(0500) + readonly_dir.chmod(int("500", 8)) readonly_dir.remove() assert not readonly_dir.check(exists=1) @@ -223,7 +223,7 @@ class TestExecution(LocalSetup): finally: env['PATH'] = oldpath - noperm.chmod(0644) + noperm.chmod(int("644", 8)) noperm.remove() def test_sysfind_absolute(self): @@ -367,13 +367,13 @@ class TestWINLocalPath: py.test.raises(NotImplementedError, "self.root.stat().group") def test_chmod_simple_int(self): - print "self.root is", self.root + py.builtin.print_("self.root is", self.root) mode = self.root.stat().mode # Ensure that we actually change the mode to something different. self.root.chmod(mode == 0 and 1 or 0) try: - print self.root.stat().mode - print mode + print(self.root.stat().mode) + print(mode) assert self.root.stat().mode != mode finally: self.root.chmod(mode) @@ -553,7 +553,7 @@ class TestPOSIXLocalPath: assert self.root == nroot def test_chmod_simple_int(self): - print "self.root is", self.root + py.builtin.print_("self.root is", self.root) mode = self.root.stat().mode self.root.chmod(mode/2) try: @@ -564,15 +564,15 @@ class TestPOSIXLocalPath: def test_chmod_rec_int(self): # XXX fragile test - print "self.root is", self.root + py.builtin.print_("self.root is", self.root) recfilter = lambda x: x.check(dotfile=0, link=0) oldmodes = {} for x in self.root.visit(rec=recfilter): oldmodes[x] = x.stat().mode - self.root.chmod(0772, rec=recfilter) + self.root.chmod(int("772", 8), rec=recfilter) try: for x in self.root.visit(rec=recfilter): - assert x.stat().mode & 0777 == 0772 + assert x.stat().mode & int("777", 8) == int("772", 8) finally: for x,y in oldmodes.items(): x.chmod(y) diff --git a/py/path/testing/test_svnauth.py b/py/path/testing/test_svnauth.py index c2ea1d933..e116ce6c8 100644 --- a/py/path/testing/test_svnauth.py +++ b/py/path/testing/test_svnauth.py @@ -36,8 +36,8 @@ def serve_bg(repopath): port, pidfile, repopath) try: py.process.cmdexec(cmd) - except py.process.cmdexec.Error, e: - pass + except py.process.cmdexec.Error: + e = sys.exc_info()[1] else: # XXX we assume here that the pid file gets written somewhere, I # guess this should be relatively safe... (I hope, at least?) @@ -276,8 +276,8 @@ class SvnAuthFunctionalTestBase(object): make_repo_auth(self.repopath, {'johnny': ('foo', 'rw')}) try: return serve_bg(self.repopath.dirpath()) - except IOError, e: - py.test.skip(str(e)) + except IOError: + py.test.skip(str(sys.exc_info()[1])) class TestSvnWCAuthFunctional(SvnAuthFunctionalTestBase): def test_checkout_constructor_arg(self): diff --git a/py/rest/convert.py b/py/rest/convert.py index df57bca72..523cac7df 100644 --- a/py/rest/convert.py +++ b/py/rest/convert.py @@ -50,7 +50,7 @@ def convert_dot(fn, new_extension): if not py.path.local.sysfind("dot"): raise SystemExit("ERROR: dot not found") result = fn.new(ext=new_extension) - print result + print(result) arg = "-T%s" % (format_to_dotargument[new_extension], ) py.std.os.system('dot "%s" "%s" > "%s"' % (arg, fn, result)) if new_extension == "eps": diff --git a/py/rest/directive.py b/py/rest/directive.py index 2951453fc..499d0313f 100644 --- a/py/rest/directive.py +++ b/py/rest/directive.py @@ -26,7 +26,7 @@ else: class ImageClass(object): option_spec = images.image.options def run(self): - return images.image(u'image', + return images.image('image', self.arguments, self.options, self.content, @@ -51,7 +51,7 @@ class GraphvizDirective(ImageClass): self.state.document.settings._source) text = self.block_text.replace("graphviz", "image", 1) self.block_text = text.replace(self.arguments[0], newname, 1) - self.name = u'image' + self.name = 'image' self.arguments = [newname] return ImageClass.run(self) diff --git a/py/rest/latex.py b/py/rest/latex.py index 1451d3485..d2c6f7f1f 100644 --- a/py/rest/latex.py +++ b/py/rest/latex.py @@ -132,15 +132,16 @@ def process_rest_file(restfile, stylesheet=None, debug=False, rest_options=None) while i < 10: # there should never be as many as five reruns, but to be sure try: latexoutput = py.process.cmdexec('pdflatex "%s"' % (tex, )) - except ExecutionFailed, e: - print "ERROR: pdflatex execution failed" - print "pdflatex stdout:" - print e.out - print "pdflatex stderr:" - print e.err + except ExecutionFailed: + e = py.std.sys.exc_info()[1] + print("ERROR: pdflatex execution failed") + print("pdflatex stdout:") + print(e.out) + print("pdflatex stderr:") + print(e.err) raise SystemExit if debug: - print latexoutput + print(latexoutput) if py.std.re.search("LaTeX Warning:.*Rerun", latexoutput) is None: break i += 1 diff --git a/py/rest/resthtml.py b/py/rest/resthtml.py index 6a97efe38..502302e6c 100644 --- a/py/rest/resthtml.py +++ b/py/rest/resthtml.py @@ -4,7 +4,7 @@ import re if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()): def log(msg): - print msg + print(msg) else: def log(msg): pass @@ -59,8 +59,14 @@ def process(txtpath, encoding='latin1'): # info = txtpath.info() # svninfopath.dump(info) -rex1 = re.compile(ur'.*(.*).*', re.MULTILINE | re.DOTALL) -rex2 = re.compile(ur'.*
(.*)
.*', re.MULTILINE | re.DOTALL) +if sys.version_info > (3, 0): + def _uni(s): return s +else: + def _uni(s): + return unicode(s) + +rex1 = re.compile(r'.*(.*).*', re.MULTILINE | re.DOTALL) +rex2 = re.compile(r'.*
(.*)
.*', re.MULTILINE | re.DOTALL) def strip_html_header(string, encoding='utf8'): """ return the content of the body-tag """ diff --git a/py/rest/rst.py b/py/rest/rst.py index 8eb7beeed..8207fb79c 100644 --- a/py/rest/rst.py +++ b/py/rest/rst.py @@ -128,8 +128,8 @@ class Rest(AbstractNode): outcome = [] if (isinstance(self.children[0], Transition) or isinstance(self.children[-1], Transition)): - raise ValueError, ('document must not begin or end with a ' - 'transition') + raise ValueError('document must not begin or end with a ' + 'transition') for child in self.children: outcome.append(child.text()) diff --git a/py/rest/testing/test_rst.py b/py/rest/testing/test_rst.py index 4cb6c27b0..1ef9ec3b2 100644 --- a/py/rest/testing/test_rst.py +++ b/py/rest/testing/test_rst.py @@ -149,8 +149,8 @@ turpis. Etiam et ipsum. Quisque at lacus. Etiam pellentesque, enim porta pulvinar viverra, libero elit iaculis justo, vitae convallis pede purus vel arcu. Morbi aliquam lacus et urna. Donec commodo pellentesque mi.""" txt = Paragraph(text, width=80).text() - print repr(txt) - print repr(expected) + print(repr(txt)) + print(repr(expected)) assert txt == expected checkrest(txt) @@ -172,7 +172,7 @@ Paragraph """ txt = Rest(Paragraph("Text"), LiteralBlock("def fun():\n some"), \ Paragraph("Paragraph")).text() - print repr(txt) + print(repr(txt)) assert txt == expected checkrest(txt) @@ -183,7 +183,7 @@ Foo Bar """ txt = Rest(Paragraph('Foo'), LiteralBlock(''), Paragraph('Bar')).text() - print repr(txt) + print(repr(txt)) assert txt == expected checkrest(txt) @@ -359,7 +359,7 @@ def test_nested_nested_lists(): """ txt = Rest(ListItem('foo', ListItem('bar', ListItem('baz')), ListItem('qux')), ListItem('quux')).text() - print txt + print(txt) assert txt == expected checkrest(txt) diff --git a/py/test/compat.py b/py/test/compat.py index d44482ec9..67551d71f 100644 --- a/py/test/compat.py +++ b/py/test/compat.py @@ -53,6 +53,6 @@ class TestCase(object): """ % locals() ) source = "".join(items) - exec py.code.Source(source).compile() + exec(py.code.Source(source).compile()) __all__ = ['TestCase'] diff --git a/py/test/dist/testing/test_dsession.py b/py/test/dist/testing/test_dsession.py index acfcdf22d..f4489e4e4 100644 --- a/py/test/dist/testing/test_dsession.py +++ b/py/test/dist/testing/test_dsession.py @@ -23,7 +23,7 @@ class MockNode: def dumpqueue(queue): while queue.qsize(): - print queue.get() + print(queue.get()) class TestDSession: def test_add_remove_node(self, testdir): @@ -184,7 +184,7 @@ class TestDSession: when = "call" session.queueevent("pytest_runtest_logreport", report=rep) reprec = testdir.getreportrecorder(session) - print session.item2nodes + print(session.item2nodes) loopstate = session._initloopstate([]) assert len(session.item2nodes[item1]) == 2 session.loop_once(loopstate) @@ -215,7 +215,7 @@ class TestDSession: item1.config.option.dist = "load" session.queueevent("pytest_testnodedown", node=node, error="xyz") reprec = testdir.getreportrecorder(session) - print session.item2nodes + print(session.item2nodes) loopstate = session._initloopstate([]) session.loop_once(loopstate) diff --git a/py/test/dist/testing/test_nodemanage.py b/py/test/dist/testing/test_nodemanage.py index da4fd979b..8384349b7 100644 --- a/py/test/dist/testing/test_nodemanage.py +++ b/py/test/dist/testing/test_nodemanage.py @@ -20,7 +20,7 @@ class TestNodeManager: nodemanager.rsync_roots() p, = nodemanager.gwmanager.multi_exec("import os ; channel.send(os.getcwd())").receive_each() p = py.path.local(p) - print "remote curdir", p + py.builtin.print_("remote curdir", p) assert p == mysetup.dest.join(config.topdir.basename) assert p.join("dir1").check() assert p.join("dir1", "file1").check() diff --git a/py/test/dist/testing/test_txnode.py b/py/test/dist/testing/test_txnode.py index f0e3a6273..fe1af7a10 100644 --- a/py/test/dist/testing/test_txnode.py +++ b/py/test/dist/testing/test_txnode.py @@ -17,7 +17,7 @@ class EventQueue: except py.std.Queue.Empty: #print "node channel", self.node.channel #print "remoteerror", self.node.channel._getremoteerror() - print "seen events", events + py.builtin.print_("seen events", events) raise IOError("did not see %r events" % (eventname)) else: name, args, kwargs = eventcall @@ -28,7 +28,7 @@ class EventQueue: return kwargs events.append(name) if name == "pytest_internalerror": - print str(kwargs["excrepr"]) + py.builtin.print_(str(kwargs["excrepr"])) class MySetup: def __init__(self, request): @@ -55,7 +55,7 @@ class MySetup: def xfinalize(self): if hasattr(self, 'node'): gw = self.node.gateway - print "exiting:", gw + py.builtin.print_("exiting:", gw) gw.exit() def pytest_funcarg__mysetup(request): @@ -117,7 +117,7 @@ class TestMasterSlaveConnection: kwargs = mysetup.geteventargs("pytest_runtest_logreport") rep = kwargs['report'] assert rep.passed - print rep + py.builtin.print_(rep) assert rep.item == item def test_send_some(self, testdir, mysetup): diff --git a/py/test/dist/txnode.py b/py/test/dist/txnode.py index b76f429b3..3c6f1b90f 100644 --- a/py/test/dist/txnode.py +++ b/py/test/dist/txnode.py @@ -66,7 +66,7 @@ class TXNode(object): raise except: excinfo = py.code.ExceptionInfo() - print "!" * 20, excinfo + py.builtin.print_("!" * 20, excinfo) self.config.pluginmanager.notify_exception(excinfo) def send(self, item): diff --git a/py/test/looponfail/remote.py b/py/test/looponfail/remote.py index 136b7e494..eaed38c4b 100644 --- a/py/test/looponfail/remote.py +++ b/py/test/looponfail/remote.py @@ -51,7 +51,7 @@ class RemoteControl(object): def trace(self, *args): if self.config.option.debug: msg = " ".join([str(x) for x in args]) - print "RemoteControl:", msg + py.builtin.print_("RemoteControl:", msg) def initgateway(self): return py.execnet.PopenGateway() @@ -97,7 +97,8 @@ class RemoteControl(object): self.channel.send(trails) try: return self.channel.receive() - except self.channel.RemoteError, e: + except self.channel.RemoteError: + e = sys.exc_info()[1] self.trace("ERROR", e) raise finally: @@ -107,7 +108,7 @@ def slave_runsession(channel, config, fullwidth, hasmarkup): """ we run this on the other side. """ if config.option.debug: def DEBUG(*args): - print " ".join(map(str, args)) + print(" ".join(map(str, args))) else: def DEBUG(*args): pass @@ -128,7 +129,7 @@ def slave_runsession(channel, config, fullwidth, hasmarkup): for trail in trails: try: colitem = py.test.collect.Collector._fromtrail(trail, config) - except AssertionError, e: + except AssertionError: #XXX send info for "test disappeared" or so continue colitems.append(colitem) diff --git a/py/test/looponfail/util.py b/py/test/looponfail/util.py index 0bd983d93..a12575e0a 100644 --- a/py/test/looponfail/util.py +++ b/py/test/looponfail/util.py @@ -38,7 +38,7 @@ class StatRecorder: if oldstat.mtime != curstat.mtime or \ oldstat.size != curstat.size: changed = True - print "# MODIFIED", path + py.builtin.print_("# MODIFIED", path) if removepycfiles and path.ext == ".py": pycfile = path + "c" if pycfile.check(): diff --git a/py/test/plugin/pytest_pylint.py b/py/test/plugin/pytest_pylint.py index ce20759f4..698828af3 100644 --- a/py/test/plugin/pytest_pylint.py +++ b/py/test/plugin/pytest_pylint.py @@ -29,8 +29,8 @@ class PylintItem(py.test.collect.Item): finally: out, err = capture.reset() rating = out.strip().split('\n')[-1] - print ">>>", - print rating + sys.stdout.write(">>>") + print(rating) assert 0 diff --git a/py/test/plugin/pytest_restdoc.py b/py/test/plugin/pytest_restdoc.py index 399ffca02..b85894799 100644 --- a/py/test/plugin/pytest_restdoc.py +++ b/py/test/plugin/pytest_restdoc.py @@ -135,7 +135,7 @@ class ReSTSyntaxTest(py.test.collect.Item): lexer = TextLexer() # take an arbitrary option if more than one is given formatter = options and VARIANTS[options.keys()[0]] or DEFAULT - parsed = highlight(u'\n'.join(content), lexer, formatter) + parsed = highlight('\n'.join(content), lexer, formatter) return [nodes.raw('', parsed, format='html')] pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS]) @@ -215,14 +215,15 @@ class DoctestText(py.test.collect.Item): for line in deindent(s).split('\n'): stripped = line.strip() if skipchunk and line.startswith(skipchunk): - print "skipping", line + py.builtin.print_("skipping", line) continue skipchunk = False if stripped.startswith(prefix): try: - exec py.code.Source(stripped[len(prefix):]).compile() in \ - mod.__dict__ - except ValueError, e: + py.builtin.exec_(py.code.Source( + stripped[len(prefix):]).compile(), mod.__dict__) + except ValueError: + e = sys.exc_info()[1] if e.args and e.args[0] == "skipchunk": skipchunk = " " * (len(line) - len(line.lstrip())) else: @@ -301,11 +302,12 @@ def urlcheck(tryfn, path, lineno, TIMEOUT_URLOPEN): py.std.socket.setdefaulttimeout(TIMEOUT_URLOPEN) try: try: - print "trying remote", tryfn + py.builtin.print_("trying remote", tryfn) py.std.urllib2.urlopen(tryfn) finally: py.std.socket.setdefaulttimeout(old) - except (py.std.urllib2.URLError, py.std.urllib2.HTTPError), e: + except (py.std.urllib2.URLError, py.std.urllib2.HTTPError): + e = sys.exc_info()[1] if getattr(e, 'code', None) in (401, 403): # authorization required, forbidden py.test.skip("%s: %s" %(tryfn, str(e))) else: @@ -325,7 +327,7 @@ def localrefcheck(tryfn, path, lineno): fn = path.dirpath(tryfn) ishtml = fn.ext == '.html' fn = ishtml and fn.new(ext='.txt') or fn - print "filename is", fn + py.builtin.print_("filename is", fn) if not fn.check(): # not ishtml or not fn.check(): if not py.path.local(tryfn).check(): # the html could be there py.test.fail("reference error %r in %s:%d" %( @@ -338,7 +340,7 @@ def localrefcheck(tryfn, path, lineno): match2 = ".. _`%s`:" % anchor match3 = ".. _%s:" % anchor candidates = (anchor, match2, match3) - print "candidates", repr(candidates) + py.builtin.print_("candidates", repr(candidates)) for line in source.split('\n'): line = line.strip() if line in candidates: diff --git a/py/test/plugin/test_pytest_runner.py b/py/test/plugin/test_pytest_runner.py index 84501a8e7..06c51dc87 100644 --- a/py/test/plugin/test_pytest_runner.py +++ b/py/test/plugin/test_pytest_runner.py @@ -78,7 +78,7 @@ class BaseFunctionalTests: def test_func(): pass """) - print reports + print(reports) rep = reports[0] assert not rep.failed assert not rep.passed @@ -112,7 +112,7 @@ class BaseFunctionalTests: def test_func(): pass """) - print reports + print(reports) assert len(reports) == 3 rep = reports[2] assert not rep.skipped @@ -159,7 +159,7 @@ class BaseFunctionalTests: """) assert len(reports) == 2 rep = reports[0] - print rep + print(rep) assert not rep.skipped assert not rep.passed assert rep.failed @@ -206,7 +206,7 @@ class TestExecutionNonForked(BaseFunctionalTests): def test_func(): raise KeyboardInterrupt("fake") """) - except KeyboardInterrupt, e: + except KeyboardInterrupt: pass else: py.test.fail("did not raise") diff --git a/py/test/plugin/test_pytest_terminal.py b/py/test/plugin/test_pytest_terminal.py index 0a9758ffc..6e0e0b759 100644 --- a/py/test/plugin/test_pytest_terminal.py +++ b/py/test/plugin/test_pytest_terminal.py @@ -175,7 +175,7 @@ class TestTerminal: g() # --calling-- """) for tbopt in ["long", "short", "no"]: - print 'testing --tb=%s...' % tbopt + print('testing --tb=%s...' % tbopt) result = testdir.runpytest('--tb=%s' % tbopt) s = result.stdout.str() if tbopt == "long": diff --git a/py/test/testing/import_test/package/test_import.py b/py/test/testing/import_test/package/test_import.py index 23efa42ac..3d7ba6ac9 100644 --- a/py/test/testing/import_test/package/test_import.py +++ b/py/test/testing/import_test/package/test_import.py @@ -1,5 +1,6 @@ import sys import os +import py def setup_module(mod=None): if mod is None: @@ -37,12 +38,12 @@ def test_import(): if mod1 is not mod2: bad_matches.append((name1, mod1, name2, mod2)) for name1, mod1, name2, mod2 in bad_matches: - print "These modules should be identical:" - print " %s:" % name1 - print " ", mod1 - print " %s:" % name2 - print " ", mod2 - print + print("These modules should be identical:") + print(" %s:" % name1) + print(" ", mod1) + print(" %s:" % name2) + print(" ", mod2) + py.builtin.print_() if bad_matches: assert False diff --git a/py/test/testing/test_collect.py b/py/test/testing/test_collect.py index c37c638b7..e18e27101 100644 --- a/py/test/testing/test_collect.py +++ b/py/test/testing/test_collect.py @@ -81,9 +81,9 @@ class TestCollector: def test_listnames_and__getitembynames(self, testdir): modcol = testdir.getmodulecol("pass", withinit=True) - print modcol.config.pluginmanager.getplugins() + print(modcol.config.pluginmanager.getplugins()) names = modcol.listnames() - print names + print(names) dircol = modcol.config.getfsnode(modcol.config.topdir) x = dircol._getitembynames(names) assert modcol.name == x.name diff --git a/py/test/testing/test_compat.py b/py/test/testing/test_compat.py index fea117940..3c972ae79 100644 --- a/py/test/testing/test_compat.py +++ b/py/test/testing/test_compat.py @@ -50,4 +50,4 @@ class TestCompatAssertions(TestCase): self.%(name)s, %(paramfail)s) """ % locals() co = py.code.Source(source).compile() - exec co + exec(co) diff --git a/py/test/testing/test_config.py b/py/test/testing/test_config.py index 5e9dc22dc..bb6505305 100644 --- a/py/test/testing/test_config.py +++ b/py/test/testing/test_config.py @@ -132,7 +132,7 @@ class TestConfigAPI: config = py.test.config._reparse([p]) assert config.getconftest_pathlist('notexist') is None pl = config.getconftest_pathlist('pathlist') - print pl + print(pl) assert len(pl) == 2 assert pl[0] == tmpdir assert pl[1] == somepath @@ -195,7 +195,7 @@ class TestConfigApi_getcolitems: config = py.test.config._reparse([x]) col = config.getfsnode(x) assert isinstance(col, py.test.collect.Directory) - print col.listchain() + print(col.listchain()) assert col.name == 'a' assert col.parent is None assert col.config is config diff --git a/py/test/testing/test_funcargs.py b/py/test/testing/test_funcargs.py index 2b132058d..05e18c3b2 100644 --- a/py/test/testing/test_funcargs.py +++ b/py/test/testing/test_funcargs.py @@ -179,7 +179,7 @@ class TestRequest: ss = item.config._setupstate assert not teardownlist ss.teardown_exact(item) - print ss.stack + print(ss.stack) assert teardownlist == [1] def test_request_addfinalizer_partial_setup_failure(self, testdir): diff --git a/py/test/testing/test_genitems.py b/py/test/testing/test_genitems.py index ebe7a9f6f..4ceea649f 100644 --- a/py/test/testing/test_genitems.py +++ b/py/test/testing/test_genitems.py @@ -58,7 +58,7 @@ class Test_genitems: s = items[0].getmodpath(stopatmodule=False) assert s.endswith("test_example_items1.testone") - print s + print(s) class TestKeywordSelection: @@ -98,7 +98,7 @@ class TestKeywordSelection: for keyword in ('xxx', 'xxx test_2', 'TestClass', 'xxx -test_1', 'TestClass test_2', 'xxx TestClass test_2',): reprec = testdir.inline_run(p.dirpath(), '-s', '-k', keyword) - print "keyword", repr(keyword) + py.builtin.print_("keyword", repr(keyword)) passed, skipped, failed = reprec.listoutcomes() assert len(passed) == 1 assert passed[0].item.name == "test_2" diff --git a/py/test/testing/test_outcome.py b/py/test/testing/test_outcome.py index db65897ee..b2e6e649b 100644 --- a/py/test/testing/test_outcome.py +++ b/py/test/testing/test_outcome.py @@ -32,7 +32,7 @@ def test_importorskip(): py.test.importorskip("hello123", minversion="5.0") """) except Skipped: - print py.code.ExceptionInfo() + print(py.code.ExceptionInfo()) py.test.fail("spurious skip") def test_pytest_exit(): diff --git a/py/test/testing/test_pickling.py b/py/test/testing/test_pickling.py index b0cedc02b..addff0bbc 100644 --- a/py/test/testing/test_pickling.py +++ b/py/test/testing/test_pickling.py @@ -3,11 +3,11 @@ import py def setglobals(request): oldconfig = py.test.config oldcom = py._com.comregistry - print "setting py.test.config to None" + print("setting py.test.config to None") py.test.config = None py._com.comregistry = py._com.Registry() def resetglobals(): - print "setting py.test.config to", oldconfig + py.builtin.print_("setting py.test.config to", oldconfig) py.test.config = oldconfig py._com.comregistry = oldcom request.addfinalizer(resetglobals) diff --git a/py/test/testing/test_pluginmanager.py b/py/test/testing/test_pluginmanager.py index fa19fa4f0..4f321996a 100644 --- a/py/test/testing/test_pluginmanager.py +++ b/py/test/testing/test_pluginmanager.py @@ -169,7 +169,7 @@ class TestPytestPluginInteractions: """) config = Config() config._conftest.importconftest(p) - print config.pluginmanager.getplugins() + print(config.pluginmanager.getplugins()) config.parse([]) assert not config.option.test123 diff --git a/py/test/testing/test_session.py b/py/test/testing/test_session.py index 14df412fd..6952ca48f 100644 --- a/py/test/testing/test_session.py +++ b/py/test/testing/test_session.py @@ -57,7 +57,7 @@ class SessionTests: assert len(failed) == 1 out = failed[0].longrepr.reprcrash.message if not out.find("DID NOT RAISE") != -1: - print out + print(out) py.test.fail("incorrect raises() output") def test_generator_yields_None(self, testdir): diff --git a/py/thread/pool.py b/py/thread/pool.py index fad69ed01..a84579891 100644 --- a/py/thread/pool.py +++ b/py/thread/pool.py @@ -2,6 +2,7 @@ import Queue import threading import time import sys +import py ERRORMARKER = object() @@ -52,7 +53,7 @@ class Reply(object): if result is ERRORMARKER: self._queue = None excinfo = self._excinfo - raise excinfo[0], excinfo[1], excinfo[2] + py.builtin._reraise(excinfo[0], excinfo[1], excinfo[2]) return result class WorkerThread(threading.Thread): diff --git a/py/thread/testing/test_io.py b/py/thread/testing/test_io.py index dd33bdffb..0ed9feb9a 100644 --- a/py/thread/testing/test_io.py +++ b/py/thread/testing/test_io.py @@ -17,7 +17,7 @@ class TestThreadOut: try: l = [] out.setwritefunc(l.append) - print 42,13, + py.builtin.print_(42,13) x = l.pop(0) assert x == '42' x = l.pop(0) @@ -34,9 +34,9 @@ class TestThreadOut: defaults = [] def f(l): out.setwritefunc(l.append) - print id(l), + print(id(l)) out.delwritefunc() - print 1 + print(1) out.setdefaultwriter(defaults.append) pool = WorkerPool() listlist = [] @@ -46,7 +46,7 @@ class TestThreadOut: pool.dispatch(f, l) pool.shutdown() for name, value in out.__dict__.items(): - print >>sys.stderr, "%s: %s" %(name, value) + sys.stderr.write("%s: %s\n" %(name, value)) pool.join(2.0) for i in range(num): item = listlist[i] diff --git a/py/thread/testing/test_pool.py b/py/thread/testing/test_pool.py index 5c94e14a6..101a7e59b 100644 --- a/py/thread/testing/test_pool.py +++ b/py/thread/testing/test_pool.py @@ -88,6 +88,6 @@ def test_pool_clean_shutdown(): assert not pool._alive assert not pool._ready out, err = capture.reset() - print out - print >>sys.stderr, err + print(out) + sys.stderr.write(err + "\n") assert err == '' diff --git a/py/xmlobj/html.py b/py/xmlobj/html.py index 6e867b06a..a1a1ec66a 100644 --- a/py/xmlobj/html.py +++ b/py/xmlobj/html.py @@ -28,11 +28,16 @@ class HtmlVisitor(SimpleUnicodeVisitor): def _isinline(self, tagname): return tagname in self.inline +if sys.version_info > (3, 0): + def u(s): return s +else: + def u(s): return unicode(s) + class HtmlTag(Tag): def unicode(self, indent=2): l = [] HtmlVisitor(l.append, indent, shortempty=False).visit(self) - return u"".join(l) + return u("").join(l) # exported plain html namespace class html(Namespace): diff --git a/py/xmlobj/misc.py b/py/xmlobj/misc.py index d3b804740..358910a0f 100644 --- a/py/xmlobj/misc.py +++ b/py/xmlobj/misc.py @@ -1,11 +1,20 @@ import re +import sys + +if sys.version_info > (3, 0): + def u(s): + return s +else: + def u(s): + return unicode(s) + class _escape: def __init__(self): self.escape = { - u'"' : u'"', u'<' : u'<', u'>' : u'>', - u'&' : u'&', u"'" : u''', + u('"') : u('"'), u('<') : u('<'), u('>') : u('>'), + u('&') : u('&'), u("'") : u('''), } - self.charef_rex = re.compile(u"|".join(self.escape.keys())) + self.charef_rex = re.compile(u("|").join(self.escape.keys())) def _replacer(self, match): return self.escape[match.group(0)] diff --git a/py/xmlobj/visit.py b/py/xmlobj/visit.py index 2b48cae23..bff64bdac 100644 --- a/py/xmlobj/visit.py +++ b/py/xmlobj/visit.py @@ -2,8 +2,16 @@ # a generic conversion serializer # +import sys from py.xml import escape +if sys.version_info > (3, 0): + def u(s): + return s +else: + def u(s): + return unicode(s) + class SimpleUnicodeVisitor(object): """ recursive visitor to write unicode. """ def __init__(self, write, indent=0, curindent=0, shortempty=True): @@ -51,21 +59,21 @@ class SimpleUnicodeVisitor(object): self.visited[id(tag)] = 1 tagname = getattr(tag, 'xmlname', tag.__class__.__name__) if self.curindent and not self._isinline(tagname): - self.write("\n" + u' ' * self.curindent) + self.write("\n" + u(' ') * self.curindent) if tag: self.curindent += self.indent - self.write(u'<%s%s>' % (tagname, self.attributes(tag))) + self.write(u('<%s%s>') % (tagname, self.attributes(tag))) self.parents.append(tag) map(self.visit, tag) self.parents.pop() - self.write(u'' % tagname) + self.write(u('') % tagname) self.curindent -= self.indent else: nameattr = tagname+self.attributes(tag) if self._issingleton(tagname): - self.write(u'<%s/>' % (nameattr,)) + self.write(u('<%s/>') % (nameattr,)) else: - self.write(u'<%s>' % (nameattr, tagname)) + self.write(u('<%s>') % (nameattr, tagname)) def attributes(self, tag): # serialize attributes @@ -77,14 +85,14 @@ class SimpleUnicodeVisitor(object): if res is not None: l.append(res) l.extend(self.getstyle(tag)) - return u"".join(l) + return u("").join(l) def repr_attribute(self, attrs, name): if name[:2] != '__': value = getattr(attrs, name) if name.endswith('_'): name = name[:-1] - return u' %s="%s"' % (name, escape(unicode(value))) + return u(' %s="%s"') % (name, escape(unicode(value))) def getstyle(self, tag): """ return attribute list suitable for styling. """ @@ -94,7 +102,7 @@ class SimpleUnicodeVisitor(object): return [] else: stylelist = [x+': ' + y for x,y in styledict.items()] - return [u' style="%s"' % u'; '.join(stylelist)] + return [u(' style="%s"') % u('; ').join(stylelist)] def _issingleton(self, tagname): """can (and will) be overridden in subclasses""" diff --git a/py/xmlobj/xml.py b/py/xmlobj/xml.py index 902620b03..1aa970538 100644 --- a/py/xmlobj/xml.py +++ b/py/xmlobj/xml.py @@ -18,7 +18,7 @@ class Tag(list): from py.__.xmlobj.visit import SimpleUnicodeVisitor l = [] SimpleUnicodeVisitor(l.append, indent).visit(self) - return u"".join(l) + return "".join(l) def __repr__(self): name = self.__class__.__name__