我有一个使用 SocketServer 在 Python 中制作的简单服务器应用程序,它有一个非常原始的命令行类型输入系统。我的主要问题是,当服务器收到一条消息时,它会将其打印到屏幕上。这一切都很好,只是 raw_input 函数仍在等待输入和检查文本。有没有办法在服务器 handle() 函数中停止 raw_input 或引发一些异常来结束输入并显示服务器正在接收的信息?
谢谢,
扎克。
据我所知,这是不可能的,因为 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()
另一种选择是创建自己的 print 和 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))