Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python script doing multiple things at once

I’m trying to make a raspberry pi control an addressable LED strip using a webserver. Because I can’t port forward, the webserver is hosted on python anywhere and the pi is constantly sending get requests to see if it needs to change the lighting.

Certain lighting effects will have their own timings and will need to loop on their own, like a rainbow effect for instance which will loop and update the LED colours at 10Hz. How can I have a script updating the LED colours while it also has to send the get requests? The get requests are relatively slow, so putting them in the same loop doesn’t seem like a viable option.

Edit:
Thanks for the responses. Turns out I was looking for asynchronous programming.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do this pretty simply with asyncio. Do note that for doing web requests you should also use an async library like aiohttp. Otherwise the blocking http call will delay the other task from running.

Here’s an example where you use a context object to allow sharing data between the different tasks. Both tasks will need to have some await calls in them which is what allows asyncio to switch between the running tasks to achieve concurrency.

import asyncio

class Context:
    def __init__(self):
        self.message = 0

async def report(context):
    while True:
        print(context.message)
        await asyncio.sleep(1)

async def update(context):
    while True:
        context.message += 1
        await asyncio.sleep(3)

async def main():
    context = Context()
    await asyncio.gather(report(context), update(context))

if __name__ == "__main__":
    asyncio.run(main())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading