Created
September 21, 2011 13:56
-
-
Save sebclaeys/1232088 to your computer and use it in GitHub Desktop.
Python non-blocking read with subprocess.Popen
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
import fcntl | |
import os | |
from subprocess import * | |
def non_block_read(output): | |
fd = output.fileno() | |
fl = fcntl.fcntl(fd, fcntl.F_GETFL) | |
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) | |
try: | |
return output.read() | |
except: | |
return "" | |
############ | |
# Use case # | |
############ | |
sb = Popen("echo test; sleep 10000", shell=True, stdout=PIPE) | |
sb.kill() | |
sb.poll() # return -9 | |
#sb.stdout.read() # Will block and will block forever cause nothing will come out since the job is done | |
non_block_read(sb.stdout) # will return '' instead of hanging for ever | |
Readline version (strips '\n')
def non_block_readline(output) -> str:
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.readline().strip("\n")
except:
return ""
Since Python 3.5 os.set_blocking
can do exactly the same thing:
import os
from subprocess import *
sb = Popen("echo test; sleep 10000", shell=True, stdout=PIPE)
os.set_blocking(sb.stdout.fileno(), False) # That's what you are looking for
sb.kill()
sb.poll() # return -9
sb.stdout.read() # This is not going to block. When the pipe is empty it returns an empty string.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
p.stdout.readline()
blocks. That is why this gist is about non_blocking_read