在Python中使用定时刷新检查打开的文件

2024-09-30 16:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何让一个函数每分钟刷新一次,并检查某个文件是否打开。我不知道该怎么做,但下面是我要找的一个例子:

def timedcheck():
   if thisgame.exe is open:
      print("The Program is Open!")
   else:
      print("The Program is closed!")
      *waits 1 minute*
      timedcheck()

我还希望脚本每分钟刷新一次函数“def timedcheck():”,这样它就可以一直检查thisgame.exe是开放的。在

我已经在网站上搜索过了,所有的建议都建议使用“importwin32ui”,当我这样做时,它会给我一个错误。在


Tags: 文件the函数ifisdefopenprogram
3条回答

您可以使用来自time module的sleep,输入为60,检查间隔为1分钟。如果不需要,可以临时打开文件并将其关闭。如果文件已打开,将发生IOError。捕获异常的错误,程序将等待一分钟,然后重试。在

import time
def timedcheck():
   try:
      f = open('thisgame.exe')
      f.close()
      print("The Program is Closed!")
   except IOError:
      print("The Program is Already Open!")
   time.sleep(60) #*program waits 1 minute*
   timedcheck()

要每分钟重复此检查:

def timedcheck():
   while True:
       if is_open("thisgame.exe"):
          print("The Program is Open!")
       else:
          print("The Program is closed!")
       sleep(60)

因为它是一个.exe文件,所以我假设“check if this file is open”是指“check if”thisgame.exe“正在运行。psutil应该会有帮助-我还没有测试下面的代码,所以它可能需要一些调整,但显示了一般原理。在

^{pr2}$

以下是@rkd91's answer的变体:

import time

thisgame_isrunning = make_is_running("thisgame.exe")

def check():
   if thisgame_isrunning():
      print("The Program is Open!")
   else:
      print("The Program is closed!")

while True:
    check() # ignore time it takes to run the check itself
    time.sleep(60) # may wake up sooner/later than in a minute

其中make_is_running()

^{pr2}$

要在WindowsforPython2.7上安装^{},可以运行^{}。在

相关问题 更多 >