Created
March 29, 2012 08:34
-
-
Save nobonobo/2235037 to your computer and use it in GitHub Desktop.
nonblocking pipe for subprocess
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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!' | |
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
time.sleep(n)はgevent.sleep(n)に変えればgreenletでも効率上げられるー。