Simulate Ctrl-C keyboard interrupt in Python while working in Linux

懵懂的女人 提交于 2019-12-05 01:42:56

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

In Linux, Ctrl-C keyboard interrupt can be sent programmatically to a process using Popen.send_signal(signal.SIGINT) function. For example

import subprocess
import signal

..
process = subprocess.Popen(..)
..
process.send_signal(signal.SIGINT)
..

Don't use Popen.communicate() for blocking commands..

Maybe I misunderstand something, but the way you do it it is difficult to get the desired result.

Whatever buff is, you query it first, then use it in the context of Popen() and then you hope that by maciv lineList fills itself up.

What you probably want is something like

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)

This gives you a pipe end fed by your vprobe script which you can read out linewise and act appropriately upon the found output.

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