简体   繁体   English

子流程管理-杀死子流程

[英]Subprocess management - Killing a subprocess

I have been trying to make a python script that will play on Mac OS X and I have gotten it to work with a .py script in Terminal, but I can't stop it. 我一直试图制作一个可以在Mac OS X上播放的python脚本,并且已经在Terminal中将其与.py脚本一起使用,但是我无法停止它。 I have been trying for weeks, os.kill() , process.terminate() , everything I could find on other StackOverflow questions. 我已经尝试了数周的os.kill()process.terminate() ,这是我在其他StackOverflow问题上可以找到的所有东西。 Here is my code, can anyone tell me the proper way to terminate this sub-process? 这是我的代码,有人可以告诉我终止该子流程的正确方法吗? (I believe I am using python 2.7) (我相信我正在使用python 2.7)

import time
import subprocess

subprocess.call(["afplay", "/Users/0095226/Desktop/introsong.wav"])
time.sleep(4)
(WHATEVER KILLS IT HERE PLEASE)

You need to use subprocess.Popen() as you can assign the process handle to a variable and later kill it. 您需要使用subprocess.Popen(),因为您可以将进程句柄分配给变量,然后将其杀死。

import time
import subprocess

p = subprocess.Popen(["calc"])
time.sleep(4)
p.kill()

The other method is to use os.kill() along with signal.SIGINT to kill the process, as seen here: 另一种方法是使用os.kill()具有沿signal.SIGINT杀死的过程中,如这里看出:

import time
import signal
import subprocess
import os

p = subprocess.Popen(["calc"])
time.sleep(4)
os.kill(p.pid, signal.SIGINT)

We are able to access the PID (Process ID) and therefore we can kill it using os.kill() . 我们能够访问PID(进程ID),因此可以使用os.kill()os.kill() signal is the module which contains codes for how to kill the process, eg send it the abort (SIGABRT), interrupt (SIGINT) etc. signal是包含有关如何终止进程的代码的模块,例如,向其发送中止(SIGABRT),中断(SIGINT)等。

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

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