控制terminal

These are the most essential terminal control sequences that you will need for your train program.

Code Effect
“\033[2J” Clear the screen.
“\033[H” Move the cursor to the upper-left corner of the screen.
“\033[r;cH” Move the cursor to row r, column c. Note that both the rows and columns are indexed starting at 1.
“\033[?25l” Hide the cursor.
“\033[K” Delete everything from the cursor to the end of the line.

颜色

  属性
0 无属性
1 高亮
4 下划线
5 闪烁
7 反显
8 消隐
9 删除线
颜色 彩色文本 彩色背景
黑色 30 40
红色 31 41
绿色 32 42
黄色 33 43
蓝色 34 44
紫色 35 45
青色 36 46
白色 37 47
attr = {
    "no": 0,
    "highlight": 1,
    "underline": 4,
    "flash": 5,
    "reverse": 7,
    "blanking": 8,
    "delete": 9,
}

fore = {
    "black": 30,
    "red": 31,
    "green": 32,
    "yellow": 33,
    "blue": 34,
    "purple": 35,
    "cyan": 36,
    "white": 37,
}

back = {
    "black": 40,
    "red": 41,
    "green": 42,
    "yellow": 43,
    "blue": 44,
    "purple": 45,
    "cyan": 46,
    "white": 47,
}

def show(mesg, attr=0, fore=37, back=40):
    reset = "\x1B[0m"
    color = "\x1B[%d;%d;%dm" % (attr,fore,back)
    print("{color}{mesg}{reset}".format(color=color, mesg=mesg, reset=reset),
          flush=True)

for ak,av in attr.items():
    for fk,fv in fore.items():
        for bk,bv in back.items():
            show("attr:{ak}\tfore:{fk}\tback:{bk}".format(ak=ak,fk=fk,bk=bk),
                 attr=av, fore=fv, back=bv)

格式

Format Specification Mini-Language

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  integer
grouping_option ::=  "_" | ","
precision       ::=  integer
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"