Merge branch 'master' into python3
authorFredrik Tolf <fredrik@dolda2000.com>
Sun, 15 Jan 2012 07:06:54 +0000 (08:06 +0100)
committerFredrik Tolf <fredrik@dolda2000.com>
Sun, 15 Jan 2012 07:06:54 +0000 (08:06 +0100)
pdm-repl
pdm/cli.py
pdm/perf.py
pdm/srv.py
setup.py

index daa8c18..c8fe277 100755 (executable)
--- a/pdm-repl
+++ b/pdm-repl
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
 import sys, getopt, readline
 import pdm.cli
@@ -20,9 +20,9 @@ buf = ""
 while True:
     try:
         if buf != "":
-            line = raw_input("  ")
+            line = input("  ")
         else:
-            line = raw_input("% ")
+            line = input("% ")
     except EOFError:
         break
     if line == "":
index 1d83920..272be86 100644 (file)
@@ -64,9 +64,9 @@ class client(object):
         the select() method).
         """
         self.sk = resolve(sk)
-        self.buf = ""
+        self.buf = b""
         line = self.readline()
-        if line != "+PDM1":
+        if line != b"+PDM1":
             raise protoerr("Illegal protocol signature")
         if proto is not None:
             self.select(proto)
@@ -82,23 +82,25 @@ class client(object):
     def readline(self):
         """Read a single NL-terminated line and return it."""
         while True:
-            p = self.buf.find("\n")
+            p = self.buf.find(b"\n")
             if p >= 0:
                 ret = self.buf[:p]
                 self.buf = self.buf[p + 1:]
                 return ret
             ret = self.sk.recv(1024)
-            if ret == "":
+            if ret == b"":
                 return None
             self.buf += ret
 
     def select(self, proto):
         """Negotiate the given subprotocol with the server"""
-        if "\n" in proto:
+        if isinstance(proto, str):
+            proto = proto.encode("ascii")
+        if b"\n" in proto:
             raise Exception("Illegal protocol specified: %r" % proto)
-        self.sk.send(proto + "\n")
+        self.sk.send(proto + b"\n")
         rep = self.readline()
-        if len(rep) < 1 or rep[0] != "+":
+        if len(rep) < 1 or rep[0] != b"+"[0]:
             raise protoerr("Error reply when selecting protocol %s: %s" % (proto, rep[1:]))
 
     def __enter__(self):
@@ -116,7 +118,7 @@ class replclient(client):
     """
     def __init__(self, sk):
         """Create a connected client as documented in the `client' class."""
-        super(replclient, self).__init__(sk, "repl")
+        super().__init__(sk, "repl")
 
     def run(self, code):
         """Run a single block of Python code on the server. Returns
@@ -129,16 +131,16 @@ class replclient(client):
             code = ncode
         while len(code) > 0 and code[-1] == "\n":
             code = code[:-1]
-        self.sk.send(code + "\n\n")
-        buf = ""
+        self.sk.send((code + "\n\n").encode("utf-8"))
+        buf = b""
         while True:
             ln = self.readline()
-            if ln[0] == " ":
-                buf += ln[1:] + "\n"
-            elif ln[0] == "+":
-                return buf
-            elif ln[0] == "-":
-                raise protoerr("Error reply: %s" % ln[1:])
+            if ln[0] == b" "[0]:
+                buf += ln[1:] + b"\n"
+            elif ln[0] == b"+"[0]:
+                return buf.decode("utf-8")
+            elif ln[0] == b"-"[0]:
+                raise protoerr("Error reply: %s" % ln[1:].decode("utf-8"))
             else:
                 raise protoerr("Illegal reply: %s" % ln)
 
@@ -228,7 +230,7 @@ class perfclient(client):
     """
     def __init__(self, sk):
         """Create a connected client as documented in the `client' class."""
-        super(perfclient, self).__init__(sk, "perf")
+        super().__init__(sk, "perf")
         self.nextid = 0
         self.lock = threading.Lock()
         self.proxies = {}
@@ -240,10 +242,10 @@ class perfclient(client):
         self.sk.send(buf)
 
     def recvb(self, num):
-        buf = ""
+        buf = b""
         while len(buf) < num:
             data = self.sk.recv(num - len(buf))
-            if data == "":
+            if data == b"":
                 raise EOFError()
             buf += data
         return buf
index f3a3e70..6a68676 100644 (file)
@@ -63,7 +63,7 @@ class attrinfo(object):
 
 class perfobj(object):
     def __init__(self, *args, **kwargs):
-        super(perfobj, self).__init__()
+        super().__init__()
     
     def pdm_protocols(self):
         return []
@@ -74,7 +74,7 @@ class simpleattr(perfobj):
     read.
     """
     def __init__(self, func, info = None, *args, **kwargs):
-        super(simpleattr, self).__init__(*args, **kwargs)
+        super().__init__(*args, **kwargs)
         self.func = func
         if info is None:
             info = attrinfo()
@@ -87,7 +87,7 @@ class simpleattr(perfobj):
         return self.info
 
     def pdm_protocols(self):
-        return super(simpleattr, self).pdm_protocols() + ["attr"]
+        return super().pdm_protocols() + ["attr"]
 
 class valueattr(perfobj):
     """An implementation of the `attr' interface, which is initialized
@@ -95,7 +95,7 @@ class valueattr(perfobj):
     updates to the value are reflected in subsequent reads.
     """
     def __init__(self, init, info = None, *args, **kwargs):
-        super(valueattr, self).__init__(*args, **kwargs)
+        super().__init__(*args, **kwargs)
         self.value = init
         if info is None:
             info = attrinfo()
@@ -108,7 +108,7 @@ class valueattr(perfobj):
         return self.info
 
     def pdm_protocols(self):
-        return super(valueattr, self).pdm_protocols() + ["attr"]
+        return super().pdm_protocols() + ["attr"]
 
 class eventobj(perfobj):
     """An implementation of the `event' interface. It keeps track of
@@ -116,7 +116,7 @@ class eventobj(perfobj):
     subscribers when submitted with the `notify' method.
     """
     def __init__(self, *args, **kwargs):
-        super(eventobj, self).__init__(*args, **kwargs)
+        super().__init__(*args, **kwargs)
         self.subscribers = set()
 
     def subscribe(self, cb):
@@ -135,7 +135,7 @@ class eventobj(perfobj):
             except: pass
 
     def pdm_protocols(self):
-        return super(eventobj, self).pdm_protocols() + ["event"]
+        return super().pdm_protocols() + ["event"]
 
 class staticdir(perfobj):
     """An implementation of the `dir' interface. Put other PERF
@@ -143,7 +143,7 @@ class staticdir(perfobj):
     return them to requesting clients.
     """
     def __init__(self, *args, **kwargs):
-        super(staticdir, self).__init__(*args, **kwargs)
+        super().__init__(*args, **kwargs)
         self.map = {}
 
     def __setitem__(self, name, ob):
@@ -159,13 +159,13 @@ class staticdir(perfobj):
         return self.map.get(name, default)
 
     def listdir(self):
-        return self.map.keys()
+        return list(self.map.keys())
 
     def lookup(self, name):
         return self.map[name]
 
     def pdm_protocols(self):
-        return super(staticdir, self).pdm_protocols() + ["dir"]
+        return super().pdm_protocols() + ["dir"]
 
 class event(object):
     """This class should be subclassed by all event objects sent via
@@ -209,7 +209,7 @@ class procevent(event):
     `finishevent' emitted when the connection is closed.
     """
     def __init__(self, id):
-        super(procevent, self).__init__()
+        super().__init__()
         if isinstance(id, procevent):
             self.id = id.id
         else:
@@ -218,7 +218,7 @@ class procevent(event):
 class startevent(procevent):
     """A subclass of `procevent'. See its documentation for details."""
     def __init__(self):
-        super(startevent, self).__init__(getprocid())
+        super().__init__(getprocid())
 
 class finishevent(procevent):
     """A subclass of `procevent'. Intended to be emitted when a
@@ -227,7 +227,7 @@ class finishevent(procevent):
     distinction is meaningful. The `start' parameter should be the
     `startevent' instance used when the process was initiated."""
     def __init__(self, start, aborted = False):
-        super(finishevent, self).__init__(start)
+        super().__init__(start)
         self.aborted = aborted
 
 sysres = staticdir()
index 8eb11f5..abf7d89 100644 (file)
@@ -40,33 +40,34 @@ class repl(object):
         self.mod = types.ModuleType("repl")
         self.mod.echo = self.echo
         self.printer = pprint.PrettyPrinter(indent = 4, depth = 6)
-        cl.send("+REPL\n")
+        cl.send(b"+REPL\n")
 
     def sendlines(self, text):
         for line in text.split("\n"):
-            self.cl.send(" " + line + "\n")
+            self.cl.send(b" " + line.encode("utf-8") + b"\n")
 
     def echo(self, ob):
         self.sendlines(self.printer.pformat(ob))
 
     def command(self, cmd):
+        cmd = cmd.decode("utf-8")
         try:
             try:
                 ccode = compile(cmd, "PDM Input", "eval")
             except SyntaxError:
                 ccode = compile(cmd, "PDM Input", "exec")
-                exec ccode in self.mod.__dict__
-                self.cl.send("+OK\n")
+                exec(ccode, self.mod.__dict__)
+                self.cl.send(b"+OK\n")
             else:
                 self.echo(eval(ccode, self.mod.__dict__))
-                self.cl.send("+OK\n")
+                self.cl.send(b"+OK\n")
         except:
             for line in traceback.format_exception(*sys.exc_info()):
-                self.cl.send(" " + line)
-            self.cl.send("+EXC\n")
+                self.cl.send(b" " + line.encode("utf-8"))
+            self.cl.send(b"+EXC\n")
 
     def handle(self, buf):
-        p = buf.find("\n\n")
+        p = buf.find(b"\n\n")
         if p < 0:
             return buf
         cmd = buf[:p + 1]
@@ -169,13 +170,13 @@ class perf(object):
     def __init__(self, cl):
         self.cl = cl
         self.odtab = {}
-        cl.send("+PERF1\n")
+        cl.send(b"+PERF1\n")
         self.buf = ""
         self.lock = threading.Lock()
         self.subscribed = {}
 
     def closed(self):
-        for id, recv in self.subscribed.iteritems():
+        for id, recv in self.subscribed.items():
             ob = self.odtab[id]
             if ob is None: continue
             ob, protos = ob
@@ -197,7 +198,7 @@ class perf(object):
             raise ValueError("Object does not support PDM introspection")
         try:
             proto = ob.pdm_protocols()
-        except Exception, exc:
+        except Exception as exc:
             raise ValueError("PDM introspection failed", exc)
         self.odtab[id] = ob, proto
         return proto
@@ -214,7 +215,7 @@ class perf(object):
             return
         try:
             proto = self.bindob(id, ob)
-        except Exception, exc:
+        except Exception as exc:
             self.send("-", exc)
             return
         self.send("+", proto)
@@ -236,12 +237,12 @@ class perf(object):
             return
         try:
             ob = src.lookup(obnm)
-        except KeyError, exc:
+        except KeyError as exc:
             self.send("-", exc)
             return
         try:
             proto = self.bindob(tgtid, ob)
-        except Exception, exc:
+        except Exception as exc:
             self.send("-", exc)
             return
         self.send("+", proto)
@@ -271,7 +272,7 @@ class perf(object):
             return
         try:
             ret = ob.readattr()
-        except Exception, exc:
+        except Exception as exc:
             self.send("-", Exception("Could not read attribute"))
             return
         self.send("+", ret)
@@ -288,7 +289,7 @@ class perf(object):
             return
         try:
             self.send("+", ob.invoke(method, *args, **kwargs))
-        except Exception, exc:
+        except Exception as exc:
             self.send("-", exc)
 
     def event(self, id, ob, ev):
@@ -354,7 +355,7 @@ protocols["perf"] = perf
 
 class client(threading.Thread):
     def __init__(self, sk):
-        super(client, self).__init__(name = "Management client")
+        super().__init__(name = "Management client")
         self.setDaemon(True)
         self.sk = sk
         self.handler = self
@@ -363,6 +364,10 @@ class client(threading.Thread):
         return self.sk.send(data)
 
     def choose(self, proto):
+        try:
+            proto = proto.decode("ascii")
+        except UnicodeError:
+            proto = None
         if proto in protocols:
             self.handler = protocols[proto](self)
         else:
@@ -370,7 +375,7 @@ class client(threading.Thread):
             raise Exception()
 
     def handle(self, buf):
-        p = buf.find("\n")
+        p = buf.find(b"\n")
         if p >= 0:
             proto = buf[:p]
             buf = buf[p + 1:]
@@ -379,24 +384,24 @@ class client(threading.Thread):
 
     def run(self):
         try:
-            buf = ""
-            self.send("+PDM1\n")
+            buf = b""
+            self.send(b"+PDM1\n")
             while True:
                 ret = self.sk.recv(1024)
-                if ret == "":
+                if ret == b"":
                     return
                 buf += ret
                 while True:
                     try:
                         nbuf = self.handler.handle(buf)
                     except:
+                        #for line in traceback.format_exception(*sys.exc_info()):
+                        #    print(line)
                         return
                     if nbuf == buf:
                         break
                     buf = nbuf
         finally:
-            #for line in traceback.format_exception(*sys.exc_info()):
-            #    print line
             try:
                 self.sk.close()
             finally:
@@ -413,7 +418,7 @@ class listener(threading.Thread):
     tcplistener.
     """
     def __init__(self):
-        super(listener, self).__init__(name = "Management listener")
+        super().__init__(name = "Management listener")
         self.setDaemon(True)
 
     def listen(self, sk):
@@ -441,14 +446,14 @@ class listener(threading.Thread):
 
 class unixlistener(listener):
     """Unix socket listener"""
-    def __init__(self, name, mode = 0600, group = None):
+    def __init__(self, name, mode = 0o600, group = None):
         """Create a listener that will bind to the Unix socket named
         by `name'. The socket will not actually be bound until the
         listener is started. The socket will be chmodded to `mode',
         and if `group' is given, the named group will be set as the
         owner of the socket.
         """
-        super(unixlistener, self).__init__()
+        super().__init__()
         self.name = name
         self.mode = mode
         self.group = group
@@ -478,7 +483,7 @@ class tcplistener(listener):
         the given local interface. The socket will not actually be
         bound until the listener is started.
         """
-        super(tcplistener, self).__init__()
+        super().__init__()
         self.port = port
         self.bindaddr = bindaddr
 
@@ -516,7 +521,7 @@ def listen(spec):
         last = spec
     if "/" in first:
         parts = spec.split(":")
-        mode = 0600
+        mode = 0o600
         group = None
         if len(parts) > 1:
             mode = int(parts[1], 8)
index 9fd505b..eb07e39 100755 (executable)
--- a/setup.py
+++ b/setup.py
@@ -1,8 +1,8 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
 from distutils.core import setup
 
-setup(name = "pdm",
+setup(name = "pdm3",
       version = "0.2",
       description = "Python daemon management library",
       author = "Fredrik Tolf",