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

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python . Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening. The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for B

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

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from