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)

 

相关文章:

  • 2022-12-23
  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
  • 2021-06-11
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-30
  • 2021-09-04
  • 2022-02-17
  • 2022-01-31
相关资源
相似解决方案