是否可以等到windows taskmanager中的任务停止?

2024-09-29 06:36:00 发布

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

因此,基本上,我希望python运行另一个程序,等待该程序在taskmanger中不可见,然后继续执行脚本。 有什么想法吗?你知道吗


Tags: 程序脚本继续执行taskmanger
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')

可以使用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)

正如@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
>>> 

相关问题 更多 >