在 python 后每 n 秒自动点击 "enter"

Hit "enter" automatically every n seconds in python

我正在使用 python 脚本循环调用一个外部程序,一般情况下一切正常。但是,有时程序会在执行某个过程时卡住。如果我点击 'enter',那么程序会根据需要继续 运行。

是否可以 运行 后台进程每 n 秒回车一次(无论程序是否卡住)?这样,无论我是否在场指导,程序都会继续。这似乎违背了我对 python 工作原理的逻辑,但我认为也许有一些解决方法。

注意:我将在 bash (ubuntu 15.04)

中 运行 安装 python 脚本

Python 很难做到这一点,但是 AutoHotkey makes it very easy with Loop and WinWaitActive。以下脚本将启动一个循环,等待标题为 "Calculator" 的 window 变为活动状态,然后立即发送 Alt+F4 并返回到循环的开头,等待下一个计算器 window 出现。实际上,它会在您启动计算器后立即关闭它。

Loop {
    WinWaitActive, Calculator
    Send !{F4}
}

Calculator 替换为错误对话框的名称 window 的标题,并将 !{F4} 替换为 {Enter}:

Loop {
    WinWaitActive, Flagrant Error
    Send {Enter}
}

运行 外部进程就像你一直在做的那样,但保持一个管道打开它的标准输入并定期向它写入一个换行符。

from subprocess import Popen, PIPE
from time import sleep

n = 10 # seconds

p = Popen(["external_program", "arg1", "arg2"], stdin=PIPE)
while <condition>:
    sleep(n)
    p.stdin.write(b'\n')
    p.stdin.flush()