running multiple functions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ryno du preez
    New Member
    • Jul 2011
    • 91

    running multiple functions

    Hello all

    Im new to python, I'm trying to write a small Program that will update find files and update then in directory ( this is working ) the problem Im facing is that I can not get two functions to run at the same time. For example While the code searches for the file and replaces them, also display a small popup window showing an text message that the system is busy. and after the code has completed show a popup message Completed.

    Code:
    !/usr/bin/python
    # -*- coding: utf-8 -*-
    #Shell script version 2
    import os
    import shutil
    from Tkinter import *
    import tkMessageBox
    import tkSimpleDialog
    from threading import Thread
    import threading
    import time
    from multiprocessing import Process
    import sys
    from tkinter.ttk import *
    import multiprocessing
    
    
    Search = 'c:\\'
    search_folder = ''
    
    
    class popupWindow(object):
        def __init__(self,parent):
            top=self.top=Toplevel(parent)
            self.l=Label(top,text="Patch is running")
            self.l.pack()
            self.b=Button(top,text='Ok',command=self.cleanup)
            self.b.pack()
        def cleanup(self):
            #self.value=self.e.get()
            self.top.destroy()
    
    class Example(Frame):
        def __init__(self, parent):
            Frame.__init__(self, parent)   
             
            self.parent = parent
            
            self.initUI()
    
        def initUI(self):
            photo = PhotoImage(file="C:\\IMAGE.gif") 
            self.parent.title("Off Line Playe Patch")
            self.style = Style()
            self.style.theme_use("default")
    
            self.pack(fill=BOTH, expand=1)
    
            W = Label(self,image=photo)
            W.photo = photo
            W.pack()
            #Button(tk,text='foo',command=bar).pack()
            quitButton = Button(self, text="Apply Patch",command=self.StPatch)
            quitButton.place(x=80, y=0)
       
    
        def StPatch(self):
            # Replaces shell.htm with correct file
    
            def FoundShell():
                
                for root, dirs, files in os.walk(search_folder):
                    for file in files:
                        print os.path.join(root,file)
                        if file == 'shell.htm':
                            print "found file"
                            Shell = os.path.join(root,file)
                            os.remove(Shell)
                            shutil.copy2('./shell.htm',Shell)
    
    
            def Hello():
                self.w = popupWindow(self.parent)
                self.parent.wait_window(self.w.top)
                i = 0
                while i < 100000:
                    print('hello world')
                    i=i+1
    
    
            if os.path.exists('C:\Player - Office 2010'):
                print 'Found Folder'
                search_folder = 'C:\Player - Office 2010'
                tkMessageBox.showinfo("Update Done", "Update has been applyed successfuly  ", command=FoundShell())
            else:  # request user to enter path to Directory
                print 'not found'
                search_folder = tkSimpleDialog.askstring('Path', 'Please enter Path to Offline Player', )
                print search_folder
                tkMessageBox.showinfo("Update Done", "Update has been applyed successfuly  ", command=FoundShell())
    
            #t1 = threading.Thread(target=RunScript(self))
            #t1.start()
            #t1.join()
            #Hello()
    
    
    
    
        # the join means wait untill it finished
    
    root = Tk()
    app = Example(root)
    
    root.mainloop()

    Any Help will be greatly appreciated
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Multiprocessing or threading is not necessary You can use Tkinter's after() method to check/update periodically. This simple program uses a counter to simulate the file operations and a label that is updated periodically (you could also use a MessageBox of course). It also creates a simple "busy box" just to show again how after() works. If you want to use multiprocessing/threading then you have to have a way to communicate between threads. In multiprocessing this is done with a Manager object or a Queue.
    Code:
    try:
        import Tkinter as tk     ## Python 2.x
    except ImportError:
        import tkinter as tk     ## Python 3.x
    
    class TestOfAfter():
        def __init__(self, root):
            self.root=root
            self.this_file_num=0
            self.total_num_files=20  ## assume 20 files to be processed
    
            self.create_widgets()
    
        def create_widgets(self):
            self.progress_label=tk.Label(self.root, text="", bg="lightblue")
            self.progress_label.grid(row=0, column=0, sticky="nsew")
    
            tk.Button(self.root, text="Exit Program", bg="orange",
                     command=self.root.quit).grid(row=10, column=0,
                     columnspan=2)
    
            self.start_progress_bar()
            self.file_updates()  ## start the ball rolling
    
        def file_updates(self):
            """ use a simple counter to simulate some work being done on
                a sequence of files
    
                The "update_label would be called after every file
                is processed, or every 10 files, etc.  And there would 
                be no after() since the updates would be using a loop
            """
            self.this_file_num += 1
            self.update_label()
    
            ## simulate the time it takes to process each file
            self.root.after(500, self.file_updates)
    
        def start_progress_bar(self):
            """ create a simple progress bar widget on a canvas
    
                You could also use the ttk.Progressbar, but I
                already had this one lying around.
            """
            self.canvas = tk.Canvas(self.root, width=261, height=60,
            background='lightgray')
            self.canvas.grid(row=0, column=1)
    
            self.rc1 = self.canvas.create_rectangle(24, 20, 32, 50, outline='white', \
                                          fill='blue')
            self.start_x=20
            self.end_x=235
            self.this_x=self.start_x
            self.one_25th = (self.end_x-self.start_x)/25.0
            rc2 = self.canvas.create_rectangle(self.start_x, 20, self.end_x, 50,
                                           outline='blue', fill='lightblue')
            self.rc1 = self.canvas.create_rectangle(self.start_x, 20, self.start_x+7, 50,
                                           outline='white', fill='blue')
            self.update_scale()
    
        def update_label(self):
            if self.this_file_num < self.total_num_files:
                self.progress_label["text"]="%d of %d files processed" % (self.this_file_num,
                                                               self.total_num_files)
            else:
                self.progress_label.destroy()     ## all files processed
    
        def update_scale(self):
            self.canvas.move(self.rc1, self.one_25th, 0)
            self.canvas.update()
            self.this_x += self.one_25th
            ## reverse direction at either end
            if (self.this_x >= self.end_x-12) or self.this_x <= self.start_x+7:
                self.one_25th *= -1
    
            ## only call after() while the countdown is running 
            ## to avoid a dangling after() when the program terminates
            if self.this_file_num < self.total_num_files:
                self.canvas.after(150, self.update_scale)
    
    root=tk.Tk()
    TA=TestOfAfter(root)
    root.mainloop()

    Comment

    • ryno du preez
      New Member
      • Jul 2011
      • 91

      #3
      Thank you very mush for the sample code. I only have one problem I do not know how many files are going to get prossessed as this script is walking the directory And finding all the hits in that directory tree. Below is the core script

      Code:
      for root, dirs, files in os.walk(search_folder):
      
                  for file in files:
                      print os.path.join(root, file)
      
                      if file == 'shell.htm':
                          print "found file"
                          Shell = os.path.join(root, file)
                          os.remove(Shell)
                          shutil.copy2('./shell.htm', Shell)

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        You did not ask a question. len(files) should be the number of files in each dir that you want to check. Note also that there is likely only one "shell.htm" in the dir, and so you can use -->if shell.htm in files and proceed with the deleting, etc. if True.

        Comment

        • ryno du preez
          New Member
          • Jul 2011
          • 91

          #5
          Ok that makes sense Thank you I'll Play around with it and see what I get. This is all new to me.Like I said I'm very new to python and programing.

          Yes there is only one file in the directory list that needs to be changed. That is what the script is looking for.

          Comment

          Working...