C:\> Rostislav Persion's Projects

.:: Search-n-run Python ::.
Finds new image in folder and loads it




This program monitors a directory for a new image file. When the file is located it is executed. I previously wrote the same program in C#. The C# code was 3 pages long. The Python code is half a page. The Python version is also more elegant and robust.

 1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334353637383940414243444546474849
import os, sysimport timeimport datetime#from PIL import Image#FILE EXTENSIONS TO LAUNCHexts = ["jpg","jpeg","png","gif","tiff","bmp"]#START MESSAGEprint("##### ROSTISLAV PERSION - IMAGE WATCH/LOADER 1.00 #####")print("MONITORING LOCAL FOLDER...")#INITIALIZE FILE LISTmyfiles_new = os.listdir()#MAIN LOOPwhile True:    #PAUSE FOR A FEW SECONDS    time.sleep(5)    #SAVE OLD FILE LIST, LOAD NEW FILE LIST    myfiles_old = myfiles_new.copy()    myfiles_new = os.listdir()    #FIND DIFFERENCE BETWEEN NEW FILE LIST AND OLD FILE LIST    myfiles_dif = list(set(myfiles_new) - set(myfiles_old))    #TRAVERSE NEW FILES    for myfiles_dir in myfiles_dif:        #FIND FILE EXTANSION FOR FILE        myfile_ext = myfiles_dir.split(".")[-1]                #CHECK IF FILE EXTANSION EXISTS IN FILE EXTENSION LIST        if myfile_ext.lower() in exts:                        #SHOW IMAGE FILE            os.system(myfiles_dir)            #img = Image.open(myfiles_dir)            #img.show()                        #GENERATE TIMESTAMP            now1 = datetime.datetime.now()            now2 = now1.strftime("%d/%m/%Y %H:%M:%S")                        #OUTPUT NEW FILE FOUND            print(now2 + " - NEW FILE FOUND: " + myfiles_dir)