我在Python中使用signarcore客户机:https://github.com/mandrewcito/signalrcore
我正在使用上面git源代码中的聊天示例,并为我的应用程序修改了它。你知道吗
我试图在函数中放置while循环,当调用另一个函数时while循环的条件应该中断。但它被困在while循环中。你知道吗
这是我的密码:
from signalrcore.hub_connection_builder import HubConnectionBuilder
def input_with_default(input_text, default_value):
value = input(input_text.format(default_value))
return default_value if value is None or value.strip() == "" else value
def start_msg(msg):
while end_event.has_been_called == False:
Print("Starting")
sleep(1)
def end_event(endmsg):
end_event.has_been_called = True
pass
print("End Event")
server_url = input_with_default('Enter your server url(default: {0}): ', "ws://localhost:62342/chathub")
username = input_with_default('Enter your username (default: {0}): ', "sam")
hub_connection = HubConnectionBuilder().with_url(server_url).with_automatic_reconnect({
"type": "raw",
"keep_alive_interval": 10,
"reconnect_interval": 5,
"max_attempts": 5
}).build()
end_event.has_been_called = False
hub_connection.on("StartEvent", start_msg)
hub_connection.on("EndEvent", end_event)
hub_connection.start()
message = None
# Do login
while message != "exit()":
message = input(">> ")
if message is not None and message is not "" and message is not "exit()":
hub_connection.send("SendMessage", [username, message])
hub_connection.stop()
在这段代码中,当它接收到带有StartEvent的消息时,它进入start\u msg函数并开始打印“Starting”,但一旦收到EndEvent,它就应该进入end\u event函数,但它只是在while循环中卡住了,并且永远不会跳出它。你知道吗
如果我删除while循环,那么它可以正常工作,但是我需要它在start\u msg中保持while循环,直到调用end\u事件。你知道吗
我怎样才能做到这一点?你知道吗
编辑:为了澄清,我指的是这个while循环:
def start_msg(msg):
while end_event.has_been_called == False:
Print("Starting")
sleep(1)
首先,我要谈谈你的if声明
与其让if语句复杂化,不如指定一个列表
conditions = [None, "", "exit()"]
那你就可以了
if message not in conditions:
如果有必要的话,你可以扩大你的条件。还有一点优雅
第二,我要把这当成一门课。
end_event.has_been_called
正在为一个函数分配一个属性,该函数是wierd。你知道吗最后,开始事件应该称为结束事件。除非这个模块以某种方式异步运行(我没有安装它),否则您将永远无法进行
end_event
函数调用,因此您将陷入循环中。希望这有帮助相关问题 更多 >
编程相关推荐