3

I am trying to find if Microsoft excel has an open window

import win32ui
import time

def WindowExists(windowname):
    try:
        win32ui.FindWindow(None, windowname)

    except win32ui.error:
        return False
    else:
        return True

if WindowExists("filename - Microsoft Excel"):
    print "Program is running"
    time.sleep(10)
else:
    print "Program is not running"
    time.sleep(10)

this works if i enter the correct filename, but the thing is i dont know the filename. so how can i get this work when only knowing part of the title?

or must i search on the classname instead? if so how do i know the classname :)?

extra note: i do know the filename but it has a unknow number attached to it, something like filename88, and differs every time i run the program.

77120
  • 865
  • 1
  • 14
  • 27
  • as a side-note, in Python methods shouldn't use CamelCase but underscore_separation, i.e. it might be a good idea to name your function `window_exists`. `win32ui` deviates from this because it exposes the Windows API, which unfortunately does use CamelCase... – Tobias Kienzler Mar 11 '15 at 10:29

1 Answers1

-2
def find_filename(substring):
    import os
    import re
    files = os.listdir(os.getcwd())
    for file in files:
        search = re.search(substring, file)
        if search:
            filename = file
            break
    return filename

file = find_filename('stringyouwant')
WindowExists(file)

This function will return the full filename that contains the shorter string that you require - however it will only work if the file you are searching for is the only file with that substring in that directory. If you want something more robust, you should modify the regular expression.

rabs
  • 333
  • 2
  • 6
  • 1
    Im new to python, but doesnt this search for files in a dir? i try to search for an openwindow or running program. correct me if im wrong :) – 77120 Jan 24 '14 at 15:06
  • Yes - it would have to be run from the same directory as the microsoft excel file you are trying to find, or you can use os.chdir(directory_required) to switch to that directory. You can then use your WindowExists(filename) to determine if it is open. – rabs Jan 24 '14 at 15:08
  • Editied to clarify where I think my code fits in. – rabs Jan 24 '14 at 15:13
  • oke that could work, just one more problem the excel files are generated and not saved in a directory, i will see if i can find it in a temp dir somewhere. thanks – 77120 Jan 24 '14 at 15:18