【问题标题】:Is it possible to wait until a task in the windows taskmanager has stopped?是否可以等到 Windows 任务管理器中的任务停止?
【发布时间】:2019-06-02 11:55:24
【问题描述】:

所以基本上,我希望 python 运行另一个程序并等到该程序在任务管理器中不可见,然后继续执行脚本。 有什么想法吗?

【问题讨论】:

  • 我可能会跟踪进程的 pid 并查看它何时不再可用。 stackoverflow.com/questions/26688936/…
  • 你所说的“在任务管理器中不可见”的意思是进程死了,对吗?在这种情况下,任务管理器并不真正相关。相关的只是流程结束。

标签: python python-3.x windows taskmanager


【解决方案1】:

正如@eryksun 建议的那样,子进程模块也可以处理等待:

import subprocess
process = subprocess.Popen(["notepad.exe"], shell=False)
process.wait()
print ("notepad.exe closed")

你可以使用这样的东西,跟踪打开程序的进程ID:

import subprocess, win32com.client, time
wmi=win32com.client.GetObject('winmgmts:')
process = subprocess.Popen(["notepad.exe"], shell=False)
pid = process.pid
flag = True
while flag:
    flag = False
    for p in wmi.InstancesOf('win32_process'):
        if pid == int(p.Properties_('ProcessId')):
            flag = True
    time.sleep(.1)
print ("notepad.exe closed")

记事本关闭时的输出:

notepad.exe closed
>>> 

【讨论】:

  • Popen 实例有一个进程句柄,当进程终止时,它将为 WinAPI WaitForSingleObject 发出信号。那么为什么不使用process.wait()process.poll()
  • @eryksun 好点,我对 subprocess 模块不是很熟悉,实际上我是从 win32com 模块开始的,后来添加了 subprocess 模块来调用程序,我已经添加了你的很多以更简洁的方式获得答案以供将来参考。
【解决方案2】:

可以用pywinauto来完成:

from pywinauto import Application

app = Application().connect(process=pid) # or connect(title_re="") or other options
app.wait_for_process_exit(timeout=50, retry_interval=0.1)

【讨论】:

    【解决方案3】:

    这里有一个简单的方法示例,它使用内置的tasklist 命令来查看 Windows 上是否正在运行某些东西:

    import os
    import subprocess
    
    target = 'notepad.exe'
    results = subprocess.check_output(['tasklist'], universal_newlines=True)
    
    if any(line.startswith(target) for line in results.splitlines()):
        print(target, 'is running')
    else:
        print(target, 'is *not* running')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多