< 返回版块

西沉 发表于 2020-06-26 16:50

Tags:cli

本期的每周一库带来的是一个十分有趣的cli小工具,rust下的cli进度条库 - pbr

先附上库的链接

库的简介十分简单,按照作者的说法,这个库的灵感来自于golang的pb库

github页面上直接提供了示例代码帮助我们快速体验pbr的功能,三个例子分别是

  • 简单用例
  • 多进度条用例
  • 文件拷贝进度条用例

下面我们来体验一下pbr库的使用,测试环境

  • Windows 10
  • cargo --version: cargo 1.45.0-nightly (9fcb8c1d2 2020-05-25)

首先我们在Cargo.toml文件中添加引用pbr = "1.0.3"

简单用例
main.rs代码,我们修改官方例子,使用time::Duration::from_millis(200)实现thread sleep功能

extern crate pbr;

use pbr::ProgressBar;
use std::{thread, time};

fn main() {
    let count = 1000;
    let mut pb = ProgressBar::new(count);
    let duration = time::Duration::from_millis(20);
    pb.format("╢▌▌░╟");
    for _ in 0..count {
        pb.inc();
        thread::sleep(duration);
    }
    pb.finish_print("done");
}

使用命令cargo run运行结果如下
rust-pbr.gif

多进度条用例

我们适当修改一下官方的例子,去除掉warning

extern crate pbr;

use std::{thread};
use pbr::MultiBar;
use std::time::Duration;

fn main() {
    let mb = MultiBar::new();
    let count = 100;
    mb.println("Application header:");

    let mut p1 = mb.create_bar(count);
    let _ = thread::spawn(move || {
        for _ in 0..count {
            p1.inc();
            thread::sleep(Duration::from_millis(100));
        }
        // notify the multibar that this bar finished.
        p1.finish();
    });

    mb.println("add a separator between the two bars");

    let mut p2 = mb.create_bar(count * 2);
    let _ = thread::spawn(move || {
        for _ in 0..count * 2 {
            p2.inc();
            thread::sleep(Duration::from_millis(100));
        }
        // notify the multibar that this bar finished.
        p2.finish();
    });

    // start listen to all bars changes.
    // this is a blocking operation, until all bars will finish.
    // to ignore blocking, you can run it in a different thread.
    mb.listen();
}

运行结果
rust-pbr-multi.gif

以上就是本期的每周一库

评论区

写评论

还没有评论

1 共 0 条评论, 1 页