模拟 Ctrl-C 到 python 脚本
我有一个 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)
I have a python script which waits for some jobs and executes them in threads (using subprocess.Popen
with shell=True
). When I run a script in a shell and try to terminate it with Ctrl-C
it closes down normally and cleanly.
The problem is I want to run this script as a daemon and then terminate it using some kind of unix signal. INT
signal should be the same as Ctrl-C
but it doesn't work in the same way. It leaves child processes of subproces.popen
running.
I also tried raising KeyboardInterupt
in main thread when I receive the signal, but that also fails to close the script and kill all children processes.
Any suggestions how to emulate Ctrl-C
?
Example of call to 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在主进程中引发
KeyboardInterrupt
会在主进程中引发KeyboardInterrupt
。您必须将信号发送到子进程。您是否尝试过
Popen.send_signal
?或者,更直接地说,
Popen.terminate
?Raising
KeyboardInterrupt
in the main process raisesKeyboardInterrupt
in the main process. You have to send the signal to the subprocesses.Have you tried
Popen.send_signal
?Or, even more straightforwardly,
Popen.terminate
?Ctrl-C 向整个进程组发送 SIGINT,不仅仅是一个进程。使用 os.killpg() 或带有
kill 的负进程 ID 向进程组发送 SIGINT。
Ctrl-C sends SIGINT to the entire process group, not just one process. Use
os.killpg()
or a negative process id withkill
to send SIGINT to a process group.