将python中的SIGINT发送到os.system [英] Send SIGINT in python to os.system

查看:160
本文介绍了将python中的SIGINT发送到os.system的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用os.system()在python中运行Linux命令strace -c ./client.当我按下ctrl+c时,我会在终端上获得一些输出.我必须在一分钟后以编程方式发送ctrl+c信号,并希望在按下文件中的ctrl+c之后产生终端输出. 伪脚本将非常有用.如果我使用subprocess.Popen然后从键盘发送ctrl+c信号,但终端上没有输出,则必须使用os.system

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

推荐答案

在Python中,您可以使用

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"

这篇关于将python中的SIGINT发送到os.system的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