简体   繁体   中英

Redraw screen in terminal

How do some programs edit whats being displayed on the terminal (to pick a random example, the program 'sl')? I'm thinking of the Linux terminal here, it may happen in other OS's too, I don't know. I've always thought once some text was displayed, it stayed there. How do you change it without redrawing the entire screen?

Depending on the terminal you send control seuqences. Common sequences are for example esc[;H to send the cursor to a specific position (eg on Ansi, Xterm, Linux, VT100). However, this will vary with the type or terminal the user has ... curses (in conjunction with the terminfo files) will wrap that information for you.

try this shellscript

#!/bin/bash
i=1
while [ true ]
    do
            echo -e -n "\r $i"
            i=$((i+1))
    done

the -n options prevents the newline ... and the \\r does the carriage return ... you write again and again into the same line - no scroling or what so ever

If you terminate a line sent to the terminal with a carriage return ('\\r') instead of a linefeed ('\\n'), it will move the cursor to the beginning of the current line, allowing the program to print more text over top of what it printed before. I use this occasionally for progress messages for long tasks.

If you ever need to do more terminal editing than that, use ncurses or a variant thereof.

Many applications make use of the curses library, or some language binding to it.

For rewriting on a single line, such as updating progress information, the special character " carriage return ", often specified by the escape sequence "\\r", can return the cursor to the start of the current line allowing subsequent output to overwrite what was previously written there.

There are characters that can be sent to the terminal that move the cursor back. Then text can be overwritten.

There is a list here . Note the "move cursor something" lines.

Corporal Touchy has answered how this is done at the lowest level. For easier development the curses library gives a higher level of control than simply sending characters to the terminal.

NCurses是一个跨平台的库,可以让您在智能终端上绘制用户界面。

在@Corporal Touchy的答案的基础上,有一些库可以为你处理一些这样的功能,比如curses / ncurses

I agree with danio, ncurses is the way to go. Here's a good tutorial:

http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM