Skip to main content
 首页 » 编程设计

python之在 Python 中停止进程

2024年10月25日9Terrylee

我正在运行一个程序,我想在按下某个按钮时停止该程序。

我正在考虑在后台运行该进程,以便在此过程中随时可以按下按钮,它会停止它。

我从文档中阅读了有关子流程的内容,但作为初学者我不知道如何使用它,感谢任何帮助。

def put(command): 
        os.system(command) 
 
        if direct == "": 
            time.sleep(.5) 
            arg1 = put("sudo ffmpeg -i \"" + q3 + "\" -f s16le -ar 22.05k -ac 1 - | sudo ./pifm - " + str(freq))  
            subprocess.Popen(arg1) 
            while True: 
                if RPIO.input(25) == GPIO.LOW: #if button is pushed, kill process (arg1) 
                    Popen.terminate() 

请您参考如下方法:

如果你想控制你的子进程,你最好使用subprocess模块。如果您通过 Popen 创建它,您将能够通过 kill() 或 terminate() 方法停止它。

例子

import subprocess 
# ... 
sub = subprocess.Popen(command) 
# ... 
sub.kill() 

而且你确定你正在杀死你自己的 child ,即使有许多命令同时运行