Subject: Re: An exercise for Pythonians, useful to Tclists - DN [1]
Robin Becker <robin@jessikat.demon.co.uk> - 24 Dec 1998 - comp.lang.tcl,comp.lang.python
Happy Yuletide/XMAS/Hnk to all the tclers & pythoneers
Interesting stuff; for the cross-dressers amongst us here is my first nontrivial python
intended as a python command server for tcl
it reads python commands on stdin and processes them into a blocked form on stdout
the response to a command is
#################################################################
# reponse --> <responseheader> <sections>
# responseheader --> <n><i>'\n'
# sections --> [<section>|] <sections>
# section --> <sectionheader> <sectiondata>
# sectionheader --> <s><L>'\n'
# sectiondata --> chars
#
# n --> a single digit count of sections 0 to 4
# i --> an 8 character hex sequence number
# s --> section type
# 1 - normal stdout
# 2 - normal stderr
# 3 - exception stdout
# 4 - exception stderr
# L --> an 8 character sectiondata length
#################################################################
import sys
import copy
import traceback
import string
g=copy.copy(globals())
l=copy.copy(locals())
# this class allows us to divert stdout/err so we can put a tag on the front of IO
class CaptureWriter:
def __init__(self,flag=1):
self.old = None
self.flag = flag
self.clear()
def capture(self):
self.clear()
if self.flag:
self.old = sys.stdout
sys.stdout = self
else:
self.old = sys.stderr
sys.stderr = self
def release(self):
if self.old:
if self.flag:
sys.stdout = self.old
else:
sys.stderr = self.old
self.old = None
def clear(self):
self.captured = []
def write(self, msg):
self.captured.append(msg)
def get_captured(self):
if self.captured==[]:
return None
else:
s = string.join(self.captured,"")
self.clear()
return s
class Buffer:
def __init__(self):
self.buffer=[]
self.sections=0
def add(self,section,msg):
if not msg is None:
self.buffer.append("%c%8.8X\n"%(section,len(msg)))
self.buffer.append(msg)
self.sections=self.sections+1
def flush(self,where):
if self.buffer!=[]:
where.write(string.join(self.buffer,""))
where.flush()
self.__init__()
STDOUT=CaptureWriter()
STDOUT.capture()
STDERR=CaptureWriter(0)
STDERR.capture()
buf=Buffer()
n=0
try:
while 1:
cmd=sys.stdin.readline()
if cmd=="":
try:
sys.stdin.tell()
except IOError:
break
n = n + 1
try:
exec cmd in g,l
buf.add('0',STDOUT.get_captured())
buf.add('1',STDERR.get_captured())
except:
buf.add('0',STDOUT.get_captured())
buf.add('1',STDERR.get_captured())
exec 'traceback.print_exc()' in g,l
buf.add('2',STDOUT.get_captured())
buf.add('3',STDERR.get_captured())
STDOUT.old.write("%1d%8.8X\n"%(buf.sections,n))
buf.flush(STDOUT.old)
#except:
# STDOUT.release()
# STDERR.release()
# print 'error detected'
# traceback.print_exc()
finally:
pass
--
Robin Becker
Last modified
1999-09-27
1999-09-27
(195.108.246.50)
Note: you are looking at
the snapshot of an old wiki
- much of this information
is likely to be very outdated
