如何使用python日志modu打印当前行

2024-04-24 01:55:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个具有多个线程的程序,因此对于日志信息,我使用python日志模块。然而,我有一部分应用程序,我想显示多少是线程是等待执行在同一行,这是被覆盖的每一次。我不想在日志中显示多行。你知道吗

我尝试使用sys.stdout.flush()函数。不幸的是它不起作用。你知道吗

我的当前代码:

def log_flush(message, start, stop):
    import logging, sys
    logging.basicConfig(level=logging.DEBUG,
                        format='(%(threadName)-10s) %(message)s',
                        )
    time = stop - start
    logging.debug((str(message) + str(time)))
    sys.stdout.write('\r')
    sys.stdout.flush()

for i in range(0, 5):
    log_flush("Time taken: ", 0, i)

我的预期输出是(执行完成后):

(MainThread) Time taken: 4

当前脚本输出:

(MainThread) Time taken: 0
(MainThread) Time taken: 1
(MainThread) Time taken: 2
(MainThread) Time taken: 3
(MainThread) Time taken: 4

Tags: 程序logmessagetimeloggingstdoutsys线程
2条回答

您可以print返回空间,如下所示:

import time, sys

t = 0
while True:
    print('Seconds passed:', t, end='')
    sys.stdout.flush()
    time.sleep(1)
    t += 1
    print('\b'*20, end='')

我想你必须清理你的控制台:))

看看这个问题:

clear console in python

相关问题 更多 >