I have this test.py
:
#!/usr/bin/env python3
import os
import sys
from select import select
from subprocess import Popen, PIPE
with Popen(('bash', '-c', 'echo 1; sleep 1; echo 2'), stdout=PIPE) as p:
readable = { p.stdout.fileno(): sys.stdout.buffer }
while readable:
fds = select(readable, [], [], 0.1)
print(f"readable is True. fds = {fds}")
if not fds[0]: continue
for fd in fds[0]:
print("In for loop")
data = os.read(fd, 1024) # read available
if not data: # EOF
print(f"delelting {fd}")
del readable[fd]
else:
readable[fd].write(data)
readable[fd].flush()
p.kill()
When I run it, I got this :
~/tmp$ ./test.py
readable is True. fds = ([4], [], [])
In for loop
1
readable is True. fds = ([4], [], [])
In for loop
delelting 4
~/tmp$
This is what I expected. But somtimes I got this by running the same script :
~/tmp$ ./test.py
readable is True. fds = ([4], [], [])
In for loop
1
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([4], [], [])
In for loop
delelting 4
~/tmp$
I'm using Python 3.8.2/ubuntu