简体   繁体   English

继续循环并继续前进(Python)

[英]Continuing a Loop and Moving On (Python)

I have a 'while' loop in my Python app (v2.7) which basically communicates with a Bluetooth GPS device and the loop continues for as long as there is data being received. 我的Python应用程序(v2.7)中有一个“ while”循环,该循环基本上与Bluetooth GPS设备通信,并且只要接收到数据,循环就持续进行。 In essence, the while loop looks like this:- 本质上,while循环看起来像这样:

> data = ""
> 
> if data == None:
>     print "Connection Failed" else:
>     print "Connection Established"
> 
> while True:
>     data = socket.recv(1024)

Now what I want to do is leave this while loop running continually throughout the life of the program until the bluetooth device is switched off which in turn will end the loop as no data will be being received. 现在,我要做的是在程序的整个生命周期中让此while循环不断运行,直到关闭蓝牙设备为止,这又将由于没有数据接收而结束循环。 Nonetheless, as this while loop continues, I then want to move onto another method which will parse the data. 尽管如此,随着while循环的继续,我然后想转到另一个将解析数据的方法。

How can I leave the loop running and move on to the next command? 如何使循环运行并继续执行下一个命令? Is threading required? 需要穿线吗? I'm new to the concept of threading and so please be patient with me :) 我是线程概念的新手,所以请耐心等待:)

Thanks 谢谢

Yeah, because you're essentially going to be doing two things at the same time, you'll have to create a new thread (using threading ) or perhaps more simply a new process (using multiprocessing or just os.fork ) 是的,因为实际上您将同时做两件事,所以您必须创建一个新线程(使用threading ),或者可能更简单地创建一个新进程(使用multiprocessing或仅使用os.fork

The easiest thing to do is to put this part in a function, and use multiprocessing or threading to start the function in a different process. 最简单的方法是将此部分放入函数中,并使用multiprocessingthreading在不同的进程中启动该函数。 Typically you'll have less weirdness with multiple processes than multiple threads, just FYI. 通常,与多个线程相比,与FYI相比,您对多个进程的怪异更少。

received = ""
while True:
     data = socket.recv(1024)
     if not data:
         break # ends the while loop
     received+=data

do_stuff(received)

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

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