0

How to prepend lines to stdout ?

In other words, when I write to stdout I want the output that was already printed to be 'pushed' down, then prepend next output.

jsalonen
  • 29,593
  • 15
  • 91
  • 109
minychillo
  • 395
  • 4
  • 17

2 Answers2

1

You cannot do that simply by manupulating stdout directly. Stdout is a file object. In regular file objects seek can be used. However, since everything is displayed in terminal as quickly as they get written to it, calling seek doesn't affect what has already been displayed.

However, with a proper terminal library like curses you can output control characters that manipulate cursor position and allows you to change text content anywhere in the console.

Note that curses is pretty low level library. For your specific use case of making animations, it might make sense to use a higher-level library like asciimatics.

jsalonen
  • 29,593
  • 15
  • 91
  • 109
  • 1
    There are also other libraries, mentioned in [this thread](https://stackoverflow.com/questions/8349085/python-ncurses-cdk-urwid-difference). – Gribouillis Jul 30 '17 at 08:47
0
  • Store the initial value to list,

  • then until your condition is satisfied,

    • append the new content to list
  • join the data with '\n'

That is,

import sys
arr = ['start line',]
while some_condition_till_you_want_to_write:
    arr.append('some new content')
print "\n".join(arr)
sys.stdout.flush()
Keerthana Prabhakaran
  • 3,766
  • 1
  • 13
  • 23
Ankur Jain
  • 115
  • 1
  • 4
  • Thank you, but I need to do this continuously – minychillo Jul 30 '17 at 08:49
  • to do this continuously, put True for while block and use queue inside. if queue is not empty fetch items from queue and print them, else don't print. And write a function, which will put the items inside the queue. – Ankur Jain Jul 30 '17 at 08:53