在Linux中工作时在Python中模拟Ctrl-C键盘中断 [英] Simulate Ctrl-C keyboard interrupt in Python while working in Linux
问题描述
我正在处理一些脚本(在我所在的公司中),这些脚本已加载/卸载到虚拟机管理程序中,以便在事件发生时触发一段代码.实际卸载脚本的唯一方法是按 Ctrl - C .我正在用Python编写一个使过程自动化的函数
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
只要在程序输出中看到字符串"done"
,它就应该杀死vprobe
.
我正在使用subprocess.Popen
执行命令:
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)
如您所见,我正在将输出写入以读写模式打开的buff
文件描述符中.我检查最后一行;如果它具有'done'
,我将其杀死.不幸的是,CTRL_C_EVENT
仅对Windows有效.
对于Linux我该怎么办?
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?
推荐答案
我认为您可以发送Linux等效文件signal.SIGINT
(中断信号).
I think you can just send the Linux equivalent, signal.SIGINT
(the interrupt signal).
(我以前在这里曾有一些事情阻止使用这种策略来控制子流程,但是仔细阅读后,听起来好像您已经决定需要在这种特定情况下使用control-C了...所以,SIGINT应该这样做.)
( 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.)
这篇关于在Linux中工作时在Python中模拟Ctrl-C键盘中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!