首页 > 编程语言 > 详细

python print end 堵塞问题以及如何非堵塞读取subprocess的所有输出做到实时读取

时间:2021-05-14 15:47:32      阅读:14      评论:0      收藏:0      [点我收藏+]

python print end

如下代码:

    for i in range(5):
        time.sleep(1)
        print(i, end=‘‘)

本来想要的效果是每秒输出,但是发现这样写会等所有循环完毕后才会打印,发现需要使用flush参数来立即输出,正确代码如下:

    for i in range(5):
        time.sleep(1)
        print(i, end=‘‘, flush=True)

实时读取subprocess的输出

如何实时读取subprocess的输出是一个困扰我很久的问题,最近终于得到了解决,之前是使用subprocess的readline(),但是如果那一行仍未运行完时还是会堵塞,无法做到真正的实时读取,多方调查发现配合fcntl库可以做到,方法如下:

p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

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 ""

out = non_block_read(p.stdout)

if out != None:
    outstr = out.decode(utf8)
    print(outstr, end=‘‘, flush=True)

 

python print end 堵塞问题以及如何非堵塞读取subprocess的所有输出做到实时读取

原文:https://www.cnblogs.com/CYHISTW/p/14767863.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!