-1

So basically, i want python to run another programm and wait till that program is not visible in the taskmanger and then continue with the script. Any Ideas?

martineau
  • 119,623
  • 25
  • 170
  • 301
ETVator
  • 43
  • 2
  • 7
  • I'd probably track the pid of the process and see when it is no longer available. https://stackoverflow.com/questions/26688936/how-to-get-pid-by-process-name-in-python – tgikal Jan 07 '19 at 19:47
  • all you mean by "not visible in the taskmanager" is that the process dies, right? In which case the taskmanager isn't really relevant. All that's relevant is that the process finishes. – pushkin Jan 07 '19 at 20:18

3 Answers3

1

As @eryksun suggested, the subprocess module can handle the waiting as well:

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

You could use something like this, tracking the process id of the opened program:

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")

Output when notepad is closed:

notepad.exe closed
>>> 
tgikal
  • 1,667
  • 1
  • 13
  • 27
  • 1
    The `Popen` instance has a handle for the process, which becomes signaled for WinAPI `WaitForSingleObject` when the process terminates. So why not use `process.wait()` or `process.poll()`? – Eryk Sun Jan 08 '19 at 02:31
  • @eryksun great point, I'm not all that familiar with the subprocess module, and I actually started with the win32com module, adding the subprocess module later to call the program, I've added your much cleaner way to the answer for future reference. – tgikal Jan 08 '19 at 14:07
0

Here's an example of a simple way to see if something is running on Windows that uses its built-in tasklist command:

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')
martineau
  • 119,623
  • 25
  • 170
  • 301
0

It can be done with 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)
Vasily Ryabov
  • 9,386
  • 6
  • 25
  • 78