如果有其他文本显示,如何终止 raw_input()

1 投票
1 回答
1039 浏览
提问于 2025-04-16 07:18

我有一个简单的服务器应用程序,是用Python的SocketServer写的,输入系统非常简单,像命令行那样。我的主要问题是,当服务器收到一条消息时,它会把消息打印到屏幕上。这本来没什么问题,但问题在于,raw_input函数还在等着用户输入文本。这时候有没有办法在服务器的handle()函数里停止raw_input,或者抛出一个异常,让输入结束,并显示服务器正在接收的信息呢?

谢谢,
扎克。

1 个回答

1

据我所知,这个功能是无法实现的,因为raw_input是从Python命令控制台接收输入的。不过,有一些意想不到的方法可以绕过这个限制:

1 - 你可以不使用控制台,而是创建一个简单的Tkinter窗口,里面有输出信息和一个输入框。你可以自定义一个打印函数,把消息添加到窗口文本的末尾(可以使用固定宽度的字体,并加上滚动条),然后再创建一个命令提示框,让它在按下回车时响应。这样的代码大概是这个样子的:

from Tkinter import *
root = Tk()
topframe=Frame(root)
bottomframe=Frame(root)
bottomframe.pack(side=BOTTOM,fill=X)
topframe.pack(side=TOP,fill=BOTH)
scrollbar = Scrollbar(topframe)
scrollbar.pack(side=RIGHT,fill=Y)
text = Text(topframe,yscrollcommand=scrollbar.set)
text.pack(side=LEFT,fill=BOTH)
scrollbar.config(command=text.yview)
text.config(state=DISABLED)
v = StringVar()
e = Entry(bottomframe,textvariable=v)
def submit():
    command = v.get()
    v.set('')
    #your input handling code goes here.
    wprint(command)
    #end your input handling
e.bind('<Return>',submit)
button=Button(bottomframe,text='RUN',command=submit)
button.pack(side=RIGHT)
e.pack(expand=True,side=LEFT,fill=X)
def wprint(obj):
    text.config(state=NORMAL)
    text.insert(END,str(obj)+'\n')
    text.config(state=DISABLED)
root.mainloop()

另一个选择是自己创建打印和raw_input方法,代码看起来可以是这样的:

import threading
wlock=threading.Lock()
printqueue=[]
rinput=False
def winput(text):
    with wlock:
        global printqueue,rinput
        rinput=True
        text = raw_input(text)
        rinput=False
        for text in printqueue:
            print(text)
        printqueue=[]
        return text
def wprint(obj):
    global printqueue
    if not(rinput):
        print(str(obj))
    else:
        printqueue.append(str(obj))

撰写回答