Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I overwrite console output?

Tags:

console

rust

Is there a way to overwrite console output using Rust instead of simply appending?

An example would be printing progress as a percentage; I would rather overwrite the line than print a new line.

like image 779
Jonathan Woollett-light Avatar asked Jan 24 '20 04:01

Jonathan Woollett-light


People also ask

Can you override console log?

log. To override a console method, we just need to redefine how the method is executed. You'll need to wrap your code to prevent the access of other functions to the private (original) method.

How do you wrap a console log?

Another way to console. log your variables is to simply place your mouse cursor on them and then wrap them on the line below with Ctrl+Alt+W + Down or the line above with Ctrl+Alt+W + Up .


1 Answers

Consoles are usually controlled by printing out "control characters", but what they are depends on the platform and terminal type. You probably don't want to reinvent the wheel to do this.

You can use the crossterm crate to get this kind of console control. A simple example is:

use std::{thread, time};
use std::io::{Write, stdout};
use crossterm::{QueueableCommand, cursor};

fn main() {
    let mut stdout = stdout();

    for i in 1..10 {
        stdout.queue(cursor::SavePosition);
        stdout.write(format!("Here!!! {}", i).as_bytes());
        stdout.queue(cursor::RestorePosition);
        stdout.flush();
        thread::sleep(time::Duration::from_millis(500));
    }

    println!("Hello, world!");
}
like image 144
Michael Anderson Avatar answered Sep 28 '22 12:09

Michael Anderson