继续循环并继续 (Python)

发布于 2024-12-05 10:05:22 字数 486 浏览 0 评论 0原文

我的 Python 应用程序 (v2.7) 中有一个“while”循环,它基本上与蓝牙 GPS 设备通信,并且只要收到数据,循环就会继续。本质上, while 循环看起来像这样: -

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

现在我想做的是让这个 while 循环在程序的整个生命周期中持续运行,直到蓝牙设备关闭,这反过来会结束循环,因为不会有数据被传送已收到。尽管如此,随着这个 while 循环的继续,我想转向另一个解析数据的方法。

如何让循环继续运行并继续执行下一个命令?是否需要穿线?我对线程的概念很陌生,所以请耐心等待:)

谢谢

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. In essence, the while loop looks like this:-

> 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. Nonetheless, as this while loop continues, I then want to move onto another method which will parse the data.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

像极了他 2024-12-12 10:05:22

是的,因为您本质上要同时做两件事,所以您必须创建一个新线程(使用 threading),或者更简单地创建一个新进程(使用 多处理或只是os.fork

最简单的方法是将这部分放在函数中,并使用多处理线程 在不同的进程中启动该功能。通常,与多线程相比,多进程的怪异程度要少一些,仅供参考。

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)

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. Typically you'll have less weirdness with multiple processes than multiple threads, just FYI.

小糖芽 2024-12-12 10:05:22
received = ""
while True:
     data = socket.recv(1024)
     if not data:
         break # ends the while loop
     received+=data

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

do_stuff(received)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文