Skip to content Skip to sidebar Skip to footer

Python Program Terminating Unexpectedly

I have a program that scrapes a website and downloads files when it finds it. Often it runs just fine but at other times it flat out terminates the operation of the program before

Solution 1:

I think the problem is caused by tkinter not given the chance to start it's main event loop which is done when you call root.mainloop(), I'd recommend making the code you currently have in a while loop instead to be a function that is periodically called with the root.after() method. I have included a potential change to test if this would fix the issue.

Note that the lines:

                    Fileupdate = Fileupdate + 1
                    root.update_idletasks()
                    continue

in some except branches are redundant since that would happen if the code kept going anyway, so part of modifying the code to work in a function was to simply get rid of those parts. Here is the code I'd like you to try running starting from the original while statement:

#-while Fileupdate <= Filecount:
def UPDATE_SOCKET():
    global Fileupdate #allow the global variable to be changed
    if Fileupdate <= Filecount:
#/+
        try:
                root.title(Fileupdate)
                url = 'http://www.webpage.com/photos/'+str(Fileupdate)+'.jpg'
                a = urllib.request.urlopen(url)
                urllib.request.urlretrieve(url, str(Fileupdate)+'.jpg')
        except urllib.error.HTTPError as err:
                #<large redundant section removed>
                print("error code",err.code)
        except socket.error as v:
                print("socket error",Fileupdate, v[0])
#-                continue
                root.after(500, UPDATE_SOCKET)
                return
#/+


        Fileupdate = Fileupdate+1
#-        root.update_idletasks()
        root.after(100, UPDATE_SOCKET) #after 100 milliseconds call the function again
        #change 100 to a smaller time to call this more frequently.


root.after(0,UPDATE_SOCKET) #when it has a chance, call the update for first time

root.mainloop() #enter main event loop
#/+

I indicate changed lines with a #- followed by the chunk that replaces it ending with a #/+


Post a Comment for "Python Program Terminating Unexpectedly"