使用python进行动态终端打印

使用python进行动态终端打印

本文介绍了使用python进行动态终端打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些应用程序如 helanzb 有一种打印到终端的方式,显示动态刷新数据,有点像 top().

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

python 中执行此操作的最佳方法是什么?我已经阅读了日志和诅咒,但不知道该使用什么.我正在创建 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.

推荐答案

如果您只需要更新一行(例如,创建进度条),最简单的方法是使用 ''(回车)和 sys.stdout:

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

import sys
import time

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

如果您需要支持移动指针等的适当控制台 UI,请使用 标准库中的curses 模块:

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)

强烈建议使用 curses.wrapper 函数来调用你的主函数,它会在出现错误时负责清理终端,所以之后它不会处于不可用状态.

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.

如果您创建更复杂的 UI,您可以为屏幕的不同部分、文本输入框和鼠标支持创建多个窗口.

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

这篇关于使用python进行动态终端打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:58