I am trying to run a Linux command strace -c ./client
in python with os.system()
. When I press Ctrl + C I get some output on the terminal. I have to send the "Process correctly halted" signal programmatically after one minute and want the terminal output that is produced after pressing Ctrl + C in a file.
A pseudo script will be really helpful. If I use subprocess.Popen
and then send Ctrl + C signal from keyboard I didn't get output on the terminal,so have to use os.system
Asked
Active
Viewed 3.1k times
11

Neuron
- 5,141
- 5
- 38
- 59

user2591307
- 119
- 1
- 2
- 6
2 Answers
10
In Python, you could programatically send a Ctrl + C signal using os.kill
. Problem is, you need the pid
of the process that'll receive the signal, and os.system
does not tell you anything about that. You should use subprocess
for that. I don't quite get what you said about not getting the output on the terminal.
Anyways, here's how you could do it:
import subprocess
import signal
import os
devnull = open('/dev/null', 'w')
p = subprocess.Popen(["./main"], stdout=devnull, shell=False)
# Get the process id
pid = p.pid
os.kill(pid, signal.SIGINT)
if not p.poll():
print("Process correctly halted")

Neuron
- 5,141
- 5
- 38
- 59

José Tomás Tocino
- 9,873
- 5
- 44
- 78
-
I think your last line, if not p.poll(), might be wrong. poll() returns None if the process is still running, not None is True, so you print the message if the process is still running, not if it has stopped. – ColinBroderick Nov 25 '21 at 20:48
3
I would recommend subprocess python module for running linux commands. In that, SIGINT signal (equivalent to Ctrl + C keyboard interrupt) can be sent programmatically to a command using Popen.send_signal(signal.SIGINT)
function. Popen.communicate()
function will give you output. For example
import subprocess
import signal
..
process = subprocess.Popen(..) # pass cmd and args to the function
..
process.send_signal(signal.SIGINT) # send Ctrl-C signal
..
stdout, stderr = process.communicate() # get command output and error
..

Neuron
- 5,141
- 5
- 38
- 59

Asif Hasnain
- 179
- 1
- 1
-
On ubuntu 14.04 x64, if I run python 2.7.6, I get an attribute error (popen object has no attribute send_signal). What's up with that? – Epu Sep 01 '15 at 18:39
-
1It should be `process.send_signal(signal.CTRL_C_EVENT)`, signal.SIGINT raise `ValueError: Unsupported signal: 2`. – Ronen Ness Jul 01 '18 at 11:47
-
1@RonenNess `CTRL_C_EVENT` is Windows, `SIGINT` is Linux. The question is tagged with Linux, so the answer is correct. – c z Aug 28 '19 at 09:55