У меня это 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()
Когда я его запустил, я получил следующее:
~/tmp$ ./test.py
readable is True. fds = ([4], [], [])
In for loop
1
readable is True. fds = ([4], [], [])
In for loop
delelting 4
~/tmp$
Это то, что я ожидал. Но иногда я получал это, запустив тот же сценарий:
~/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$
Я использую Python 3.8.2/ubuntu