简体   繁体   中英

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. 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

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.

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

do_stuff(received)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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