继续循环并继续 (Python)
我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,因为您本质上要同时做两件事,所以您必须创建一个新线程(使用
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 (usingmultiprocessing
or justos.fork
)The easiest thing to do is to put this part in a function, and use
multiprocessing
orthreading
to start the function in a different process. Typically you'll have less weirdness with multiple processes than multiple threads, just FYI.