Skip to main content

Python: sort | uniq -c via the subprocess module

Here is "sort | uniq -c" pieced together using the subprocess module:
from subprocess import Popen, PIPE

p1 = Popen(["sort"], stdin=PIPE, stdout=PIPE)
p1.stdin.write('FOO\nBAR\nBAR\n')
p1.stdin.close()
p2 = Popen(["uniq", "-c"], stdin=p1.stdout, stdout=PIPE)
for line in p2.stdout:
print line.rstrip()
Note, I'm not bothering to check the exit status. You can see my previous post about how to do that.

Now, here's the question. Why does the program freeze if I put the two Popen lines together? I don't understand why I can't setup the pipeline, then feed it data, then close the stdin, and then read the result.

Comments

Unknown said…
I don't know why putting the Popens together causes it to lock up, but this:

p1 = Popen(["sort"], stdin=PIPE, stdout=PIPE)
p1.stdin.write('FOO\nBAR\nBAR\n')
p1.stdin.close()

Will only work for large writes because sort happens to be a "sponge", i.e. sucks up all its input before emitting any output.

If it were a filter it could block waiting for a reader, which would block you (the writer) once the pipe's buffer filled.

I usually spawn a thread for the input end of a pipeline for this reason.
The reason it hangs if you put the popen calls together is that it changes the relative ordering of the 2nd popen and the p1.stdin.close() call. In the working version you posted, p1.stdin is closed, then the uniq process is launched. Remember, processes inherit file descriptors from their parents. If you launch uniq before you close p1.stdin, then p1.stdin is open in the uniq process and you won't be able to close it. So, the hang is due to sort continuing to try to read from stdin.
_Mark_ said…
Confusion like this is why python needs a "pipeline" class on top of subprocess... as benjamin points out, if sort weren't special, neither of your approaches would work. Unix pipes get you a page (4k) of buffer. You instead want to use select (or poll) to write when you can, and to read when you can, and to notice EOFs (and then you want to look at *all* of the exit statuses.)
jjinux said…
> If you launch uniq before you close p1.stdin, then p1.stdin is open in the uniq process and you won't be able to close it.

That must be it. Thanks!
jjinux said…
Very helpful comments, everyone. It took me like three times reading them all, but they all made sense. Thanks!
Max Ischenko said…
looks like it resolved already.

ltrace/strace helps in such cases usually, since it becomes clear I/O is blocking
Anonymous said…
Further to jean-paul's comment - Popen takes a 'close_fds' keyword argument and if you set it to True then file descriptors of the parent process are closed in the child, so the block is avoided.

kmh
jjinux said…
> Popen takes a 'close_fds' keyword argument

That's a great tip. Thanks!
jjinux said…
Yep, it worked.
bsergean said…
(Jean-Paul) There is such a
pipeline class.

from pipes import Template

t = Template()
t.append('p4 print -q \"$IN\"', 'f-')

# iconv from src encoding to UTF-8
t.append('iconv -f %s -t UTF-8' % (r.p4encoding), '--')

# Turn on debugging
t.debug(1)

# start it
t.copy('//Work/foo/bar', '/tmp/foo')
bsergean said…
(That was Mark who wanted a pipeline module ...)
_Mark_ said…
Thanks for the pointer (I hadn't noticed pipes.py before) but it gets two big things wrong:
* it takes strings, not lists, so it's doomed to quoting horror
* unlike pretty much the entire rest of python, it ignores errors (it doesn't even look *possible* to get the exit statuses out.)

(Sadly both of those are based on the interface, not the implementation, so it's not just a matter of fixing bugs.)

Popular posts from this blog

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

ERNOS: Erlang Networked Operating System

I've been reading Dreaming in Code lately, and I really like it. If you're not a dreamer, you may safely skip the rest of this post ;) In Chapter 10, "Engineers and Artists", Alan Kay, John Backus, and Jaron Lanier really got me thinking. I've also been thinking a lot about Minix 3 , Erlang , and the original Lisp machine . The ideas are beginning to synthesize into something cohesive--more than just the sum of their parts. Now, I'm sure that many of these ideas have already been envisioned within Tunes.org , LLVM , Microsoft's Singularity project, or in some other place that I haven't managed to discover or fully read, but I'm going to blog them anyway. Rather than wax philosophical, let me just dump out some ideas: Start with Minix 3. It's a new microkernel, and it's meant for real use, unlike the original Minix. "This new OS is extremely small, with the part that runs in kernel mode under 4000 lines of executable code.&quo

Haskell or Erlang?

I've coded in both Erlang and Haskell. Erlang is practical, efficient, and useful. It's got a wonderful niche in the distributed world, and it has some real success stories such as CouchDB and jabber.org. Haskell is elegant and beautiful. It's been successful in various programming language competitions. I have some experience in both, but I'm thinking it's time to really commit to learning one of them on a professional level. They both have good books out now, and it's probably time I read one of those books cover to cover. My question is which? Back in 2000, Perl had established a real niche for systems administration, CGI, and text processing. The syntax wasn't exactly beautiful (unless you're into that sort of thing), but it was popular and mature. Python hadn't really become popular, nor did it really have a strong niche (at least as far as I could see). I went with Python because of its elegance, but since then, I've coded both p