1. Victor Stinner
  2. python-ptrace

Commits

Victor Stinner  committed 5205c9a

Experimental support of Python 3 in the same code base

Drop support of Python 2.5

  • Participants
  • Parent commits e4197d0
  • Branches default

Comments (0)

Files changed (26)

File ChangeLog

View file
 python-ptrace 0.7
 -----------------
 
+ * Experimental support of Python 3 in the same code base
+ * Drop support of Python 2.5
+
 python-ptrace 0.6.6 (2013-12-16)
 --------------------------------
 

File examples/itrace.py

View file
         syscall_limit = self.options.syscall_limit
         i = 0
         while i < syscall_limit or syscall_limit is None:
-            print i
+            print(i)
             i += 1
             process.syscall()
             self.debugger.waitSyscall()
         i = 0
         while self.debugger:
             eip = process.getInstrPointer()
-            print i, process.pid, "[%08x]" % eip
+            print(i, process.pid, "[%08x]" % eip)
             i += 1
             process.singleStep()
             event = self.debugger.waitProcessEvent()
             if isinstance(event, ProcessExit):
-                print "process exit"
+                print("process exit")
                 return
             if (isinstance(event, ProcessSignal) and
                 event.signum & ~128 != signal.SIGTRAP):
-                print "died with signal %i" % event.signum
+                print("died with signal %i" % event.signum)
                 return
 
 if __name__ == "__main__":

File examples/simple_dbg.py

View file
 
 def playWithProcess(process):
     # Do anything you want with the process here...
-    print "Dump process registers"
+    print("Dump process registers")
     process.dumpRegs()
-    print "Continue process execution"
+    print("Continue process execution")
     process.cont()
-    print "Wait next process event..."
+    print("Wait next process event...")
     event = process.waitEvent()
-    print "New process event: %s" % event
+    print("New process event: %s" % event)
 
 def traceProgram(arguments):
     # Copy the environment variables
 def main():
     # Check the command line
     if len(argv) < 2:
-        print >>stderr, "usage: %s program [arg1 arg2 ...]" % argv[0]
-        print >>stderr, "   or: %s pid" % argv[0]
+        print("usage: %s program [arg1 arg2 ...]" % argv[0], file=stderr)
+        print("   or: %s pid" % argv[0], file=stderr)
         exit(1)
 
     # Get the process identifier

File gdb.py

View file
 #!/usr/bin/env python
