views:

34

answers:

1

I would like to be able to save my session state within the PythonWin editor (e.g. these three files are opened and positioned in these particular locations within the PythonWin window). I can get handles to each of the child windows within PythonWin using win32gui, as well as the titles of each of the files and the positions/sizes of the windows. I'm unclear though in how to get the full path for the file listed as the child window name (i.e. if child window name is test.py and test.py lives at c:\python\test.py, I don't know how to get c:\python). I was thinking I would write out which files were opened plus their window positions to a small file that I would then call at PythonWin start time for loading.

Any ideas on how to get the full paths to the child window names?

Alternatively if someone already has a more elegant solution for saving session state in PythonWin please pass it along.

Below is the code I'm using right now (thanks to Michal Niklas for the starter code for using win32gui).


import win32gui
import re

MAIN_HWND = 0

def is_win_ok(hwnd, starttext):
    s = win32gui.GetWindowText(hwnd)
    if s.startswith(starttext):
        global MAIN_HWND
        MAIN_HWND = hwnd
        return None
    return 1


def find_main_window(starttxt):
    global MAIN_HWND
    win32gui.EnumChildWindows(0, is_win_ok, starttxt)
    return MAIN_HWND


def winPos(hwnd):
    if  type(hwnd) == type(1): ( left, top, right, bottom ) = win32gui.GetWindowRect(hwnd)
    return "%i, %i, %i, %i" % (left, right, top, bottom)


def winName(hwnd, children):
    s = win32gui.GetWindowText(hwnd)

    rePy = re.compile(r'[a-zA-Z1-9_ ]*.py')
    rePySearch = rePy.search(s)

    if rePySearch is not None:
        if rePySearch.group()[0:7] != "Running":
            s = s + ',' + winPos(hwnd) + '\n'
            children.append(s)
    return 1

def main():

    children = []
    main_app = 'PythonWin'
    hwnd = win32gui.FindWindow(None, main_app)

    if hwnd < 1:
        hwnd = find_main_window(main_app)

    if hwnd:
        win32gui.EnumChildWindows(hwnd, winName, children)

    filename = "sessionInfo.txt"
    sessionFile = os.path.join(sys.path[0],filename)

    fp=open(sessionFile, 'wb')
    for i in range(len(children)):
        fp.write(children[i])
    fp.close()

main()
A: 

I could be wrong, but isn't PythonWin written in Python?

Have you tried reading the source to the "Save" command to figure out where it stores its full paths?

(I'd take a look myself, but I haven't used Windows in half a decade)

ssokolow
I think it's written in c++, but regardless, good idea. I'm having a look now. Thanks for the tip.
Todd Hay
Once you're convinced you're not going to get any more answers, don't forget to mark my answer as "Best Answer". Otherwise, you'll start building an unfavorable "Accept Rate" rating and people won't bother to answer your questions.
ssokolow