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

2021/5/14 12:25:28

本文主要是介绍python print end 堵塞问题以及如何非堵塞读取subprocess的所有输出做到实时读取,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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的所有输出做到实时读取的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程