标签: 命令行

  • 基于ANSI转义序列来构建命令行工具

    命令行工具在输出时,如果是简单的进度更新,可以使用 \r\b 来达成刷新行的效果,但如果要更复杂些的如字体颜色、背景颜色、光标位置移动等功能,那就需要使用 ANSI 转移序列了。

    已有不少成熟的命令行工具库,如 ReadlineJLinePython Prompt Toolkit,基于这些库创造了如 mycliipython 等好用的工具。

    ANSI 转义序列有比较悠久的历史,不同平台支持的功能不完全一致,这里学习到的是比较简单常用的,包括字体颜色、背景色和其它装饰的富文本和光标操作。

    \u001b 即 ESC 的 ASCII 码,\u001b[0m 是清除之前的设定。

    适用于 *nix 的系统。

    富文本

    前景色

    8 色

    \u001b[?m,其中 ? ∈ [30, 37]

    • 黑(black):\u001b[30m
    • 红(red):\u001b[31m
    • 绿(green):\u001b[32m
    • 黄(yellow):\u001b[33m
    • 蓝(blue):\u001b[34m
    • 品红(magenta):\u001b[35m
    • 蓝绿(cyan):\u001b[36m
    • 白(white):\u001b[37m
    • 重置(reset) :\u001b[0m

    16 色

    在 8 色的基础上对字体加粗,颜色加亮,得到另外 8 种,加起来就是 16 色。

    \u001b[?;1m,其中 ? ∈ [30, 37]

    • 亮黑(black):\u001b[30;1m
    • 亮红(red):\u001b[31;1m
    • 亮绿(green):\u001b[32;1m
    • 亮黄(yellow):\u001b[33;1m
    • 亮蓝(blue):\u001b[34;1m
    • 亮品红(magenta):\u001b[35;1m
    • 亮蓝绿(cyan):\u001b[36;1m
    • 亮白(white):\u001b[37;1m
    const out = process.stdout;
    
    function colors8(pre, post, startCode = 30) {
      const codePointA = 'A'.codePointAt(0);
    
      let i = 0;
      while (i < 8) {
        const colorCode = startCode + i;
        const char = String.fromCodePoint(codePointA + i);
        out.write(`{pre}{colorCode}{post}{char} `);
        i++;
      }
      console.log('\u001b[0m');
    }
    
    function fgColors8() {
      colors8('\u001b[', 'm');
    }
    
    function fgColors8Bright() {
      colors8('\u001b[', ';1m');
    }
    
    fgColors8();
    fgColors8Bright();
    

    (更多…)

  • sdcv – 命令行版本的 StarDict

    因为没找到 StarDict 的快捷打开/隐藏键,每次都要用鼠标点,觉得很不爽,于是找了一下,发现有个命令行版本,使用 StarDict 的词库。

    sudo apt-get install sdcv
    
    $ sdcv -h
    sdcv - console version of StarDict.
    Usage: sdcv [OPTIONS] words
    -h, --help               display this help and exit
    -v, --version            display version information and exit
    -l, --list-dicts         display list of available dictionaries and exit
    -u, --use-dict bookname  for search use only dictionary with this bookname
    -n, --non-interactive    for use in scripts
    --utf8-output            output must be in utf8
    --utf8-input             input of sdcv in utf8
    --data-dir path/to/dir   use this directory as path to stardict data directory