![](/img/trans.png)
[英]DataReceivedEvent not hit while Interacting with (Python) process from redirected input/output/error
[英]Python: readline/input() interacting with output from different threads
我正在编写一个带有交互式控制台的多线程程序:
def console()
import readline
while True:
data = input()
do_whatever(data.split())
但是,我正在使用的库从不同的线程运行我的回调。 回调需要打印到控制台。 因此我想清除命令行,重新显示提示,并重新显示命令行。
如果没有重新实现readline
,我该怎么做?
从这个解决 C 问题的答案开始,我得到了以下 Python 代码,它对我的目的来说效果很好:
import os
import readline
import signal
import sys
import time
import threading
print_lock = threading.Lock()
def print_safely(text):
with print_lock:
sys.stdout.write(f'\r\x1b[K{text}\n')
os.kill(os.getpid(), signal.SIGWINCH)
def background_thread():
while True:
time.sleep(0.5)
print_safely('x')
threading.Thread(target=background_thread, daemon=True).start()
while True:
try:
inp = input(f'> ')
with print_lock:
print(repr(inp))
except (KeyboardInterrupt, EOFError):
print('')
break
print_safely
\\r\\x1b[K
( CR + CSI 代码EL ) 删除现有的 Readline 提示可能存在的问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.