Send SIGINT in python to os.system

I am trying to run a Linux command strace -c ./client

in python with os.system()

. When I click ctrl+c

, I get some output in the terminal. I need to send a signal ctrl+c

programmatically after one minute and receive the terminal output that is generated after being clicked ctrl+c

in a file. The pseudo script will be really helpful. If I use subprocess.Popen

and then send a signal ctrl+c

from the keyboard, I got no output on the terminal, so you need to useos.system

+3


source to share


2 answers


In Python, you can send a signal programmatically Ctrl+C

using os.kill . The problem is that you need a pid

process that will receive the signal, and os.system

it says nothing about it. You must use subprocess

for this. I don't quite understand what you said about not getting output to the terminal.

Anyway, how could you do this:



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"

      

+2


source


I would recommend the subprocess python module for executing Linux commands. In this case, the SIGINT signal (equivalent to the keyboard interrupt Ctrl-C) can be programmatically transmitted to the command using the Popen.send_signal (signal.SIGINT) function. The Popen.communicate () function will give you the result. 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
..

      

0


source







All Articles