[Tutor] Newbie Wondering About Threads
Damon Timm
damontimm at gmail.com
Sun Dec 7 21:10:46 CET 2008
On Sun, Dec 7, 2008 at 10:47 AM, Kent Johnson <kent37 at tds.net> wrote:
> A function as mentioned above would help. For the threaded solution
> the function could just start the child process and wait for it to
> finish, it doesn't have to return anything. Each thread will block on
> its associated child.
I think I did it! Woo hoo! (cheers all around! drinks on me!)
First, I found that using the Popen.communicate() function wasn't
going to work (because it sits there and waits for until it's done
before continuing); so, I ditched that, created my own little function
that returned the Popen object and went from there ... I mixed in one
super-long audio file file with all the others it seems to work
without a hitch (so far) ... watching top I see both processors
running at max during the lame processing.
Check it out (there are probably sexier ways to populate the *.mp3
files but I was more interested in the threads):
---
import time
import subprocess
totProcs = 2 #number of processes to spawn before waiting
flacFiles = [["test.flac","test.mp3"],["test2.flac","test2.mp3"],\
["test3.flac","test3.mp3"],["test4.flac","test4.mp3"],\
["test5.flac","test5.mp3"],["test6.flac","test6.mp3"]]
procs = []
def flac_to_mp3(flacfile,mp3file):
print "beginning to process " + flacfile
p = subprocess.Popen(["flac","--decode","--stdout","--silent",flacfile],
stdout=subprocess.PIPE)
p1 = subprocess.Popen(["lame","--silent","-",mp3file], stdin=p.stdout)
return p1
while flacFiles or procs:
procs = [p for p in procs if p.poll() is None]
while flacFiles and len(procs) < totProcs:
file = flacFiles.pop(0)
procs.append(flac_to_mp3(file[0],file[1]))
time.sleep(1)
------[EOF]------
Thanks again - onward I go!
Damon
More information about the Tutor
mailing list