## Copyright(C) 2008 Gareth Nelson## This code is made available under the GNU General Public License# version 2 or any other licensing terms which the author grants# in writing.## This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## A gloriously simple Erlang port in pythonimport sysimport structimport threaddef default_handler(msg): sys.stderr.write('Got a message from erlang! w00t! ' + str(msg) + '\n')class ErlangPort: def __init__(self): self.handler = default_handler self.running = True def read_msg(self): size_buf = sys.stdin.read(2) if len(size_buf)==2: (pack_len,) = struct.unpack('!h',size_buf) return sys.stdin.read(pack_len) else: return None def send_msg(self,msg_data): size_buf = struct.pack('!h',len(msg_data)) sys.stdout.write(size_buf) sys.stdout.write(msg_data) def start(self): self.recv_thread = thread.start_new_thread(self.recv_loop,()) def recv_loop(self): while self.running: msg = None try: msg = self.read_msg() except Exception,e: print str(e) if not (msg==None): self.default_handler(msg)