zoukankan      html  css  js  c++  java
  • 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的输出

    fcntl库似乎在windows中使用有问题,待找其他库代替,下面代码是基于linux系统

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

    import fcntl
    import subprocess
    import os
    import time
    
    p = subprocess.Popen('ping www.baidu.com', 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 ""
    
    # 当程序未运行结束时输出
    while p.poll() is None:
        out = non_block_read(p.stdout)
        if out != None:
            outstr = out.decode('utf8')
            print(outstr, end='', flush=True)

     subprocess 以 ctrl c 方式终止

    直接p.kill()方式可能与我们使用命令行时使用ctrl c终止方式不同,比如pytest-html,如果kill()子进程,则报告不会保留,但是以ctrl c方式会保存已测试的结果

    import signal
    
    p = subprocess...
    
    p.send_signal(signal.SIGINT)
    喜欢的觉得有用的就点个赞吧,点波关注不迷路呦
  • 相关阅读:
    Ant
    责任链模式
    日志logback
    知识点
    三个实例演示 Java Thread Dump 日志分析
    IDEA运行编译后配置文件无法找到,或配置文件修改后无效的问题
    IDEA创建MAVEN WEB工程
    多线程源码分析ThreadPoolExecutor
    解决
    微博关系服务与Redis的故事
  • 原文地址:https://www.cnblogs.com/CYHISTW/p/14767863.html
Copyright © 2011-2022 走看看