inpipe and outpipe (and other useful functions)

Discussion in 'Python' started by Ole Martin Bjørndalen, Aug 28, 2011.

  1. 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/
    Ole Martin Bjørndalen, Aug 28, 2011
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Nick Jacobson

    Useful? __slots__ for functions

    Nick Jacobson, May 25, 2004, in forum: Python
    Replies:
    3
    Views:
    276
    A. Lloyd Flanagan
    May 26, 2004
  2. MJL
    Replies:
    2
    Views:
    283
    Gordon Burditt
    Aug 15, 2004
  3. J. Romano
    Replies:
    18
    Views:
    220
    J. Romano
    Jul 13, 2004
  4. Leif
    Replies:
    3
    Views:
    211
  5. George Mpouras

    two useful windows functions

    George Mpouras, Apr 4, 2014, in forum: Perl Misc
    Replies:
    0
    Views:
    127
    George Mpouras
    Apr 4, 2014
Loading...

Share This Page