【发布时间】:2022-01-05 18:14:33
【问题描述】:
一直在努力让它工作,因为我无法在不会结束的 while 循环中使用 return。
简而言之,我在一个函数receive()(无限循环)的套接字客户端中接收到一条消息,并且需要将该传入消息的结果传递给main()。尝试使用yield,因为我不确定还有什么可以实现这一点。我创建了另一个函数来尝试在receive() 函数中捕获yield。
我知道初始消息到达服务器是因为它输出了消息,并且我知道客户端正在接收服务器的确认消息,因为它正在打印它。我只是没有运气将该数据传递给main(),因此其余代码将无法正常工作。
我对此很陌生,所以我可能做错了。我应该使用类来更轻松地共享数据,但还没有充分掌握它们。希望使用 yield 或其他方法可以解决这个问题。
接收函数:
def receive():
while True:
try:
incoming = client.recv(2048).decode(FORMAT)
if 'RECEIVED' in incoming:
confirmation = 'confirmed'
yield confirmation
print(incoming)
except:
print("Connection interrupted.")
client.close()
break
#------------
# also tried
#------------
def receive():
while True:
try:
incoming = client.recv(2048).decode(FORMAT)
if 'RECEIVED:COMPLETE' in incoming:
confirmation = 'confirmed'
else:
confirmation = 'unconfirmed'
yield confirmation
except:
print("Connection interrupted.")
client.close()
break
返回函数:
def pass_return(passed_return_value):
passed_return_value
主函数(带有各种测试)
def main():
pass_return(receive())
# Bunch of code
if something == True:
send("some message")
time.sleep(.25)
try:
if confirmation == 'confirmed':
# do the business here
#------------
# also tried
#------------
def main():
# Bunch of code
if something == True:
send("some message")
time.sleep(.25)
pass_return(receive())
try:
if confirmation == 'confirmed':
# do the business here
#------------
# also tried
#------------
def main():
r = pass_return(receive())
# Bunch of code
if something == True:
send("some message")
time.sleep(.25)
try:
if r == 'confirmed':
# do the business here
#------------
# even tried
#------------
def main():
# Bunch of code
if something == True:
send("some message")
time.sleep(.25)
r = pass_return(receive())
try:
if r == 'confirmed':
# do the business here
我声明变量 confirmation OUTSIDE of main() 和 receive()(在我的常量所在的文件顶部),否则我会收到 confirmation is undefined 的错误。
如果我在main() 中print confirmation,它要么不打印,要么不打印None,所以我猜它只是得到confirmation 的初始空值而不是yield。
# constants above here
confirmation = str()
# code and such
def pass_return(passed_return_value):
passed_return_value
def receive():
#code...
def main():
#code...
if __name__ == '__main__':
main()
【问题讨论】:
-
编写以非阻塞方式正确处理此类事情的代码是一个非常广泛的主题。您可能想了解现有框架是如何做到这一点的(例如,Python 的 Discord API)。
标签: python function if-statement variables while-loop