inpipe and outpipe (and other useful functions)

  • Thread starter Ole Martin Bjørndalen
  • Start date
O

Ole Martin Bjørndalen

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!
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top