Skip to main content
 首页 » 编程设计

python之模拟 Ctrl-C 到 python 脚本

2025年05月04日17kevingrace

我有一个 python 脚本,它等待一些作业并在线程中执行它们(使用 subprocess.Popen 和 shell=True)。当我在 shell 中运行脚本并尝试使用 Ctrl-C 终止它时,它会正常且干净地关闭。

问题是我想将此脚本作为守护进程运行,然后使用某种 unix 信号终止它。 INT 信号应与 Ctrl-C 相同,但工作方式不同。它让 subproces.popen 的子进程继续运行。

我还尝试在收到信号时在主线程中引发 KeyboardInterupt,但这也无法关闭脚本并终止所有子进程。

有什么关于如何模拟 Ctrl-C 的建议吗?

调用 subprocess.popen 的示例:

shell_cmd = "bwa aln -t 8 file1.fasta file1.fastq.gz > file1.sam.sai" 
process = subprocess.Popen(shell_cmd, 
                           shell=True, 
                           stderr=subprocess.PIPE) 

请您参考如下方法:

在主进程中引发 KeyboardInterrupt 在主进程中引发 KeyboardInterrupt。您必须将信号发送到子流程。

你试过了吗Popen.send_signal ?

或者,更直接地说,Popen.terminate ?