0

I'm trying make python program which waits to process to open and then it does few things,
in my case those "few things" will be in function named action().
I'm a little complicated with this, here's what I did until now.
I've found that function which checks if process is running from the tasklist.exe

def isWindowsProcessRunning( exeName ) :            
    import subprocess    
    process = subprocess.Popen( 
        'tasklist.exe /FO CSV /FI "IMAGENAME eq %s"' % exeName,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        universal_newlines=True )
    out, err = process.communicate()    
    try : return out.split("\n")[1].startswith('"%s"' % exeName)
    except : return False

And I thought to use that in that way:

if( isWindowsPrecessRunning("chrome.exe") == False ):
    print "Waiting for chrome to open.."
    while( True ):
        if( isWindowsPrecessRunning("chrome.exe") == True ):
            action()
else:
    print "Chrome must be closed when the program starts, please close chrome, and re-open the program"

The problem is that the program was built with "tkinter" for windows,
and while I turn it on once, and chrome isn't running - the program gets into endless loop.
That endless loop, prevent the user of the program to do anything, because it opens a clear cmd, and closes it, opens it, closes it and so over- the user can't even close it.
Does anyone have an idea about how to do it?
Thanks in advance :)

guyshitz
  • 47
  • 6
  • Because of the statement `while( True ):` the program will indeed be in an endless loop. So you need to decide what should happen in the case where the exeName program isn't running. – ImportanceOfBeingErnest Nov 26 '16 at 10:50
  • Note that an `if` statement already evaluates the boolean value and parentheses are neither required nor desired for control statements. Also, unless you need to comply with a project or organization coding standard, it's recommended to follow PEP 8 style. So it's idiomatic in Python to write `if not is_windows_process_running("chrome.exe")` instead of `if( isWindowsProcessRunning("chrome.exe") == False )`. – Eryk Sun Nov 26 '16 at 11:00
  • For the problem, I recommend using the [wmi module](http://timgolden.me.uk/python/wmi/tutorial.html#monitoring) with the [`Win32_Process`](https://msdn.microsoft.com/en-us/library/aa394372) class. The tutorial shows an example that allows efficiently waiting for a process to start instead of polling. Creating a list of all "chrome.exe" processes is equally simple: `[p for p in c.Win32_Process() if p.Name == 'chrome.exe']`. If the list is empty, then wait for a chrome.exe process to start. – Eryk Sun Nov 26 '16 at 11:10
  • Regarding the running of background console processes (e.g. tasklist.exe) from a GUI program, use either `creationflags=DETACHED_PROCESS` or `creationflags=CREATE_NO_WINDOW`, as shown in [this answer](http://stackoverflow.com/a/7006424/205580). – Eryk Sun Nov 26 '16 at 11:14

0 Answers0