Pausing a process or thread in Python
I've created a little audio player that looks up a chapter of an audiobook at a website I've specified, downloads it, and plays it. The only problem is, I can't pause it. To play the mp3 file I'm using os.system("afplay chapter.mp3")
I've thought about creating a thread with the os.system call in it but I'm pretty sure I can't pause it that way. If the thread was a loop I could just lock a variable it needs to access and unlock when I'm ready to resume. But since this thread would be just one line of code that doesn't seem possible. I've also looked at creating a process and sending SIGSTOP to it. But for some unknown reason that won't work.
import os, signal from multiprocessing import Process p = Process(target=play) p.start() raw_input("press enter to pause: ") os.kill(p.pid, signal.SIGSTOP)
The code just executes silently without stopping the process.
I know there are alternatives to afplay but for now I'm just going to stick with the os.system call. So my question is, How can I pause a one-line thread or process? Instead of creating a new process with the Process() call do I need to find the process id of afplay? If so how?
Why don't you just use the subprocess module instead of subprocess and os.system? That should give you better control over spawned processes.
os.system creates a child process and waits for that child process to exit. You can use os.execv to replace a process with another program, or use subprocess.Popen to create a child process that you can find the pid of with Popen.pid.