By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,649 Members | 696 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,649 IT Pros & Developers. It's quick & easy.

running multiple functions

ryno du preez
P: 91
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.

Expand|Select|Wrap|Line Numbers
  1. !/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #Shell script version 2
  4. import os
  5. import shutil
  6. from Tkinter import *
  7. import tkMessageBox
  8. import tkSimpleDialog
  9. from threading import Thread
  10. import threading
  11. import time
  12. from multiprocessing import Process
  13. import sys
  14. from tkinter.ttk import *
  15. import multiprocessing
  16.  
  17.  
  18. Search = 'c:\\'
  19. search_folder = ''
  20.  
  21.  
  22. class popupWindow(object):
  23.     def __init__(self,parent):
  24.         top=self.top=Toplevel(parent)
  25.         self.l=Label(top,text="Patch is running")
  26.         self.l.pack()
  27.         self.b=Button(top,text='Ok',command=self.cleanup)
  28.         self.b.pack()
  29.     def cleanup(self):
  30.         #self.value=self.e.get()
  31.         self.top.destroy()
  32.  
  33. class Example(Frame):
  34.     def __init__(self, parent):
  35.         Frame.__init__(self, parent)   
  36.  
  37.         self.parent = parent
  38.  
  39.         self.initUI()
  40.  
  41.     def initUI(self):
  42.         photo = PhotoImage(file="C:\\IMAGE.gif") 
  43.         self.parent.title("Off Line Playe Patch")
  44.         self.style = Style()
  45.         self.style.theme_use("default")
  46.  
  47.         self.pack(fill=BOTH, expand=1)
  48.  
  49.         W = Label(self,image=photo)
  50.         W.photo = photo
  51.         W.pack()
  52.         #Button(tk,text='foo',command=bar).pack()
  53.         quitButton = Button(self, text="Apply Patch",command=self.StPatch)
  54.         quitButton.place(x=80, y=0)
  55.  
  56.  
  57.     def StPatch(self):
  58.         # Replaces shell.htm with correct file
  59.  
  60.         def FoundShell():
  61.  
  62.             for root, dirs, files in os.walk(search_folder):
  63.                 for file in files:
  64.                     print os.path.join(root,file)
  65.                     if file == 'shell.htm':
  66.                         print "found file"
  67.                         Shell = os.path.join(root,file)
  68.                         os.remove(Shell)
  69.                         shutil.copy2('./shell.htm',Shell)
  70.  
  71.  
  72.         def Hello():
  73.             self.w = popupWindow(self.parent)
  74.             self.parent.wait_window(self.w.top)
  75.             i = 0
  76.             while i < 100000:
  77.                 print('hello world')
  78.                 i=i+1
  79.  
  80.  
  81.         if os.path.exists('C:\Player - Office 2010'):
  82.             print 'Found Folder'
  83.             search_folder = 'C:\Player - Office 2010'
  84.             tkMessageBox.showinfo("Update Done", "Update has been applyed successfuly  ", command=FoundShell())
  85.         else:  # request user to enter path to Directory
  86.             print 'not found'
  87.             search_folder = tkSimpleDialog.askstring('Path', 'Please enter Path to Offline Player', )
  88.             print search_folder
  89.             tkMessageBox.showinfo("Update Done", "Update has been applyed successfuly  ", command=FoundShell())
  90.  
  91.         #t1 = threading.Thread(target=RunScript(self))
  92.         #t1.start()
  93.         #t1.join()
  94.         #Hello()
  95.  
  96.  
  97.  
  98.  
  99.     # the join means wait untill it finished
  100.  
  101. root = Tk()
  102. app = Example(root)
  103.  
  104. root.mainloop() 

Any Help will be greatly appreciated
Jun 2 '16 #1

✓ answered by dwblas

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.
Expand|Select|Wrap|Line Numbers
  1. try:
  2.     import Tkinter as tk     ## Python 2.x
  3. except ImportError:
  4.     import tkinter as tk     ## Python 3.x
  5.  
  6. class TestOfAfter():
  7.     def __init__(self, root):
  8.         self.root=root
  9.         self.this_file_num=0
  10.         self.total_num_files=20  ## assume 20 files to be processed
  11.  
  12.         self.create_widgets()
  13.  
  14.     def create_widgets(self):
  15.         self.progress_label=tk.Label(self.root, text="", bg="lightblue")
  16.         self.progress_label.grid(row=0, column=0, sticky="nsew")
  17.  
  18.         tk.Button(self.root, text="Exit Program", bg="orange",
  19.                  command=self.root.quit).grid(row=10, column=0,
  20.                  columnspan=2)
  21.  
  22.         self.start_progress_bar()
  23.         self.file_updates()  ## start the ball rolling
  24.  
  25.     def file_updates(self):
  26.         """ use a simple counter to simulate some work being done on
  27.             a sequence of files
  28.  
  29.             The "update_label would be called after every file
  30.             is processed, or every 10 files, etc.  And there would 
  31.             be no after() since the updates would be using a loop
  32.         """
  33.         self.this_file_num += 1
  34.         self.update_label()
  35.  
  36.         ## simulate the time it takes to process each file
  37.         self.root.after(500, self.file_updates)
  38.  
  39.     def start_progress_bar(self):
  40.         """ create a simple progress bar widget on a canvas
  41.  
  42.             You could also use the ttk.Progressbar, but I
  43.             already had this one lying around.
  44.         """
  45.         self.canvas = tk.Canvas(self.root, width=261, height=60,
  46.         background='lightgray')
  47.         self.canvas.grid(row=0, column=1)
  48.  
  49.         self.rc1 = self.canvas.create_rectangle(24, 20, 32, 50, outline='white', \
  50.                                       fill='blue')
  51.         self.start_x=20
  52.         self.end_x=235
  53.         self.this_x=self.start_x
  54.         self.one_25th = (self.end_x-self.start_x)/25.0
  55.         rc2 = self.canvas.create_rectangle(self.start_x, 20, self.end_x, 50,
  56.                                        outline='blue', fill='lightblue')
  57.         self.rc1 = self.canvas.create_rectangle(self.start_x, 20, self.start_x+7, 50,
  58.                                        outline='white', fill='blue')
  59.         self.update_scale()
  60.  
  61.     def update_label(self):
  62.         if self.this_file_num < self.total_num_files:
  63.             self.progress_label["text"]="%d of %d files processed" % (self.this_file_num,
  64.                                                            self.total_num_files)
  65.         else:
  66.             self.progress_label.destroy()     ## all files processed
  67.  
  68.     def update_scale(self):
  69.         self.canvas.move(self.rc1, self.one_25th, 0)
  70.         self.canvas.update()
  71.         self.this_x += self.one_25th
  72.         ## reverse direction at either end
  73.         if (self.this_x >= self.end_x-12) or self.this_x <= self.start_x+7:
  74.             self.one_25th *= -1
  75.  
  76.         ## only call after() while the countdown is running 
  77.         ## to avoid a dangling after() when the program terminates
  78.         if self.this_file_num < self.total_num_files:
  79.             self.canvas.after(150, self.update_scale)
  80.  
  81. root=tk.Tk()
  82. TA=TestOfAfter(root)
  83. root.mainloop() 

