Follow and read the contents output to the standard output with subprocess.Popen. At this time, instead of using readline () to read each line break, use read () to read (?). I often worry about the stream, so make a note.
I have confirmed the operation with Python 2.7.5 on CentOS7.
This is the script that is started by Popen.
textout.py
#!/usr/bin/env python
import sys
import time
for i in range(0, 10):
sys.stdout.write("[Count {0:04d}]".format(i))
time.sleep(1)
A simple script that outputs [Count 0000]
every second. However, since it does not break, it cannot be read by readline ().
Call the above script with Popen and read the standard output.
reader.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os, time, errno, fcntl
from subprocess import Popen, PIPE
#Textout with Popen.Run py
#At this time to python-Pass u option to avoid buffering
p = Popen([sys.executable, "-u", "textout.py"], bufsize=0, stdout=PIPE)
# p.Put stdout into non-blocking mode
flag = fcntl.fcntl(p.stdout.fileno(), fcntl.F_GETFL)
fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, flag | os.O_NONBLOCK)
while True:
#Read loop
try:
# p.load stdout
#Since it is a non-blocking mode, read as much as you can read
buf = p.stdout.read()
if buf == "": break # p.Exit when stdout is closed
sys.stdout.write(buf) #Output what you read
sys.stdout.flush() #Flush because there are no line breaks()
except IOError, e:
#IOError if there is nothing to read(11,
# "Resource temporarily unavailable")But
#Wait because it will be thrown
if e.errno == errno.EAGAIN:
time.sleep(0.1)
p.wait()
$ ./reader.py
[Count 0000][Count 0001][Count 0002][Count 0003][Count 0004][Count 0005][Count 0006][Count 0007][Count 0008][Count 0009]
[Count 0000]
is output every second.
--Do not buffer when running textout.py, or flush () after writing to sys.stdout --reader.py reads p.stdout with read (), so read in non-blocking mode --When waiting for output, errno.EAGAIN is sent, so exception handling and waiting --If you wait until textout.py finishes, read () one shot (^^;) without doing such a troublesome thing
Recommended Posts