简体   繁体   English

从无限的while循环中在函数之间传递数据

[英]Passing data between functions from endless while loop

Been struggling to get this to work because I can't use return in a while loop that is not going to end.一直在努力让它工作,因为我不能在一个不会结束的 while 循环中使用return

In a nutshell, I'm receiving a message in a socket client in one function receive() (the endless loop) and need to pass the result of that incoming message to main() .简而言之,我在一个 function receive() (无限循环)的套接字客户端中接收到一条消息,并且需要将该传入消息的结果传递给main() Trying to use yield , since I'm not sure what else would achieve this.尝试使用yield ,因为我不确定还有什么可以实现这一点。 I created another function to try and capture the yield in the receive() function.我创建了另一个 function 来尝试在receive() function 中捕获yield

I know the initial message reaches the server because it outputs the message, and I know the client is receiving the server's confirmation message because it's printing it.我知道初始消息到达服务器是因为它输出消息,并且我知道客户端正在接收服务器的确认消息,因为它正在打印它。 I just am having no luck passing that data to main() , so the rest of the code won't work right.我只是没有运气将该数据传递给main() ,因此代码的 rest 将无法正常工作。

I'm very new to this, so I'm probably doing this horribly wrong.我对此很陌生,所以我可能做错了。 I should be using classes to share data more easily, but don't grasp them enough yet.我应该使用类来更轻松地共享数据,但还没有充分掌握它们。 Hopefully using yield or something else can get around that.希望使用产量或其他东西可以解决这个问题。

receive function:接收 function:

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

return function:返回 function:

def pass_return(passed_return_value):
    passed_return_value

main function (with various tests)主function(带各种测试)

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

I'm declaring the variable confirmation OUTSIDE of main() and receive() (atop the file where my constants are) or else I get an error of confirmation is undefined .我在main()receive()的外部声明变量confirmation (在我的常量所在的文件顶部),否则我得到一个confirmation is undefined

If I print confirmation in main() , it either prints nothing or None , so my guess is that it's just getting the initial empty value of confirmation and not the yield .如果我在main()print confirmation ,它要么不打印,要么不打印,所以我的猜测是它只是获得了confirmation的初始None值而不是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()

Note that Python is single-threaded.请注意,Python 是单线程的。 If your program is supposed to do nothing else than waiting for a data to arrive on the socket from an external source, and reacting to it, then this would work:如果您的程序除了等待数据从外部源到达套接字并对其做出反应之外什么都不做,那么这将起作用:

def receive():
    while True:
        try:
            incoming = client.recv(2048).decode(FORMAT)
            if 'RECEIVED' in incoming:
                yield {'status': 'confirmed', 'message': incoming}
            else:
                yield {'status': 'unconfirmed', 'message': incoming}
        except:
            print("Connection interrupted.")
            client.close()
            break

def main():
    for message in receive():
        print(message)

Here, most of this program's time will be spent on client.recv(2048) .在这里,这个程序的大部分时间将花在client.recv(2048)上。 This is a blocking call.这是一个阻塞调用。 It does not return until the requested number of bytes is received.在收到请求的字节数之前它不会返回。 Nothing else can happen in your program during this time.在此期间,您的程序中不会发生任何其他事情。

As soon as the bytes are received, you can yield , and the for loop inside main() can process the data.一旦接收到字节,您就可以yield ,并且main()中的for循环可以处理数据。 When that's done, the program flow will return to client.recv(2048) and sit there.完成后,程序流将返回到client.recv(2048)并坐在那里。

If you want different things to happen in your program while it also listens for data on that socket, you will need to look into multithreading, and put this code on a background thread.如果您希望程序侦听该套接字上的数据的同时发生不同的事情,则需要研究多线程,并将此代码放在后台线程上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM