如何使用print或sys.stdout.write执行多行刷新

时间:2018-01-19 13:43:46

标签: python stdout

我的脚本将运行几个小时,我想要更新其状态。我通常使用sys.stdout.write("\r"+string)并且效果很好但是目前,我需要记录多个内容,因此我必须使用'\n'或添加其他打印功能。

我的想法已经不多了。我正在玩curses,但在initscr()时无法找到PyCharm的控制台。

那么,你如何刷新多线输出?

虚拟代码:

import sys
import time

for i in range(2):
    # sys.stdout.write(
    # "\r"+
    # "line 1 loop {loop1}\n"
    # "line 2 loop {loop2}\n".format(
    #     loop1=i,
    #     loop2=i
    # ))

    sys.stdout.write("\r" + "line 3 loop {loop}".format(loop=i))
    sys.stdout.write("\r" + "line 4 loop {loop}".format(loop=i))


    # sys.stdout.write("line 6 loop {loop}\n".format(loop=i))
    # sys.stdout.write("line 7 loop {loop}\n".format(loop=i))
    # sys.stdout.flush()

    # print("line 5 loop {loop}".format(loop=i), end="\r", flush=True)

    time.sleep(0.5)

输出:

line 4 loop 1

期望的输出:

line 3 loop 1
line 4 loop 1

更新,因为我的例子不够清楚

import sys
import time

def increment(i):
    return i+1

def multiply(i):
    return i*2

for i in range(5):
    sys.stdout.write(
    "\r"+
    "candies eaten {candies}\n"
    "chocolates eaten {chocolate}\n".format(
        candies=increment(i),
        chocolate=multiply(i)
    ))

    time.sleep(0.5)

输出

candies eaten 1
chocolate eaten 0
candies eaten 2
chocolate eaten 2
candies eaten 3
chocolate eaten 4
candies eaten 4
chocolate eaten 6
candies eaten 5
chocolate eaten 8

期望的输出

candies eaten 5
chocolate eaten 8
每次循环都会更新

0 个答案:

没有答案