Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
击中;输入“;在python中每n秒自动执行一次_Python_Time - Fatal编程技术网

击中;输入“;在python中每n秒自动执行一次

击中;输入“;在python中每n秒自动执行一次,python,time,Python,Time,我使用python脚本将一个外部程序称为一个循环,一般来说一切都很好。然而,有时程序在执行某个特定的过程时会陷入困境。如果我点击“回车”,那么程序将继续按需要运行 是否有可能在后台运行每n秒按一次enter键的进程(无论程序是否被卡住)?这样,无论我是否在场指导,我都将继续该计划。这似乎违背了我关于python如何工作的逻辑,但我想也许有办法解决这个问题 注意:我将在bash(ubuntu15.04)中运行python脚本这对于python来说很困难,但是对于和来说非常容易。下面的脚本将启动一个

我使用python脚本将一个外部程序称为一个循环,一般来说一切都很好。然而,有时程序在执行某个特定的过程时会陷入困境。如果我点击“回车”,那么程序将继续按需要运行

是否有可能在后台运行每
n
秒按一次enter键的进程(无论程序是否被卡住)?这样,无论我是否在场指导,我都将继续该计划。这似乎违背了我关于python如何工作的逻辑,但我想也许有办法解决这个问题


注意:我将在bash(ubuntu15.04)中运行python脚本

这对于python来说很困难,但是对于和来说非常容易。下面的脚本将启动一个循环,等待标题为“Calculator”的窗口变为活动状态,然后立即发送Alt+F4并返回到循环的开头,等待下一个Calculator窗口出现。实际上,它会在您启动计算器时立即将其关闭

Loop {
    WinWaitActive, Calculator
    Send !{F4}
}
计算器
替换为错误对话框窗口标题的名称,然后
!{F4}
{Enter}

Loop {
    WinWaitActive, Flagrant Error
    Send {Enter}
}

像以前一样运行外部进程,但保持管道对其stdin开放,并定期向其写入换行符

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()
从子流程导入Popen,管道
从时间上导入睡眠
n=10秒
p=Popen([“外部_程序”、“arg1”、“arg2”],stdin=PIPE)
而:
睡眠(n)
p、 stdin.write(b'\n')
p、 stdin.flush()

感谢您的回复。我将在Linux中运行该脚本,因此我不确定autohotkey是否可以工作。感谢您的回复。你能详细说明一下这是怎么回事吗?while循环是否仅在外部程序完成后运行?否,外部程序在后台异步运行add
p.stdin.flush()
或显式设置
bufsize=0
。使用bytes literal与Python 3兼容:
b'\n'
或pass
universal\u newlines=True
来启用文本模式。@JeffDror,如果您使用
communicate()
wait()
或另一个阻塞调用(
check\u call()
等),则为True,但不仅仅是像这里那样创建
Popen
对象。