Share this Question
Share on Google+
4 Replies


Expert 100+
P: 619
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.
Expand|Select|Wrap|Line Numbers
  1. try:
  2.     import Tkinter as tk     ## Python 2.x
  3. except ImportError:
  4.     import tkinter as tk     ## Python 3.x
  5.  
  6. class TestOfAfter():
  7.     def __init__(self, root):
  8.         self.root=root
  9.         self.this_file_num=0
  10.         self.total_num_files=20  ## assume 20 files to be processed
  11.  
  12.         self.create_widgets()
  13.  
  14.     def create_widgets(self):
  15.         self.progress_label=tk.Label(self.root, text="", bg="lightblue")
  16.         self.progress_label.grid(row=0, column=0, sticky="nsew")
  17.  
  18.         tk.Button(self.root, text="Exit Program", bg="orange",
  19.                  command=self.root.quit).grid(row=10, column=0,
  20.                  columnspan=2)
  21.  
  22.         self.start_progress_bar()
  23.         self.file_updates()  ## start the ball rolling
  24.  
  25.     def file_updates(self):
  26.         """ use a simple counter to simulate some work being done on
  27.             a sequence of files
  28.  
  29.             The "update_label would be called after every file
  30.             is processed, or every 10 files, etc.  And there would 
  31.             be no after() since the updates would be using a loop
  32.         """
  33.         self.this_file_num += 1
  34.         self.update_label()
  35.  
  36.         ## simulate the time it takes to process each file
  37.         self.root.after(500, self.file_updates)
  38.  
  39.     def start_progress_bar(self):
  40.         """ create a simple progress bar widget on a canvas
  41.  
  42.             You could also use the ttk.Progressbar, but I
  43.             already had this one lying around.
  44.         """
  45.         self.canvas = tk.Canvas(self.root, width=261, height=60,
  46.         background='lightgray')
  47.         self.canvas.grid(row=0, column=1)
  48.  
  49.         self.rc1 = self.canvas.create_rectangle(24, 20, 32, 50, outline='white', \
  50.                                       fill='blue')
  51.         self.start_x=20
  52.         self.end_x=235
  53.         self.this_x=self.start_x
  54.         self.one_25th = (self.end_x-self.start_x)/25.0
  55.         rc2 = self.canvas.create_rectangle(self.start_x, 20, self.end_x, 50,
  56.                                        outline='blue', fill='lightblue')
  57.         self.rc1 = self.canvas.create_rectangle(self.start_x, 20, self.start_x+7, 50,
  58.                                        outline='white', fill='blue')
  59.         self.update_scale()
  60.  
  61.     def update_label(self):
  62.         if self.this_file_num < self.total_num_files:
  63.             self.progress_label["text"]="%d of %d files processed" % (self.this_file_num,
  64.                                                            self.total_num_files)
  65.         else:
  66.             self.progress_label.destroy()     ## all files processed
  67.  
  68.     def update_scale(self):
  69.         self.canvas.move(self.rc1, self.one_25th, 0)
  70.         self.canvas.update()
  71.         self.this_x += self.one_25th
  72.         ## reverse direction at either end
  73.         if (self.this_x >= self.end_x-12) or self.this_x <= self.start_x+7:
  74.             self.one_25th *= -1
  75.  
  76.         ## only call after() while the countdown is running 
  77.         ## to avoid a dangling after() when the program terminates
  78.         if self.this_file_num < self.total_num_files:
  79.             self.canvas.after(150, self.update_scale)
  80.  
  81. root=tk.Tk()
  82. TA=TestOfAfter(root)
  83. root.mainloop() 
Jun 2 '16 #2

ryno du preez
P: 91
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

Expand|Select|Wrap|Line Numbers
  1. for root, dirs, files in os.walk(search_folder):
  2.  
  3.             for file in files:
  4.                 print os.path.join(root, file)
  5.  
  6.                 if file == 'shell.htm':
  7.                     print "found file"
  8.                     Shell = os.path.join(root, file)
  9.                     os.remove(Shell)
  10.                     shutil.copy2('./shell.htm', Shell)
Jun 6 '16 #3

Expert 100+
P: 619
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.
Jun 6 '16 #4

ryno du preez
P: 91
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.
Jun 7 '16 #5

Post your reply

Sign in to post your reply or Sign up for a free account.