在enter键按下之前,如何将通过keybord输入的文本打印到python的input()方法?

2024-10-01 05:05:45 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的多线程(2个线程)python程序中,两个线程都写入控制台。主线程使用input()接受命令,另一个线程从服务器获取一些数据并打印一些消息。我已经通过将'\r'打印到控制台,成功地将输入提示符(第一个线程)移动到新行。但是我找不到一种方法来恢复在半路上的输入。我如何才能做到正确的行为

这是程序中的一段代码:

class GetServerData:
    def mainthread(self, interval):
        updates = threading.Thread(target=self.getUpdates, args={interval})
        updates.start()
        self.threadsrunning = True

        self.continuemainloop = True
        while(self.continuemainloop):
            self.promptinput()
            command = input()
            if(command == "")
                self.promptinput()
            elif(command=="quit")
                self.continueloop = False
                print("\rWaiting for all threads to terminate ...")
                while(self.threadsrunning)
                    pass
                self.continuemainloop = False
        print("Program terminated")


    def getUpdates(self, interval)
        self.continueloop  = True
        while(self.continueloop):
            #Code for getting data from server
            #and print/process the response
            #if server responds
            time.sleep(15)
            print("\rReceived Updates ...") #This prints at the current line
            #After this, prompt should be shown
            #If something was being typed, it should also be shown here
            self.promptinput()
        self.threadsrunning = False


    def promptinput(self):
        print(" >> ", end='', flush=True) #Prompt shows without moving to next line
        #TODO : Print current keyboard input which is not finished yet

在提示prints>>之后我应该放置什么来显示未完成的输入


Tags: self程序falsetrueinputdef线程command