Easy way python async method wanted

200 views Asked by At

I am developing a small media player app on raspberry pi. So This have two main functions. Namely radio and file player. If entered into file player below is the code :

        
        process = subprocess.Popen(['omxplayer',songs[0],'-o','local'],  stdout=subprocess.PIPE )
        #stdout = process.communicate()[0]
        
        nxt=0
        while True:
            print("looping")
            output = process.stdout.readline()
            if nxt>1:     
                process = subprocess.Popen(['omxplayer', songs[nxt],'-o','local'], stdout=subprocess.PIPE)
                output = process.stdout.readline()
                #stdout = process.communicate()[0]
                
            if output =='' :
                print("2")
            if output:
                print("finshed")
                nxt=nxt+1
            if GPIO.input(7)==0:
                break

The problem is code after and outside this loop doesnt work before the subprocess is finished. How can I use ayncio so that some gpio readings can be taken and exit this loop once needed ? I really spent 8 hours to figureout this googling this. But all available tutorials are very difficult to understand.

1

There are 1 answers

0
ti7 On

If you're interacting with a live process, you need to have some handle to do so - often this will look like a socket, which seems to be what the process expects from these examples (briefly skimmed)

However, in order for your Python process to also do some logic while managing this, you'll need one of the following

  • threading: likely easier to reason about, but with more troublesome caveats (limited maximum interactions, cleanup, serializing commands..)
  • asyncio: likely the best choice overall, but potentially more troublesome to reason about at first
  • multiprocessing: similar to threading, but perhaps the most troublesome to reason about (ie. how do the processes communicate?) and least beneficial for your case (simply writing or reading a socket)

It's beyond the scope of the question, but to get started, you may find it easy to

  • write a small test script for interacting with sockets to learn how they work
  • play with with a good, but simple async web framework like Tornado to understand how asynchronous logic behaves
  • combine 'em using with Tornado's IOStream logic to make a complete example
  • continue with your new design ideas