在Linux中工作时,在Python中模拟Ctrl-C键盘中断

Cor*_*ped 10 python linux kill

我正在处理一些脚本(在我工作的公司中),这些脚本被加载/卸载到虚拟机管理程序中,以便在事件发生时触发一段代码.实际卸载脚本的唯一方法是点击Ctrl- C.我正在用Python编写一个自动化过程的函数

一旦它看到"done"程序输出中的字符串,就应该杀掉它vprobe.我subprocess.Popen用来执行命令:

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)
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在buff以读/写模式打开文件描述符中的输出.我检查最后一行; 如果它有'done',我杀了它.不幸的是,CTRL_C_EVENT它仅适用于Windows.我能为Linux做些什么?

And*_*ter 10

我想你可以发送Linux等价物signal.SIGINT(中断信号).

(编辑:我曾经在这里有一些东西阻止使用这种策略来控制子过程,但是仔细阅读它听起来你已经决定在这种特殊情况下你需要控制-C ...所以,SIGINT应该这样做.)


glg*_*lgl 5

也许我误解了一些东西,但你这样做的方式很难得到想要的结果。

无论buff是什么,您首先查询它,然后在上下文中使用它Popen(),然后您希望 by macivlineList自行填充。

你可能想要的是类似的东西

logfile = open("mylogfile", "a")
p = subprocess.Popen(['vprobe', '/vprobe/myhello.emt'], stdout=subprocess.PIPE,  buff, universal_newlines=True, preexec_fn=os.setsid)
for line in p.stdout:
    logfile.write(line)
    if re.search("done", line):
        break
    print "waiting"
os.kill(p.pid, signal.CTRL_C_EVENT)
Run Code Online (Sandbox Code Playgroud)

这为您提供了一个由脚本提供的管道末端vprobe,您可以逐行读出该管道末端并根据找到的输出进行适当的操作。


小智 5

在Linux中,可以使用Popen.send_signal(signal.SIGINT)函数以编程方式将Ctrl-C键盘中断发送给进程。例如

import subprocess
import signal

..
process = subprocess.Popen(..)
..
process.send_signal(signal.SIGINT)
..
Run Code Online (Sandbox Code Playgroud)

不要使用Popen.communicate()阻止命令。