5

I have a python script that calls another python script. Inside the other python script it spawns some threads.How do I make the calling script wait until the called script is completely done running?

This is my code :

while(len(mProfiles) < num):
        print distro + " " + str(len(mProfiles))
        mod_scanProfiles.main(distro)
        time.sleep(180)
        mProfiles = readProfiles(mFile,num,distro)
        print "yoyo"

How do I wait until mod_scanProfiles.main() and all threads are completely finished? ( I used time.sleep(180) for now but its not good programming habit)

5
  • It doesn't look like you're using the subprocess module. Can you show the code of mod_scanProfiles.main(distro)? Commented Aug 9, 2012 at 13:00
  • I am not using the subprocess module indeed... I was guessing I might need to use it to use it so i also tagged it Commented Aug 9, 2012 at 13:02
  • 2
    Two approaches: 1) use subprocess instead; 2) change mod_scanProfiles.main() to wait for all threads to finish before returning. Either way shouldn't be too hard. Commented Aug 9, 2012 at 13:10
  • Yeah, since you're not using subprocess you probably just need to do Thread.join to wait. Commented Aug 9, 2012 at 13:10
  • 2
    To wait for a thread to finish running, use the .join() method. Commented Aug 9, 2012 at 13:12

1 Answer 1

7

You want to modify the code in mod_scanProfiles.main to block until all it's threads are finished.

Assuming you make a call to subprocess.Popen in that function just do:

# in mod_scanPfiles.main:
p = subprocess.Popen(...)
p.wait() # wait until the process completes.

If you're not currently waiting for your threads to end you'll also want to call Thread.join (docs) to wait for them to complete. For example:

# assuming you have a list of thread objects somewhere
threads = [MyThread(), ...]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the example code. I used the join function on my thread list and it waits without using the subprocess now :) thnx... didnt know it would be that simple...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.