代码之家  ›  专栏  ›  技术社区  ›  a.t.

在打印语句行下方的文本后,如何覆盖该行?

  •  0
  • a.t.  · 技术社区  · 3 年前

    上下文

    我很难找到合适的stackoverflow问题: 我想用打印其他内容后计算的值更新python中的打印行。这个 something else 应保持在更新的行以下。

    例如:

    first="hello"
    third=""
    print(f'{first} \r{third}', end=" ", flush=True)
    
    second="somethingelse"
    print(second)
    
    if second == "somethingelse":
        third="world"
    else:
        third="Universe"
    

    应打印:

    hello 
    something.
    

    然后将其更改为:

    hello world
    something
    

    或者应该打印:

    hello
    something.
    

    然后将其更改为:

    hello universe
    something
    

    重要的是:

    • 在打印内容之前先打印hello。
    • world/universe与hello打印在同一行。
    • 你好宇宙/世界线以下有东西。
    • 某些东西可以由任意数量的打印行组成。

    XY问题

    我修改了 showme pip包来显示函数的运行时。我希望打印出函数名,然后是正在运行的函数的输出。并且仍然将运行时打印在与函数名称相同的行后面/上。(为了减少CLI混乱)。

    问题

    如何使用在该行下方打印其他内容后计算的值更新该行?

    相关问题:

    Print in one line dynamically

    How can I print something, and then call a function with a print on the same line?

    Remove and Replace Printed items

    How to overwrite the previous print to stdout?

    2 回复  |  直到 3 年前
        1
  •  1
  •   Jarno Lamberg    3 年前

    不使用 curses 或者类似的东西,只可能更新终端中的最后一行输出,而不可能更新之前的输出。

    下面是一个简单的例子,说明如何在用curses打印第二行后更新第一行( sleep 仅用于使更改更加明显的函数):

    import curses
    from time import sleep
    
    w = curses.initscr()
    
    w.addstr(0,0, 'first line')
    w.refresh()
    w.addstr(1, 0, 'second line')
    w.refresh()
    
    sleep(2)
    
    w.addstr(0,0, 'replaced first line')
    w.refresh()
    
    sleep(2)
    
    curses.endwin()
    
        2
  •  0
  •   Dejene T.    3 年前

    我不太确定这个答案是否能让你满意

    first="hello"
    third=""
    second="sometfirst="hello"
    third=""
    second="somethingelse"
    
    if second == "somethingelse":
        third="world"
    else:
        third="Universe"
        
    print(f'{first} {third}', end=" ", flush=True)
    print(second)