inpipe and outpipe (and other useful functions)

Ole Martin Bjørndalen ombdalen at gmail.com
Sun Aug 28 06:19:54 EDT 2011


Hi!

Please excuse me if this i common knowledge, or if I've one again
re-implemented something
that turned out to be in the standard library, but I think I came up
with something rather neat.

I'm writing a lot of programs that call external programs, and as much
as I love subproces.Popen, I do get tired of writing
rather wordy things like:

   args = ['cmd', 'arg1', 'arg2', 'etc']
   p = subprocess.Popen(args, stdin=subprocess.PIPE)
   for line in p:
          line = line.decode('latin1')
          do_something_with(line)

Bleh.

so last week I had enough, and I sat down and wrote a few functions.
No I can do:

    from lib import inpipe

    for line in inpipe(args, encoding='latin1'):
        do_something_with(line)

and

    from lib import outpipe

    with outpipe(args, addnl=True) as write:
        write('Python is awesome!')
        write('')

Some code from a program I'm writing:

    args = ['metaflac',
               '--show-total-samples',
               '--show-sample-rate',
               file]

    for line in stripped(inpipe(args)):
        (name, value) = line.split('=')
        # ... process tag

Now, that is a lot more readable than what I had before!

The library has a lot of other things in it as well, and is available here:

    https://github.com/olemb/lib

I love Python!


-- 
Ole Martin,
http://nerdly.info/ole/



More information about the Python-list mailing list