简体   繁体   English

在Python中暂停进程或线程

[英]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") 要播放mp3文件,请使用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. 我曾考虑过使用os.system调用创建一个线程,但是我敢肯定我不能以这种方式暂停它。 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. 我也研究过创建一个进程并将SIGSTOP发送给它。 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. 我知道afplay有其他选择,但现在我只继续使用os.system调用。 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? 除了需要使用Process()调用来创建新进程外,我还需要查找afplay的进程ID? If so how? 如果可以,怎么办?

os.system creates a child process and waits for that child process to exit. os.system创建一个子进程并等待该子进程退出。 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 . 您可以使用os.execv与其他程序来替换进程,或使用subprocess.Popen创建一个子进程,你可以找到与PID Popen.pid

Why don't you just use the subprocess module instead of subprocess and os.system? 您为什么不只使用subprocess模块​​而不是subprocess和os.system? That should give you better control over spawned processes. 这样可以更好地控制生成的进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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