1

How to print multiline string in python in place without moving to next line when the string is updated?

I tried pandas, numpy, print, \r works only for last row of the string that is printed.. any idea or workaround this?

from sys import stdout
from time import sleep

for i in range(5):
    text = "line one:{}\nline two:{}".format(i,i+2)
    stdout.write("\r"+text)
    sleep(1)

The output should be only two lines that are updated with values.
line one:0 > update this value to 1
line two:2 > update this value to 3

Mustafa Zengin
  • 2,885
  • 5
  • 21
  • 24
PythonMan
  • 787
  • 10
  • 18
  • 1
    try to save your string on buffer before your print it all out! – Frank AK Jan 26 '18 at 09:26
  • 2
    I think that it only possible with the curses interface, allowing you to arbitrarily place character on the screen. This has for example been used in the old days for 'graphical' games on character displays. There is a curses module available for python. However, I am not sure if it works with windows as curses is originally a Unix thing. – Lars Jan 26 '18 at 09:26
  • 1
    UniCurses - works windows and linux - see this answer https://stackoverflow.com/a/41224335/7505395 ( [what-is-needed-for-curses-in-python-3-4-on-windows7](https://stackoverflow.com/questions/32417379/what-is-needed-for-curses-in-python-3-4-on-windows7) , also for w10) – Patrick Artner Jan 26 '18 at 09:29

2 Answers2

2

You could try curses to replace the text in any position of the screen. This example will show consecutive numbers from i to i+5 in different lines.

import curses, time
scr = curses.initscr()
for i in range(10):
    for k in range(5):
        scr.addstr(k, 0, "%2d" % (i+k))
    scr.refresh()
    time.sleep(0.5)
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • curses is a great start it works in py/cmd console but doesn't work in pycharm(Redirection is not supported.). I will try some workarounds with that part but atleast I have now some idea how to do it. – PythonMan Jan 26 '18 at 09:48
  • @PythonMan What do you mean, it does not work in PyCharm? That's just an IDE, and even if the builtin console does not support curses, the program you create in that IDE will ultimately run as a regular Python script, right? – tobias_k Jan 26 '18 at 10:03
  • When I run script in PyCharm it throws error "Redirection is not supported."(because built in console does not support curses).. But if I run it regularly (Not over PyCharm), yeah it will work. – PythonMan Jan 26 '18 at 10:41
-2

Your question was not clear, so I thought this code would be useful.

import array
L = list("someList")
for i in L:
   a=array.array('c', 'X_String_you_need_to_change')
   a[0] = i
   print a.tostring()
Daniel F
  • 13,684
  • 11
  • 87
  • 116