+from __future__ import print_function
 from ptrace import PtraceError
 from ptrace.debugger import (PtraceDebugger, Application,
     ProcessExit, NewProcessEvent, ProcessSignal,
 from ptrace.debugger import ChildError
 from ptrace.debugger.memory_mapping import readProcessMappings
 from ptrace.os_tools import RUNNING_PYTHON3
+try:
+    unichr
+    raw_input
+except NameError:
+    # Python 3
+    unichr = chr
+    raw_input = input
 
 import re
 try:
         self.followterms.append(term)
 
     def showFollowTerms(self):
-        print self.followterms
+        print(self.followterms)
 
     def _xray(self):
         for term in self.followterms:
         for process, procmap, address, term in self._xray():
             pointers = " ".join(formatAddress(ptr_addr)
                 for ptr_addr in getPointers(process, address))
-            print "term[%s] pid[%i] %s %s pointers: %s" % (
+            print("term[%s] pid[%i] %s %s pointers: %s" % (
                 repr(term), process.pid, procmap,
                 formatAddress(address),
-                pointers)
+                pointers))
 
     def execute(self, command):
         errmsg = None
         else:
             errmsg = "Unknown command: %r" % command
         if errmsg:
-            print >>stderr, errmsg
+            print(errmsg, file=stderr)
             return False
         return True
 
             pass
         try:
             return self.parseInteger(command)
-        except ValueError, err:
+        except ValueError as err:
             raise ValueError("Invalid signal number: %r" % command)
 
     def signal(self, command):
         try:
             signum = self.parseSignum(command)
-        except ValueError, err:
+        except ValueError as err:
             return str(err)
         last_process = self.process
         try:
     def print_(self, command):
         try:
             value = self.parseInteger(command)
-        except ValueError, err:
+        except ValueError as err:
             return str(err)
         error("Decimal: %s" % value)
         error("Hexadecimal: %s" % formatWordHex(value))
                 if end_address <= start_address:
                     raise ValueError('End address (%s) is smaller than start address(%s)!'
                         % (formatAddress(end_address), formatAddress(start_address)))
-            except ValueError, err:
+            except ValueError as err:
                 return str(err)
             size = end_address - start_address
             max_size = width*max_line
         else:
             try:
                 start_address = self.parseInteger(command)
-            except ValueError, err:
+            except ValueError as err:
                 return str(err)
             end_address = start_address + 5*width
 
 
                 # Format bytes
                 hexa = formatHexa(memory)
-                hexa = hexa.ljust(width*3-1, u' ')
+                hexa = hexa.ljust(width*3-1, ' ')
 
                 ascii = formatAscii(memory)
-                ascii = ascii.ljust(width, u' ')
+                ascii = ascii.ljust(width, ' ')
 
                 # Display previous read error, if any
                 if read_error:
                     read_error = None
 
                 # Display line
-                error(u"%s| %s| %s" % (formatAddress(address), hexa, ascii))
+                error("%s| %s| %s" % (formatAddress(address), hexa, ascii))
             except PtraceError:
                 if not read_error:
                     read_error = [address, address + size]
         stop = None
         try:
             values = self.parseIntegers(command)
-        except ValueError, err:
+        except ValueError as err:
             return str(err)
         if 1 <= len(values):
             start = values[0]
             if not key.startswith("$"):
                 return 'Register name (%s) have to start with "$"' % key
             key = key[1:]
-        except ValueError, err:
+        except ValueError as err:
              return "Invalid command: %r" % command
         try:
             value = self.parseInteger(value)
-        except ValueError, err:
+        except ValueError as err:
             return str(err)
         try:
             self.process.setreg(key, value)
-        except ProcessError, err:
+        except ProcessError as err:
             return "Unable to set $%s=%s: %s" % (key, value, err)
         error("Set $%s to %s" % (key, value))
         return None
                     prefix, formatAddress(instr.address), instr.text))
             else:
                 self.process.dumpCode()
-        except PtraceError, err:
+        except PtraceError as err:
             error("Unable to read current instruction: %s" % err)
 
     def attachProcess(self, text):
         try:
             pid = self.parseInteger(text)
-        except ValueError, err:
+        except ValueError as err:
              return str(err)
         process = self.debugger.addProcess(pid, False)
         self.switchProcess(process)
     def until(self, command):
         try:
             address = self.parseInteger(command)
-        except ValueError, err:
+        except ValueError as err:
              return str(err)
         errmsg = self.step(False, address)
         if errmsg:
             return
         try:
             pid = self.parseInteger(command)
-        except ValueError, err:
+        except ValueError as err:
              return str(err)
         try:
             process = self.debugger[pid]
 
     def nextProcess(self):
         try:
-            process = iter(self.debugger).next()
+            process = next(iter(self.debugger))
             self.switchProcess(process)
         except StopIteration:
             pass
     def displayBreakpoints(self):
         found = False
         for process in self.debugger:
-            for bp in process.breakpoints.itervalues():
+            for bp in process.breakpoints.values():
                 found = True
                 error("%s:%s" % (process, bp))
         if not found:
             error("(no breakpoint)")
 
     def displaySignals(self):
-        signals = SIGNAMES.items()
-        signals.sort(key=lambda (key, value): key)
+        signals = list(SIGNAMES.items())
+        signals.sort(key=lambda key_value: key_value[0])
         for signum, name in signals:
             error("% 2s: %s" % (signum, name))
 
             # Get address and size of instruction at specified address
             instr = self.process.disassembleOne(address)
             return instr.size
-        except PtraceError, err:
+        except PtraceError as err:
             warning("Warning: Unable to read instruction size at %s: %s" % (
                 formatAddress(address), err))
             return default_size
     def breakpoint(self, command):
         try:
             address = self.parseInteger(command)
-        except ValueError, err:
+        except ValueError as err:
             return str(err)
 
         # Create breakpoint
         size = self.readInstrSize(address)
         try:
             bp = self.process.createBreakpoint(address, size)
