Python 打印与输入重叠

Python Print overlapping with input

我正在创建服务器,它在控制台中显示了一些信息,问题是 user/admin 正在输入控制台线程仍在将输入打印到控制台,然后很难输入,甚至更多然后命令是复杂。

显示该问题的代码:

import threading
import random
import time

def some_process():  # simulation of server that print some info in background
    for i in range(50)
        time.sleep(random.randint(1, 3))
        print("Some program output")

thread = threading.Thread(target=some_process)
thread.start()

while True:
    shell = input("> ")
    # rest of shell like "help", "exit" and some things like that

输出:

> connect localhoSome program output
st 4665 SSL=TrSome program output
ue

我排除的:

Some program output
Some program output
> connect localhost 4665 SSL=True  # That line move then something print.

如果可能的话,我正在寻找最跨平台的解决方案。 (大多数人都在寻找 windows 解决方案,但也需要 linux)

思路是用ANSI escape codes来操作光标位置。所有输出都必须存储在一个列表中,该列表将在每次更新时打印。

ANSI 命令

  • 3[s 存储当前光标位置
  • 3[u重置光标位置
  • [2K 擦除当前行
  • [NA 光标向上移动N行
  • [2J清除终端

chr(27)是转义

import threading
import random
import time

output_lines = []

def print_above(message):
    global output_lines
    output_lines.append(message)
    
    for i, line in enumerate(reversed(output_lines)):
        print(f"3[s{chr(27)}[{i+1}A[2K\r{line}3[u", end="")

def some_process():  # simulation of server that print some info in background
    for i in range(12):
        time.sleep(0.1*random.randint(5, 10))
        print_above(f"Thread output {12-i}")

thread = threading.Thread(target=some_process)
thread.start()

print(chr(27) + "[2J") # clearing the terminal
while True:
    shell = input("> ")
    print_above(f"shell {shell}")

示例输出

Thread output 12
Thread output 11
Thread output 10
Thread output 9
shell 123
Thread output 8
Thread output 7
Thread output 6
Thread output 5
Thread output 4
Thread output 3
Thread output 2
Thread output 1
> 987654321 

这不是一个完美的解决方案,因为它可能无法很好地处理许多边缘情况,并且可能无法在所有终端上运行。它可能还需要补充才能真正很好地处理线程。