1

私はSocketServerを使用してPythonで作成した単純なサーバーアプリケーションを持っています。それは非常に原始的なコマンドラインタイプの入力システムを持っています。ここでの私の主な問題は、サーバーがメッセージを受信すると、それを画面に出力することです。raw_input関数がテキストの入力とチェックを待機していることを除けば、これはすべて問題ありません。サーバーのhandle()関数で、raw_inputを停止するか、入力を終了してサーバーが受信している情報を表示する例外を発生させる方法はありますか?

ありがとう、
ザック。

4

1 に答える 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()

もう1つのオプションは、次のような独自の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))
于 2010-11-19T00:26:57.603 に答える