-        except PtraceError, err:
+        except PtraceError as err:
             return "Unable to set breakpoint at %s: %s" % (
                 formatAddress(address), err)
         error("New breakpoint: %s" % bp)
     def delete(self, command):
         try:
             address = self.parseInteger(command)
-        except ValueError, err:
+        except ValueError as err:
             return str(err)
 
         breakpoint = self.process.findBreakpoint(address)
             info("Wait %s interruption" % process)
             try:
                 process.waitSignals(SIGINT)
-            except ProcessSignal, event:
+            except ProcessSignal as event:
                 event.display()
             except KeyboardInterrupt:
                 pass
             self.restoreTerminal()
             command = raw_input(self.invite).strip()
         except EOFError:
-            print
+            print()
             return True
         except KeyboardInterrupt:
             error("User interrupt!")
                 command = command.strip()
                 try:
                     ok &= self.execute(command)
-                except Exception, err:
-                    print "Command error: %s" % err
+                except Exception as err:
+                    print("Command error: %s" % err)
                     ok = False
                 if not ok:
                     break
                 self.previous_command = command_str
         except KeyboardInterrupt:
             self.interrupt()
-        except NewProcessEvent, event:
+        except NewProcessEvent as event:
             self.newProcess(event)
-        except ProcessSignal, event:
+        except ProcessSignal as event:
             self.processSignal(event)
-        except ProcessExit, event:
+        except ProcessExit as event:
             error(event)
             self.nextProcess()
-        except ProcessExecution, event:
+        except ProcessExecution as event:
             self.processExecution(event)
-        except PtraceError, err:
+        except PtraceError as err:
             error("ERROR: %s" % err)
             if err.errno == ESRCH:
                 self.deleteProcess(err.pid)
         # Create new process
         try:
             self.process = self.createProcess()
-        except ChildError, err:
+        except ChildError as err:
             writeError(getLogger(), err, "Unable to create child process")
             return
         if not self.process:
             self.runDebugger()
         except KeyboardInterrupt:
             error("Interrupt debugger: quit!")
-        except PTRACE_ERRORS, err:
+        except PTRACE_ERRORS as err:
             writeError(getLogger(), err, "Debugger error")
         self.process = None
         self.debugger.quit()

File ptrace/binding/func.py

View file
     if HAS_CPTRACE:
         try:
             result = _ptrace(command, pid, arg1, arg2)
-        except ValueError, errobj:
+        except ValueError as errobj:
             message = str(errobj)
             errno = get_errno()
             raise PtraceError(message, errno=errno, pid=pid)

File ptrace/ctypes_errno.py

