Python processing of an input byte stream

Quinn Dunkan quinn at chunder.ugcs.caltech.edu
Mon Oct 30 18:29:39 EST 2000


On Mon, 30 Oct 2000 21:23:47 GMT, apighin at my-deja.com <apighin at my-deja.com>
wrote:
>First off, I have to admit that I am entirely new
>to Python.  I had been looking at possible ways
>of approaching a task (to be outlined soon) and
>had more or less settled on Perl, when it was
>suggested: 'NO! Python, Python, Python! It's MUCH
>better.'  So here I am, eliciting help.
>
>Here is what I am trying to accomplish:  I am
>trying to do processing on an incoming byte
>stream, according to a template.  The template
>would, in my mind (but not necessarily) be
>something similar to the 'printf' formatting
>codes for C.  The input byte stream would be
>continuous, so the Python module should expect an
>EOF, similar to running 'tail -f'.
>
>For example, an input byte of '0x1' might
>translate to 'Function (main) initialized'.  An
>input byte might translate to 'A key was pressed,
>that key was ?' where ? would come from the next
>byte in the stream.  This means that the routine
>would need to have an understanding that some
>mappings have parameters associated, and other do
>not.  This is sort of turning into an FSM.
>
>I took a quick look at Compiling Little Languages
>in Python (John Aycock) from the www.python.org
>Website, and that outlines one possible direction.
>
>I'd really like to know if this is Python's
>forte, if I should look somewhere else (where!?),
>and best of all, if this is already done!
>
>Thanks very much in advance,
>Anthony

import sys, time
ops = {
    0x1 : lambda: 'Function (main) initialized',
    0x2 : lambda a: "Key '%s' was pressed" % a,
    # etc.
}

while 1:
    c = sys.stdin.read(1)
    if not c:
        time.sleep(1)
        continue
    op = ops[c]
    nargs = op.func_code.co_argcount
    args = tuple(sys.stdin.read(nargs))
    print apply(op, args)


There ya go! :)



More information about the Python-list mailing list