python监听键盘ctrl c,在Linux中工作时在Python中模拟Ctrl-C键盘中断

博主正在编写一个Python函数,该函数用于自动化监控hypervisor中加载/卸载的脚本。当检测到输出中有'done'字符串时,函数会发送一个信号来终止进程。目前,博主使用的是Windows下的CTRL_C_EVENT信号,但寻求适用于Linux的解决方案。建议在Linux中使用SIGINT信号作为中断进程的手段。
摘要由CSDN通过智能技术生成

I am working on some scripts (in the company I work in) that are loaded/unloaded into hypervisors to fire a piece of code when an event occurs. The only way to actually unload a script is to hit Ctrl-C. I am writing a function in Python that automates the process

As soon as it sees the string "done" in the output of the program, it should kill the vprobe.

I am using subprocess.Popen to execute the command:

lineList = buff.readlines()

cmd = "vprobe /vprobe/myhello.emt"

p = subprocess.Popen(args = cmd, shell=True,stdout = buff, universal_newlines = True,preexec_fn=os.setsid)

while not re.search("done",lineList[-1]):

print "waiting"

os.kill(p.pid,signal.CTRL_C_EVENT)

As you can see, I am writing the output in buff file descriptor opened in read+write mode. I check the last line; if it has 'done', I kill it. Unfortunately, the CTRL_C_EVENT is only valid for Windows.

What can I do for Linux?

解决方案

I think you can just send the Linux equivalent, signal.SIGINT (the interrupt signal).

(Edit: I used to have something here discouraging the use of this strategy for controlling subprocesses, but on more careful reading it sounds like you've already decided you need control-C in this specific case... So, SIGINT should do it.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值