如何检测用户是否在控制台输入了数据
有没有办法在终端窗口中检查用户是否输入了数据,而不需要使用会阻塞程序的 stdin
呢?
我正在用 Twisted Python 实现一个聊天客户端,客户端代码需要显示其他连接客户端发送的消息。当客户端输入一条消息并按下回车键时,我希望它能运行一个事件驱动的循环,把消息发送到服务器,然后服务器再把这条消息广播给其他所有客户端。
简单来说,我想找到一种方法,能够检测用户何时按下回车键或在终端中输入文本,而不需要让程序停下来等着。
更新:到目前为止的客户端代码……
class MyClientProtocol( protocol.Protocol ):
def sendData( self ):
message = raw_input( 'Enter Message: ' )
if message and ( message != "quit()" ):
logging.debug( " ...Sending %s ...", message )
self.transport.write( str( message ) )
else:
self.transport.loseConnection()
def connectionMade( self ):
print "Connection made to server!"
def dataReceived( self, msg ):
print msg
self.sendData()
class MyClientFactory( protocol.ClientFactory ):
protocol = MyClientProtocol
clientConnectionLost = clientConnectionFailed = lambda self, connector, reason: reactor.stop()
reactor.connectTCP( HOST, PORT, MyClientFactory() )
reactor.run()
这段代码目前只在从服务器收到数据后才接受用户输入,因为我在 dataReceived
中调用了 sendData
。有没有什么建议可以让我同时接收用户输入和从服务器获取数据呢?
2 个回答
0
我最近也试着玩了一下这个。我的做法是启动了一个单独的线程(使用threading
模块),这个线程在等待用户输入,而主线程则负责接收和打印广播消息,像这样:
def collect_input():
while True:
msg = raw_input()
handle(msg) # you'll need to implement this
# in client code
import threading
t = threading.Thread(target=collect_input)
t.start()
我不太确定这样做是否合适,但这是我想到的第一个办法,而且看起来是有效的。
注意:我没有使用Twisted
,只是用了sockets
。正如其他回答所示,你并不需要用Twisted来实现这个功能。
3
如果你已经在使用Twisted这个框架,它有很多插件可以让你把几乎任何东西都接入到事件循环中。
不过对于stdin
(标准输入),你甚至不需要插件,因为它是内置的。里面有一个示例正好展示了你想做的事情。这个示例叫做 stdin.py
。