命令行工具,可以使每行的输出颜色不一样

创建日期: 2023-01-08 14:05 | 作者: 风波 | 浏览次数: 15 | 分类: Python

1. 使用方法

2. 代码

#!/bin/bash

cmd='
# -*- coding: utf-8 -*-

import sys
import argparse
import random


conf_ = dict()

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
            "-n",
            action="store_true",
            help="no color",
            default=False
            )
    parser.add_argument(
            "-r",
            action="store_true",
            help="random color",
            default=False
            )
    args = parser.parse_args()
    return args


def print_start_color(args):
    if args.n:
        return True
    fmt = ""
    if args.r:
        cnt = (conf_.get("cnt", 0) + random.randint(1, 5)) % 7 + 1
        conf_["cnt"] = cnt
        fmt = "\033[0;3{}m".format(cnt)
    else:
        cnt = (conf_.get("cnt", 0) + 1) % 7 + 1
        fmt = "\033[0;3{}m".format(cnt)
        conf_["cnt"] = cnt
    sys.stdout.write(fmt)
    #print(fmt, end="")
    return True


def print_end_color(args):
    if args.n:
        return True
    sys.stdout.write("\033[0;m")
    #print("\033[0;m", end="")


def main():
    args = parse_args()
    for line in sys.stdin:
        print_start_color(args)
        #print(line, end="")
        sys.stdout.write(line)
        print_end_color(args)


if "__main__" == __name__:
    main()

'

python -c "${cmd}" ${@}
15 浏览
8 爬虫
0 评论