63

Certain applications like hellanzb have a way of printing to the terminal with the appearance of dynamically refreshing data, kind of like top().

Whats the best method in python for doing this? I have read up on logging and curses, but don't know what to use. I am creating a reimplementation of top. If you have any other suggestions I am open to them as well.

1
  • 7
    Any reason this is a community wiki? Commented Jan 23, 2010 at 6:51

7 Answers 7

83

The simplest way, if you only ever need to update a single line (for instance, creating a progress bar), is to use '\r' (carriage return) and sys.stdout:

import sys
import time

for i in range(10):
    sys.stdout.write("\r{0}>".format("="*i))
    sys.stdout.flush()
    time.sleep(0.5)

If you need a proper console UI that support moving the pointer etc., use the curses module from the standard library:

import time
import curses

def pbar(window):
    for i in range(10):
        window.addstr(10, 10, "[" + ("=" * i) + ">" + (" " * (10 - i )) + "]")
        window.refresh()
        time.sleep(0.5)

curses.wrapper(pbar)

It's highly advisable to use the curses.wrapper function to call your main function, it will take care of cleaning up the terminal in case of an error, so it won't be in an unusable state afterwards.

If you create a more complex UI, you can create multiple windows for different parts of the screen, text input boxes and mouse support.

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

1 Comment

Actually you don't even have to use sys.stdout. The statement print 'hey', will not create a line break.
22

As most of the answers have already stated, you really have little option on Linux but to use ncurses. But what if you aren't on Linux, or want something a little more high-level for creating your terminal UI?

I personally found the lack of a modern, cross-platform terminal API in Python frustrating, so wrote asciimatics to solve this. Not only does it give you a simple cross-platform API, it also provides a lot of higher level abstractions for UI widgets and animations which could be easily used to create a top-like UI.

1 Comment

Thanks. BTW, I have now written a sample top application for this priject.
8

Sending output to the terminal via the print() command can be done without scrolling if you use the attribute "end".

The default is end='\n' which is a new line.

To suppress scrolling and overwrite the whole previous line, you can use the RETURN escape which is '\r'.

If you only want to rewrite the last four characters, you can use a few back-spaces.

print(value, "_of_", total, end='\r')

NOTE This works for the standard system terminal. The terminal emulator in some tools like IDLE has an error and the '\r' does not work properly, the output is simply concatenated with some non-printable character between.

BONUS INFORMATION FOR print() In the example above, the spaces on each side of "of" are meant to insure white-space between my values and the word "of". However, the default separater of the print() is a " " (space) so we end up with white space between the value and underscore of "_of_".

>> print (value, "_of_", total, end='\r')
8 _of_ 17

The sepparator attribute, sep, can be used to set character between printed items. In my example, I will change it to a null string ('') to make my output suit my needs.

>> print (value, "_of_", total, sep='', end='\r')
8_of_17

Comments

5

I hacked this script using curses. Its really a ad-hoc solution I did for a fun. It does not support scrolling but I think its a good starting point if you are looking to build a live updating monitor with multiple rows on the terminal.

https://gist.github.com/tpandit/b2bc4f434ee7f5fd890e095e79283aec

Here is the main:

    if __name__ == "__main__":
        stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
        curses.init_pair(4, curses.COLOR_CYAN, curses.COLOR_BLACK)

        try:
            while True:
                resp = get_data()
                report_progress(get_data())
                time.sleep(60/REQUESTS_PER_MINUTE)
        finally:
            curses.echo()
            curses.nocbreak()
            curses.endwin()

1 Comment

Great example of outputting an entire table to console and constantly updating it!
1
import time
for i in range(10):
    print('\r{}>'.format('='*i), end='')
    time.sleep(0.5)

Comments

0

When I do this in shell scripts on Unix, I tend to just use the clear program. You can use the Python subprocess module to execute it. It will at least get you what you're looking for quickly.

Comments

0

I don't think that including another libraries in this situation is really good practice. So, solution:

print("\rCurrent: %s\t%s" % (str(<value>), <another_value>), end="")

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.