python子进程杀死行为

时间:2020-07-10 21:17:26

标签: python subprocess kill

我有这个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

0 个答案:

没有答案
相关问题