0

I have a function, for example

def f(x):
    for i in range(x):
        print i

Without making any addition in f(x) function, is it possible to overwrite the terminal line during run? For example, in my case it shows like this:

print f(5)

output is:

1
2
3
4

but I want it to overwrite and instead print like this:

print f(5)

4

Please keep in mind that I cannot modify inside f(x) function.

Loquitor
  • 19
  • 6

3 Answers3

0

In general, no; but depending on what the "terminal" is assumed to be, maybe. Many terminal windows emulate the ancient cursor positioning commands from one or more "glass tty" terminals. In which case, if you assume you know what terminal is being emulated, you can send cursor positioning commands to move back to the previous before calling f.

ddyer
  • 1,792
  • 19
  • 26
0

Since print issues a newline, and you cannot go back after that, you have to prevent at all costs that a newline char to be issued in the terminal.

You can do it by redirecting sys.stdout. print will output to your new stream. In your stream, remove the linefeed and add a carriage return. Done

import sys


def f(x):
    for i in range(x):
        print i

class fake():
    def __init__(self):
        self.__out = sys.stdout
    def write(self,x):
        r = self.__out.write(x.replace("\n","")+"\r")
        self.__out.flush()  # flush like if we wrote a newline
        return r


sys.stdout=fake()

f(5)

Result:

  • on a terminal (windows or Linux): only 4 is shown
  • redirecting to a file: we see all numbers separated by \r chars

Ok it's a hack but we cannot modify f and we did not... Mission accomplished.

It may be useful to restore sys.stdout to its original value once we're done.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

If you are trying to print only the last line, you can pipe the output and use tail command to retrieve only the last word.

Useful link: https://kb.iu.edu/d/acrj

  • Hi Ganesh, welcome to SO and thank you for your answer. As links can change over time, would you mind editing your post (edit link below it) to add in the pertintent details of your suggested solution? You can still include the link as context and attribution, but it would be helpful to keep the key details alive here. Thank you! – Tim Malone Sep 26 '16 at 00:32