【问题标题】:Different output of printing in rust and pythonrust 和 python 中打印的不同输出
【发布时间】:2021-11-06 17:50:39
【问题描述】:

我正在尝试生锈,我想为我的计时器创建一行打印。

我想用 rust 编写的 Python 代码:

from time import sleep
for i in range(61):
    print(i, end="\r")
    sleep(1)

此代码在一行中打印秒数,从而更新行中的秒数

我试过用 rust 来做这个:

use std::thread::sleep;
use std::time::Duration;

fn main() {
    for i in 0..61 {
        print!("{}\r", i);
        sleep(Duration::from_millis(1000));
    }
}

Rust 脚本不会打印任何内容,但 python 脚本会打印第二个并更新它: 当你运行它时

$ python script.py
0

当它运行 1 秒时

$ python script.py
1

当它运行 2 秒时

$ python script.py
0

我尝试从 rust 代码中的行中删除“\r”,现在它等待 60 秒,然后在一行中打印从 0 到 61 的数字:0123456789...%

我看不出 python 和 rust 代码之间的区别

【问题讨论】:

标签: rust


【解决方案1】:

Rust stdout 是缓冲的,这意味着如果您不打印换行符并希望它输出某些内容,则需要刷新它。

你会这样写:

use std::thread::sleep;
use std::time::Duration;
use std::io::{self, Write};

fn main() {
    for i in 0..61 {
        print!("{}\r", i);
        match io::stdout().flush() {
            Ok(_) => {},
            Err(_) => std::process::exit(1)
        }
        sleep(Duration::from_millis(1000));
    }
}

【讨论】:

  • 更好的解决方案是使用println!() 宏,因为它会为您处理刷新和换行控制字符。
  • @IvanC 我尝试使用println 并将每个新整数打印在新行上,而不是替换旧整数。
【解决方案2】:

尝试打印

for i in 1..10{
  println!("{}",i);
  sleep(Duration::from_millis(1000));
}

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多