473,378 Members | 1,438 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

running multiple functions

ryno du preez
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() 

4 1668
dwblas
626 Expert 512MB
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
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
dwblas
626 Expert 512MB
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
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

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

Similar topics

5
by: Mike | last post by:
I have some code I am working on. One function reads a file using fso, then I have multiple functions using the string read from the file. Each function splits the lines up and will return one...
4
by: PalB | last post by:
How to stop running multiple instances of my App in C#? Thanx
11
by: Clark Stevens | last post by:
I just finished a WinForms app in VB.NET. I want to allow the user to be able to run multiple instances of the program like you can with Notepad and Wordpad. The way it is now, once I run the...
2
by: Wei Wang | last post by:
Hi, Can I call multiple functions in one trigger? Something like this: CREATE TRIGGER match_cond_name_generate BEFORE INSERT OR UPDATE ON public.predicate_index FOR EACH ROW EXECUTE...
5
by: vj | last post by:
Hi all, I am using C++Builder-5. I want to run multiple cpp files at the same time. If I use the C++Builder for running a cpp file (i.e., I just double click the cpp file, it then opens in the...
13
LacrosseB0ss
by: LacrosseB0ss | last post by:
I was wondering, can an OnClick event of a button call multiple functions? The reason for this is I have a page that when "ok" is clicked, goes to a preview page before submitting data to the...
7
by: pronerd | last post by:
Does any one know how to add a function to an event handler with out losing the current event handler? For example you can add multiple functions to a single event handler with something like : ...
14
by: Supermansteel | last post by:
My team at work uses Cognos to run multiple queries to pull in data. Then they take that data and import into Access and then usually run an Append Query to run a RND function to pull out a few...
3
by: Harshpandya | last post by:
<form action="?= $postUri ?>" method="post" onSubmit="return verifyInput();" onReset="setTimeout('toggleDHCP()',100) setFormDisabled(true);"> In this code - i want to pass multiple functions...
1
by: su817200 | last post by:
Dear Friend, I would like to run multiple functions on Button Click eg... <input type="button" value="Update" name="B1" onclick="ReadFileToString() timedRefresh(1500)"></p> It is giving...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.