0

I have 2 functions:

  1. get_list populates a list of site domains to excel sheet in column A
  2. get_traffic calls API for each site and populates that to column B next to the relevant site domain

Problem is that function 2 (get_traffic) doesn't wait for function 1 (get_list) to finish before starting, and therefore I'm not getting the data I need.

My question is: how can I make a function wait for another function to finish before running?

code:

get_list(wb)
get_traffic(wb)

Thank you!

James Monger
  • 10,181
  • 7
  • 62
  • 98
Ido Amit
  • 41
  • 1
  • 5
  • You should always post the code that's you've tried to solve your problem. Also, this sounds like a problem where you'll need to use threading. – reticentroot Apr 13 '15 at 23:16
  • 1
    What's wrong with the code you have? Won't that run the first function, then run the second? – KSFT Apr 13 '15 at 23:22
  • How is `get_list` implemented? Does it use `threading` or similar internally, or does it call out to some kind of asynchronous API? – Blckknght Apr 13 '15 at 23:43

1 Answers1

1

Use threading.

t = threading.Thread(target=get_list, args=wb)
t.start()

while t.isAlive():
    pass

t = threading.Thread(target=get_traffic, args=wb)
t.start()
Darth Vader
  • 383
  • 3
  • 12
  • Does the loop hog CPU? – TigerhawkT3 Apr 13 '15 at 23:15
  • @TigerhawkT3 No, not really, but if you're worried, you can just use `time.sleep(0.01)` inside the loop, which should actually increase performance marginally. – Darth Vader Apr 13 '15 at 23:18
  • Ew, of course [it will hog CPU](http://stackoverflow.com/a/529052/4403123). Using [`Event` objects](https://docs.python.org/2/library/threading.html#event-objects) would be better. Also, you forgot to start the threads. I don't get the point of using threads at all if you're running one function first, then the other. – KSFT Apr 13 '15 at 23:24
  • @KSFT Oops, you're right, I forgot to start them. This is just a quick-and-dirty solution. It won't win any awards, but it'll solve OP's problem. – Darth Vader Apr 13 '15 at 23:37