模拟 Ctrl-C 到 python 脚本

发布于 2025-01-08 11:53:46 字数 676 浏览 0 评论 0原文

我有一个 python 脚本,它等待一些作业并在线程中执行它们(使用 subprocess.Popenshell=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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅紫色的梦幻 2025-01-15 11:53:46

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

您是否尝试过Popen.send_signal

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

Raising KeyboardInterrupt in the main process raises KeyboardInterrupt 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?

盛夏尉蓝 2025-01-15 11:53:46

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 with kill to send SIGINT to a process group.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文