Rok
Rok

Reputation: 494

Simulate Ctrl-C to python script

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)

Upvotes: 1

Views: 5275

Answers (2)

Teddy
Teddy

Reputation: 6163

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.

Upvotes: 1

senderle
senderle

Reputation: 151177

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?

Upvotes: 6

Related Questions