tags:

views:

51

answers:

2

Hi everyone,

Forgive me if the title is not lucid, but I could not better describe it in a single sentence.

Consider I have the following in a loop, which increments counter each time it runs.

output_string = 'Enter the number [{0}]'.format(counter)

When I do a print output_string, the output goes like:

Enter the number [1]: 

When I print this line again with the incremented number, like:

Enter the number [2]:

It will of course follow the 1st line and the cumulative output would be:

Enter the number [1]:
Enter the number [2]:

However, I don't want this. I want the first line line should be updated and without adding another line, the output should just change in the first line itself.

Like, it should display Enter the number [1]: and after that it should do an in-place replacement for [1] and the screen should read: Enter the number [2], without adding an extra line.

I hope I am being clear. The reason I am doing this is because I am taking in large inputs from the user and I don't want to clutter up the terminal when I can just keep on incrementing what I want within a single line.

+1  A: 

If your script will be running on Unix/Linux you could use the curses module.

Dave Webb
@Dave: I can but I really don't want myself restricted to Linux only. So if there is another way to do it, I would probably try that before checking out curses.
sukhbir
@PulpFunction: Curses is available for Windows. http://adamv.com/dev/python/curses/
S.Lott
@PulpFiction: fair enough. There are ways to get `curses` working on Windows but all they seemed ghastly when I looked at them. If you find a Windows-friendly way of doing this it'd be useful for me too.
Dave Webb
This issue is not Linux/Windows specific per si, it is terminal emulation related. Assuming you will be launching python from cmd.exe, you want to know how to control he cursor position on cmd .
João Pinto
+1  A: 

Try this

print('enter the number[1]', end='\r' )

If you're using Python 2.7, don't forget from __future__ import print_function.

S.Lott
I don't get it -- what is this supposed to do that the original solution didn't?
katrielalex
@S.Lott: Doesn't seem to work.
sukhbir
@katrielalex: It may not move "down" on some terminal windows. It may overwrite the line, depending on the settings.
S.Lott
@S.Lott: It still is not an in-place replacement. I think this is possible since I have seen it somewhere. I would have looked at the sources but I don't recall where.
sukhbir
@PulpFiction: Anything more than this is terminal specific. It requires either curses or writing two separate versions, one for Linux (using the TERMIO settings) and one for Windows.
S.Lott
@S.Lott: Aah thank you. And also, thanks for your amazing book. I am currently following that (Building Skills in Python).
sukhbir