2016-09-26 56 views
0

我使用Python的cmd模块来处理终端输入循环。在用户按下输入之前跟踪当前输入

我有一个线程在后台运行,当它收到一条消息时,它会在终端打印出一些东西。这些消息打破了视觉用户输入:

> writing a com 
@@@ message generated from a thread and printing during user input @@@ 
mand 

我问一个相关的问题here,并已基本告知,以避免破坏用户的输入办法之一是跟踪用户输入的,所以当消息传入我可以打印消息并重新打印用户输入。当我问这个问题时,我没有使用cmd模块。

当使用cmd模块时,我将如何跟踪用户当前输入的内容,以便我可以重印它?

回答

0

我发现了readline module和它的get_line_buffer()方法。

这里是我如何解决它,因为要打印出来的数据,同时我在读用户输入在主线程:

import readline 
# Save the current buffer 
current_buffer = readline.get_line_buffer() 
# Print our stuff, note the \r is important to overwrite the current buffer 
print("\rladida interruption\nsome more interruption\n") 
# Reprint our buffer 
print('> ' + current_buffer, end='', flush=True) 

下面是一个例子,前:

$ ./main.py 
> help 

和之后:

$ ./main.py 
ladida interruption 
some more interruption 

> help 

请注意命令提示符如何干净地向下移动,用户当前命令输入在pl高手。光标也处于正确的位置继续打字,退格键也可以正常工作。