简体   繁体   English

如何打印输出并保持在同一行(Python)?

[英]How to print output and stay in the same line (Python)?

I have string that goes over multiple lines leading the terminal to scroll to the latest printed line.我有跨越多行的字符串,导致终端滚动到最新的打印行。 But I want to stay in the first line, so that I will be able to see the first lines but not the latest.但是我想留在第一行,这样我就可以看到第一行而不是最新行。 Is that possible?那可能吗? eg:例如:

for i in range(100):
    print(f"hello {i}")

and I want to see hello 0 but the output should stay in the same shape我想看到hello 0但输出应该保持相同的形状

You can set defscrollback 100 if you're using GNU.如果您使用的是 GNU,则可以设置 defscrollback 100。 Otherwise, this should help:否则,这应该会有所帮助:

class More(object):
def __init__(self, num_lines):
    self.num_lines = num_lines
def __ror__(self, other):
    s = str(other).split("\n")
    for i in range(0, len(s), self.num_lines):
        print(*s[i: i + self.num_lines], sep="\n")
        input("Press <Enter> for more")
more = More(num_lines=30)  
"\n".join(map(str, range(100))) | more

I think this question actually is not about python but about the terminal emulator that you use.我认为这个问题实际上与 python 无关,而是与您使用的终端模拟器有关。 In most terminal emulators you can simply scroll up a line after you launched your application so that the output won't scroll down automatically.在大多数终端模拟器中,您可以在启动应用程序后简单地向上滚动一行,这样输出就不会自动向下滚动。 Just do the following:只需执行以下操作:

  1. Open the terminal打开终端
  2. Start your python script启动你的python脚本
  3. Scroll up before the large output starts在大输出开始之前向上滚动
  4. Hopefully your terminal stays in the position.希望您的终端保持在该位置。

Alternatively, you can pipe the output of the programm to less, so that you can scroll page-wise:或者,您可以将程序的输出通过管道传输到less,以便您可以逐页滚动:

ps x | less

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM