Send SIGINT in python to os.system

情到浓时终转凉″ 提交于 2019-11-30 05:39:52

问题


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 ctrl+c 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


回答1:


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"



回答2:


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
..


来源:https://stackoverflow.com/questions/27356837/send-sigint-in-python-to-os-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!