0

A simple question on a python module. Let's say I have the following code:

for i in range(1000):
  print i

It'll output something along the lines of:

1

2

'Snip'

999

Is it possible to have the program output all the numbers on the same line? I'm not talking about "1, 2, 3 .." rather I want the line value to change to the current i

5 Answers 5

3

If you want the character to be overwritten/replaced each time, you may need to use a terminal control library like 'curses'. Here's a Python how-to article to get you started.

Sign up to request clarification or add additional context in comments.

Comments

3

If you want to draw a GUI inside a terminal, you'll have to use the curses module.

Comments

2

For a simple case the following code works just fine:

sys.stdout.write(str(i)+'\r')
sys.stdout.flush()

3 Comments

Don't forget to add padding to the right, to overwrite characters that are not overwritten by the following output. The last output from the example would read "999p" because "999" doesn't overwrite the "p" from "snip".
@Steven: For a simple case...
you're right, of course. I just mentioned it because it wouldn't work with the example output as given in the question. And now I realize that 'Snip' wasn't actually meant as an example output ;-)
2
import os

for i in range(1000):
  print i
  os.system("clear")

edit: as mentioned in the comment below, change "clear" to "cls" if using windows.

2 Comments

This won't work on Windows, since the UNIX clear utility is called cls there.
I left it out initially because I assumed UNIX. Thanks for pointing it out.
1

Text printed to stdout can't be dynamically changed. You need to use a panel.

http://docs.python.org/library/curses.panel.html

Initialize a new panel, and then use Panel.set_userptr(obj) in your loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.