【问题标题】:Checking for an open file with a timed refresh in Python在 Python 中使用定时刷新检查打开的文件
【发布时间】:2013-01-18 02:26:21
【问题描述】:

我想知道如何让一个函数每分钟刷新一次,并检查它是否打开了某个文件。我不完全知道该怎么做,但这是我正在寻找的一个例子:

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 是否打开。

我已经搜索了该网站,所有建议都建议使用“import win32ui”,但我这样做时会出错。

【问题讨论】:

  • 什么操作系统?必须是跨平台解决方案吗?
  • 只是 Windows 32 和 64 位

标签: python file-io time


【解决方案1】:

您可以使用来自time module 的睡眠,输入为 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()

【讨论】:

  • 这包括如何让程序等待,谢谢。但是我如何让脚本检查某个程序是否打开。
  • 一个很好的补充是使用 winsound 模块通过扬声器发出警报。有兴趣的有stack overflow here
【解决方案2】:

每分钟重复一次检查:

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

由于它是一个 .exe 文件,我假设“检查此文件是否打开”是指“检查 thisgame.exe 是否正在运行”。 psutil 应该会有所帮助 - 我还没有测试过下面的代码,所以它可能需要一些调整,但显示了一般原则。

def is_open(proc_name):
    import psutil
    for process in psutil.process_iter():
        if proc_name in process.name:
            return True
    return False

【讨论】:

  • ImportError: No module named psutil... 我真的厌倦了这些不断的导入错误,运行 Python27 btw。
  • 他链接了 psutil 页面。您必须自己下载并添加为 Python 模块;它不是默认模块。
  • 没有name.contains() 方法。 psutil.get_process_list() 已弃用。你可以use process_iter() instead
  • 谢谢 - 想不出我在想什么语言 contains()
  • 你可以使用any(): is_open = lambda name: any(name in p.name for p in psutil.process_iter())
【解决方案3】:

这是@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():

import psutil # 3rd party module that needs to be installed

def make_is_running(program):
    p = [None] # cache running process
    def is_running():
        if p[0] is None or not p[0].is_running():
            # find program in the process list
            p[0] = next((p for p in psutil.process_iter()
                         if p.name == program), None)
        return p[0] is not None
    return is_running

要在 Windows 上为 Python 2.7 安装 psutil,您可以运行 psutil-0.6.1.win32-py2.7.exe

【讨论】:

    猜你喜欢
    • 2013-12-05
    • 1970-01-01
    • 2011-10-13
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2017-03-31
    相关资源
    最近更新 更多