Skip to content

Instantly share code, notes, and snippets.

@nobonobo
Created March 29, 2012 08:34
Show Gist options
  • Save nobonobo/2235037 to your computer and use it in GitHub Desktop.
Save nobonobo/2235037 to your computer and use it in GitHub Desktop.
nonblocking pipe for subprocess
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
import fcntl
import shlex
from time import sleep
from subprocess import Popen, PIPE
proc = Popen(shlex.split('''python -m SimpleHTTPServer'''), stdout=PIPE, close_fds=True)
#PIPEオブジェクトのノンブロッキング化 for Unix系
fno = proc.stdout.fileno()
fcntl.fcntl(fno, fcntl.F_SETFL, fcntl.fcntl(fno, fcntl.F_GETFL, 0) | os.O_NONBLOCK)
while proc.poll() is None:
try:
try:
print proc.stdout.readline()
except IOError:
# ノンブロッキングファイルからの読み出しは期待した分量が不足すると
# 「IOError: [Errno 11] Resource temporarily unavailable」が発生する。
sleep(0) # 他のスレッドの挙動を待つ
except KeyboardInterrupt:
proc.send_signal(2)
proc.wait()
print 'exit!'
@w495
Copy link

w495 commented Aug 1, 2016

Cool! Is it really works?

But, what should I do, If wont to sleep?
Will some kinds of unimit help me,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment