【问题标题】:Python Print overlapping with inputPython打印与输入重叠
【发布时间】:2021-08-20 09:17:03
【问题描述】:

我正在创建服务器并在控制台中显示一些信息,问题是用户/管理员正在输入控制台线程仍在将输入打印到控制台,然后很难输入,甚至命令很复杂。

显示该问题的代码:

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)

【问题讨论】:

  • 你正在同时做事
  • 是的,因为一个线程正在接受对服务器的请求而另一个正在管理数据库,这里的代码是问题的示例。
  • 如果您同时使用同一个控制台来显示程序的输出并接受用户的输入,那么您必须使用 Curses 之类的东西来复用控制台。

标签: python python-3.x input python-multithreading


【解决方案1】:

这个想法是使用ANSI escape codes 来操纵光标位置。所有输出都必须存储在每次更新时都会打印的列表中。

ANSI 命令

  • \033[s存储当前光标位置
  • \033[u重置光标位置
  • \33[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"\033[s{chr(27)}[{i+1}A\33[2K\r{line}\033[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 

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

【讨论】:

    猜你喜欢
    • 2015-07-20
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多