如何重置控制台输出?清除只是将输出移回

Kre*_*ory 5 console-application rust

我的控制台应用程序需要清除屏幕。如何真正清屏,就像Linux中的reset命令一样?

我尝试使用在 Google 上找到的方法,例如:

print!("{}[2J", 27 as char); // First attempt
print!("{}", termion::clear::All); // 'termion' crate, version 1.5.3
Run Code Online (Sandbox Code Playgroud)

它们都只是向下滚动,将之前的输出留在后面。我想过通过Rust执行reset命令,但肯定还有其他方法吧?

ale*_*der 2

既然没有人写答案,我就写吧。

如前所述@mcarton,您需要使用一个alternate screen在超出范围后自动重置所有内容的工具。

基本上,这将创建一个virtual screen覆盖您当前的位置terminal screen,并将on旧的位置放置same coordinatessame height and width. 它就像一个copy,简称。

在您的程序期间,您将写入和删除到备用屏幕,而不会损坏您的终端屏幕。

一个示例工作代码docs是:

use termion::screen::AlternateScreen;
use std::io::{Write, stdout};

fn main() {
    {
        let mut screen = AlternateScreen::from(stdout());
        write!(screen, "Writing to alternate screen!").unwrap();
        screen.flush().unwrap();
    }
    println!("Writing to main screen.");
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用termion打印到可变的备用屏幕。

        write!(
            screen,
            "{}{}{}",
            termion::cursor::Goto(1, 10),
            "some text on coordinates (y=10, x=1)",
            termion::cursor::Hide,
        )
        .unwrap();
//
// to refresh the screen you need to flush it, i.e 
// to write all the changes from the buffer to the screen
// just like flushing to toilet, 
// but flushing the buffer where the text was placed
// which is a matrix
        self.screen.flush().unwrap();

Run Code Online (Sandbox Code Playgroud)