einmalundweg
einmalundweg

Reputation: 103

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? e.g.:

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

Upvotes: 1

Views: 274

Answers (2)

ShlokSayani
ShlokSayani

Reputation: 91

You can set defscrollback 100 if you're using GNU. 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

Upvotes: 1

MiH
MiH

Reputation: 135

I think this question actually is not about python but about the terminal emulator that you use. 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
  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:

ps x | less

Upvotes: 0

Related Questions