overwriting output of function in terminal on same line
<p>I have a function, for example</p>

<pre><code>def f(x):
    for i in range(x):
        print i
</code></pre>

<p>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:</p>

<pre><code>print f(5)
</code></pre>

<p>output is:</p>

<pre><code>1
2
3
4
</code></pre>

<p>but I want it to overwrite and instead print like this:</p>

<pre><code>print f(5)

4
</code></pre>

<p>Please keep in mind that I cannot modify inside f(x) function.</p>

<p>Since <code>print</code> 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.</p>

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

<pre><code>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)
</code></pre>

<p>Result:</p>

<ul>
<li>on a terminal (windows or Linux): only 4 is shown</li>
<li>redirecting to a file: we see all numbers separated by <code>\r</code> chars</li>
</ul>

<p>Ok it's a hack but we cannot modify <code>f</code> and we did not... Mission accomplished.</p>

<p>It may be useful to restore <code>sys.stdout</code> to its original value once we're done.</p>

python python-2.7