打印新行后如何在 Rust 中清除终端屏幕



我已经使用println!打印了一些文本,现在我需要清除终端并写入新文本而不是旧文本。如何从终端清除所有当前文本?

我尝试过这段代码,但它只清除了当前行,1仍在输出中。

fn main() {
    println!("1");
    print!("2");
    print!("r");
}

您可以发送控制字符以清除终端屏幕。

fn main() {
    print!("{}[2J", 27 as char);
}

或者将光标也定位在第 1 行、第 1

print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
print!("x1B[2Jx1B[1;1H");

这将清除屏幕并将光标放在屏幕的第一行和第一列。

投票答案提供的解决方案没有按照我想要的方式工作。x1B[2Jx1B[1;1H顺序仅向下滚动终端,因此它实际上隐藏了内容,并且不会清除它。由于我想运行并无限循环重新呈现向用户显示的内容,这是个问题,因为我的终端窗口的滚动条随着每个"滴答"而缩小。

灵感来自 清除我正在使用的真实终端屏幕

print!("{esc}c", esc = 27 as char);

这对我来说很有效。除了我使用的其他系统(Ubuntu)之外,可能会有一些缺点,我不知道。

在 Linux 或 macOS 终端中尝试一下:

std::process::Command::new("clear").status().unwrap();

在 Windows One 中:

std::process::Command::new("cls").status().unwrap();

这基本上将"清除"命令发送到终端。

查看 Vallentin 给出的 cant-run-a-system-command-in-windows 的确切答案:

use std::{
    error::Error,
    process::Command,
};
fn main() -> Result<(), Box<dyn Error>> {
    clear_terminal_screen();
    println!("Hello World!");
    Ok(())
}

这样:

pub fn clear_terminal_screen() {
    if cfg!(target_os = "windows") {
        Command::new("cmd")
            .args(["/c", "cls"])
            .spawn()
            .expect("cls command failed to start")
            .wait()
            .expect("failed to wait");
    } else {
        Command::new("clear")
            .spawn()
            .expect("clear command failed to start")
            .wait()
            .expect("failed to wait");
    };
}

参观锈操场。

最新更新