View file
         """
         try:
             pythonapi.PyErr_SetFromErrno(py_object(OSError))
-        except OSError, err:
+        except OSError as err:
             return err.errno
         else:
             raise RuntimeError("get_errno() is unable to get error code")

File ptrace/debugger/application.py

View file
+from __future__ import print_function
 from optparse import OptionGroup
 from logging import (getLogger, StreamHandler,
     DEBUG, INFO, WARNING, ERROR)
             try:
                 self.debugger.traceFork()
             except DebuggerError:
-                print >>stderr, "ERROR: --fork option is not supported by your OS, sorry!"
+                print("ERROR: --fork option is not supported by your OS, sorry!", file=stderr)
                 exit(1)
         if self.options.trace_exec:
             self.debugger.traceExec()
             is_attached = True
         try:
             return self.debugger.addProcess(pid, is_attached=is_attached)
-        except (ProcessExit, PtraceError), err:
+        except (ProcessExit, PtraceError) as err:
             if isinstance(err, PtraceError) \
             and err.errno == EPERM:
                 error("ERROR: You are not allowed to trace process %s (permission denied or process already traced)" % pid)

File ptrace/debugger/child.py

View file
     while True:
         try:
             return waitpid(pid, options)
-        except OSError, e:
+        except OSError as e:
             if e.errno == EINTR:
                 continue
             else:
     while True:
         try:
             return read(fd, buffersize)
-        except OSError, e:
+        except OSError as e:
             if e.errno == EINTR:
                 continue
             else:
     while True:
         try:
             return write(fd, s)
-        except OSError, e:
+        except OSError as e:
             if e.errno == EINTR:
                 continue
             else:
     # Child code
     try:
         ptrace_traceme()
-    except PtraceError, err:
+    except PtraceError as err:
         raise ChildError(str(err))
 
     # Close all files except 0, 1, 2 and errpipe_write
-    for fd in xrange(3, MAXFD):
+    for fd in range(3, MAXFD):
         if fd == errpipe_write:
             continue
         try:
             dup2(null.fileno(), 1)
             dup2(1, 2)
             null.close()
-        except IOError, err:
+        except IOError as err:
             close(2)
             close(1)
     try:
             execve(arguments[0], arguments, env)
         else:
             execv(arguments[0], arguments)
-    except Exception, err:
+    except Exception as err:
         raise ChildError(str(err))
 
 def createChild(arguments, no_stdout, env=None):

File ptrace/debugger/debugger.py

View file
                 "User interrupt! Force the process %s attach "
                 "(don't wait for signals)."
                 % pid)
-        except ProcessSignal, event:
+        except ProcessSignal as event:
             event.display()
         except:
             process.is_attached = False
         while not process:
             try:
                 pid, status = self._waitpid(wanted_pid, blocking)
-            except OSError, err:
+            except OSError as err:
                 if err.errno == ECHILD:
                     process = self.dict[wanted_pid]
                     return process.processTerminated()

File ptrace/debugger/memory_mapping.py

View file
         return maps
     try:
         mapsfile = openProc("%s/maps" % process.pid)
-    except ProcError, err:
+    except ProcError as err:
         raise ProcessError(process, "Unable to read process maps: %s" % err)
     try:
         for line in mapsfile:

File ptrace/debugger/process.py

View file
     from ptrace.binding import ptrace_getregs
 else:
     from ptrace.binding import ptrace_peekuser, ptrace_registers_t
-from ptrace.os_tools import HAS_PROC, RUNNING_BSD
+from ptrace.os_tools import HAS_PROC, RUNNING_BSD, RUNNING_PYTHON3
 from ptrace.tools import dumpRegs
 from ptrace.cpu_info import CPU_WORD_SIZE, CPU_64BITS
 from ptrace.ctypes_tools import bytes2word, word2bytes, bytes2type, bytes2array
             log = error
         try:
             ip = self.getInstrPointer()
-        except PtraceError, err:
+        except PtraceError as err:
             if start is None:
                 log("Unable to read instruction pointer: %s" % err)
                 return
 
         try:
             self._dumpCode(start, stop, ip, manage_bp, log)
-        except PtraceError, err:
+        except PtraceError as err:
             log("Unable to dump code at %s: %s" % (
                 formatAddress(start), err))
 
             else:
                 size = MIN_CODE_SIZE
             code = self.readBytes(start, size)
-            text = " ".join( "%02x" % ord(byte) for byte in code )
+            if RUNNING_PYTHON3:
+                text = " ".join( "%02x" % byte for byte in code )
+            else:
+                text = " ".join( "%02x" % ord(byte) for byte in code )
             log("CODE: %s" % text)
             return
 
         if manage_bp:
             address = start
-            for line in xrange(10):
+            for line in range(10):
                 bp = False
                 if address in self.breakpoints:
                     bytes = self.breakpoints[address].old_bytes
                 self.cont(SIGKILL)
             else:
                 self.kill(SIGKILL)
-        except PtraceError, event:
+        except PtraceError as event:
             if event.errno == ESRCH:
                 done = True
             else:
             # FIXME: Optimize getreg() when used with this function
             words = []
             nb_words = sizeof(ptrace_registers_t) // CPU_WORD_SIZE
-            for offset in xrange(nb_words):
+            for offset in range(nb_words):
                 word = ptrace_peekuser(self.pid, offset*CPU_WORD_SIZE)
                 bytes = word2bytes(word)
                 words.append(bytes)
                 filename = '/proc/%u/mem' % self.pid
                 try:
                     self.read_mem_file = open(filename, 'rb', 0)
-                except IOError, err:
+                except IOError as err:
                     message = "Unable to open %s: fallback to ptrace implementation" % filename
                     if err.errno != EACCES:
                         error(message)
                 mem = self.read_mem_file
                 mem.seek(address)
                 return mem.read(size)
-            except (IOError, ValueError), err:
+            except (IOError, ValueError) as err:
                 raise ProcessError(self, "readBytes(%s, %s) error: %s" % (
                     formatAddress(address), size, err))
     else:
                 break
             size += chunk_length
             address += chunk_length
-        return ''.join(string), truncated
+        return b''.join(string), truncated
 
     def dumpStack(self, log=None):
         if not log:
     def _dumpStack(self, log):
         sp = self.getStackPointer()
         displayed = 0
-        for index in xrange(-5, 5+1):
+        for index in range(-5, 5+1):
             delta = index * CPU_WORD_SIZE
             try:
                 value = self.readWord(sp + delta)
         try:
             regs = self.getregs()
             dumpRegs(log, regs)
-        except PtraceError, err:
+        except PtraceError as err:
             log("Unable to read registers: %s" % err)
 
     def cont(self, signum=0):
         self.debugger.waitSyscall(self)
 
     def findBreakpoint(self, address):
-        for bp in self.breakpoints.itervalues():
+        for bp in self.breakpoints.values():
             if bp.address <= address < bp.address + bp.size:
                 return bp
         return None

File ptrace/debugger/ptrace_signal.py

View file
         return None
     try:
         return parseExpression(process, expr)
-    except ValueError, err:
-        print "err: %s" % err
+    except ValueError as err:
+        print("err: %s" % err)
         return None
 
 class ProcessSignal(ProcessEvent):

File ptrace/debugger/signal_reason.py

View file
         try:
             value = process.getreg(name)
             registers[name] = value
-        except PtraceError, err:
+        except PtraceError as err:
             pass
     return registers
 
             log("- instruction: %s" % self.instr)
         for mapping in self.mappings:
             log("- mapping: %s" % mapping)
-        for name, value in self.registers.iteritems():
+        for name, value in self.registers.items():
             log("- register %s=%s" % (name, formatWordHex(value)))
 
     def displayExtra(self, log):

File ptrace/disasm.py

View file
         else:
             raise ImportError("CPU not supported")
         DISTORM3 = True
-    except ImportError, err:
+    except ImportError as err:
         DISTORM3 = False
         from ptrace.pydistorm import Decode
         if CPU_X86_64:
             else:
                 self.address = instr.offset
                 self.size = instr.size
-                self.hexa = unicode(instr.instructionHex)
-                self.text = u"%s %s" % (instr.mnemonic, instr.operands)
+                self.hexa = str(instr.instructionHex)
+                self.text = "%s %s" % (instr.mnemonic, instr.operands)
 
         def __str__(self):
             return self.text
         raise PtraceError("Unable to disassemble %r" % code)
 
     HAS_DISASSEMBLER = True
-except (ImportError, OSError), err:
+except (ImportError, OSError) as err:
     # OSError if libdistorm64.so doesn't exist
     HAS_DISASSEMBLER = False
 

File ptrace/func_arg.py

View file
                     self.text = formatAddress(self.value)
                 else:
                     self.text = repr(self.value)
-            except PTRACE_ERRORS, err:
+            except PTRACE_ERRORS as err:
                 writeError(getLogger(), err,
                     "Format argument %s of function %s() value error"
                     % (self.name, self.function.name))
                     text = str(text)
                 else:
                     text = repr(value)
-            except PTRACE_ERRORS, err:
+            except PTRACE_ERRORS as err:
                 writeError(getLogger(), err, "Format struct value error")
                 text = repr(value)
             arguments.append("%s=%s" % (name, text))
     def readArray(self, address, basetype, count):
         array = self.function.process.readArray(address, basetype, count)
         arguments = []
-        for index in xrange(count):
+        for index in range(count):
             value = array[index]
             value = str(value)
             arguments.append(value)

File ptrace/linux_proc.py

View file
     filename = "/proc/%s" % path
     try:
         return open(filename)
-    except IOError, err:
+    except IOError as err:
         raise ProcError("Unable to open %r: %s" % (filename, err))
 
 def readProc(path):
         filename = "/proc/%s/%s" % (pid, key)
         with open(filename) as proc:
             return proc.read()
-    except IOError, err:
+    except IOError as err:
         raise ProcError("Process %s doesn't exist: %s" % (pid, err))
 
 class ProcessState(object):
     try:
         filename = "/proc/%s/%s" % (pid, key)
         return readlink(filename)
-    except OSError, err:
+    except OSError as err:
         raise ProcError("Unable to read proc link %r: %s" % (filename, err))
 
 def readProcesses():

File ptrace/profiler.py

View file
 from hotshot import Profile
 from hotshot.stats import load as loadStats
 from os import unlink
-try:
-    from cStringIO import StringIO
-except ImportError:
-    from StringIO import StringIO
+from io import StringIO
 
 def runProfiler(logger, func, args=tuple(), kw={},
 verbose=True, nb_func=25,

File ptrace/pydistorm.py

View file
         # Yield instruction and compute decoded size
         size = 0
         instr_array = cast(result, POINTER(_DecodedInst))
-        for index in xrange(count):
+        for index in range(count):
             instr = instr_array[index]
             size += instr.size
             yield instr

File ptrace/signames.py

View file
         except KeyError:
             allnames[signum] = [name]
     signames = {}
-    for signum, names in allnames.iteritems():
+    for signum, names in allnames.items():
         if not signum:
             # Skip signal 0
             continue

File ptrace/syscall/posix_arg.py

View file
 
 # From /usr/include/bits/fcntl.h (Ubuntu Feisty, i386)
 OPEN_MODE_BITMASK = (
-    (01, "O_WRONLY"),
-    (02, "O_RDWR"),
-    (0100, "O_CREAT"),
-    (0200, "O_EXCL"),
-    (0400, "O_NOCTTY"),
-    (01000, "O_TRUNC"),
-    (02000, "O_APPEND"),
-    (04000, "O_NONBLOCK"),
-    (010000, "O_SYNC"),
-    (020000, "O_ASYNC"),
-    (040000, "O_DIRECT"),
-    (0100000, "O_LARGEFILE"),
-    (0200000, "O_DIRECTORY"),
-    (0400000, "O_NOFOLLOW"),
-    (01000000, "O_NOATIME"),
+    (0o1, "O_WRONLY"),
+    (0o2, "O_RDWR"),
+    (0o100, "O_CREAT"),
+    (0o200, "O_EXCL"),
+    (0o400, "O_NOCTTY"),
+    (0o1000, "O_TRUNC"),
+    (0o2000, "O_APPEND"),
+    (0o4000, "O_NONBLOCK"),
+    (0o10000, "O_SYNC"),
+    (0o20000, "O_ASYNC"),
+    (0o40000, "O_DIRECT"),
+    (0o100000, "O_LARGEFILE"),
+    (0o200000, "O_DIRECTORY"),
+    (0o400000, "O_NOFOLLOW"),
+    (0o1000000, "O_NOATIME"),
 )
 
 def formatOpenMode(argument):

File ptrace/syscall/prototypes.py

View file
         )),
 }
 
-for orig, copies in ALIASES.iteritems():
+for orig, copies in ALIASES.items():
     orig = SYSCALL_PROTOTYPES[orig]
     for copy in copies:
         SYSCALL_PROTOTYPES[copy] = orig

File ptrace/syscall/ptrace_syscall.py

View file
 from os import strerror
-from itertools import izip
+
 from ptrace.cpu_info import CPU_X86_64, CPU_POWERPC, CPU_I386
 from ptrace.ctypes_tools import ulong2long, formatAddress, formatWordHex
 from ptrace.func_call import FunctionCall
         if RUNNING_BSD:
             sp = self.process.getStackPointer()
             return [ self.process.readWord(sp + index*CPU_WORD_SIZE)
-                for index in xrange(1, 6+1) ]
+                for index in range(1, 6+1) ]
         if CPU_I386:
             return (regs.ebx, regs.ecx, regs.edx, regs.esi, regs.edi, regs.ebp)
         if CPU_POWERPC:
     def readArguments(self, argument_values):
         if self.name in SYSCALL_PROTOTYPES:
             self.restype, formats = SYSCALL_PROTOTYPES[self.name]
-            for value, format in izip(argument_values, formats):
+            for value, format in zip(argument_values, formats):
                 argtype, argname = format
                 self.addArgument(value=value, name=argname, type=argtype)
         else:

File ptrace/syscall/syscall_argument.py

View file
 def iterBits(data):
     for char in data:
         byte = ord(char)
-        for index in xrange(8):
+        for index in range(8):
             yield ((byte >> index) & 1) == 1
 
 class SyscallArgument(FunctionArgument):
                 text = self.formatValuePointer(argtype[:-1])
                 if text:
                     return text
-            except PTRACE_ERRORS, err:
+            except PTRACE_ERRORS as err:
                 writeError(getLogger(), err, "Warning: Format %r value error" % self, log_level=INFO)
             return formatAddress(self.value)
 

File ptrace/tools.py

View file
     {32: '0x20', 16: '0x10'}
     """
     result = {}
-    for key, value in data.iteritems():
+    for key, value in data.items():
         result[value] = key
     return result
 

File setup.py

View file
     "long_description": LONG_DESCRIPTION,
     "classifiers": CLASSIFIERS,
     "license": ptrace.LICENSE,
-    "packages": PACKAGES.keys(),
+    "packages": list(PACKAGES.keys()),
     "package_dir": PACKAGES,
     "scripts": SCRIPTS,
 }

File strace.py

View file
 #!/usr/bin/env python
+from __future__ import print_function
 from ptrace import PtraceError
 from ptrace.debugger import (PtraceDebugger, Application,
     ProcessExit, ProcessSignal, NewProcessEvent, ProcessExecution)
         self.options, self.program = parser.parse_args()
 
         if self.options.list_syscalls:
-            syscalls = SYSCALL_NAMES.items()
+            syscalls = list(SYSCALL_NAMES.items())
             syscalls.sort(key=lambda data: data[0])
             for num, name in syscalls:
-                print "% 3s: %s" % (num, name)
+                print("% 3s: %s" % (num, name))
             exit(0)
 
         if self.options.pid is None and not self.program:
                 if not item or item in only:
                     continue
                 ok = True
-                valid_names = SYSCALL_NAMES.values()
+                valid_names = list(SYSCALL_NAMES.values())
                 for name in only:
                     if name not in valid_names:
-                        print >>stderr, "ERROR: unknow syscall %r" % name
+                        print("ERROR: unknow syscall %r" % name, file=stderr)
                         ok = False
                 if not ok:
-                    print >>stderr
-                    print >>stderr, "Use --list-syscalls options to get system calls list"
+                    print(file=stderr)
+                    print("Use --list-syscalls options to get system calls list", file=stderr)
                     exit(1)
                 # remove duplicates
                 only.add(item)
         if self.options.filename:
-            for syscall, format in SYSCALL_PROTOTYPES.iteritems():
+            for syscall, format in SYSCALL_PROTOTYPES.items():
                 restype, arguments = format
                 if any(argname in FILENAME_ARGUMENTS for argtype, argname in arguments):
                     only.add(syscall)
         if self.options.ignore_regex:
             try:
                 self.ignore_regex = re.compile(self.options.ignore_regex)
-            except Exception, err:
-                print "Invalid regular expression! %s" % err
-                print "(regex: %r)" % self.options.ignore_regex
+            except Exception as err:
+                print("Invalid regular expression! %s" % err)
+                print("(regex: %r)" % self.options.ignore_regex)
                 exit(1)
         else:
             self.ignore_regex = None
             try:
                 event = self.debugger.waitSyscall()
                 process = event.process
-            except ProcessExit, event:
+            except ProcessExit as event:
                 self.processExited(event)
                 continue
-            except ProcessSignal, event:
+            except ProcessSignal as event:
                 event.display()
                 process.syscall(event.signum)
                 continue
-            except NewProcessEvent, event:
+            except NewProcessEvent as event:
                 self.newProcess(event)
                 continue
-            except ProcessExecution, event:
+            except ProcessExecution as event:
                 self.processExecution(event)
                 continue
 
         self.debugger = PtraceDebugger()
         try:
             self.runDebugger()
-        except ProcessExit, event:
+        except ProcessExit as event:
             self.processExited(event)
-        except PtraceError, err:
+        except PtraceError as err:
             error("ptrace() error: %s" % err)
         except KeyboardInterrupt:
             error("Interrupted.")
-        except PTRACE_ERRORS, err:
+        except PTRACE_ERRORS as err:
             writeError(getLogger(), err, "Debugger error")
         self.debugger.quit()