Reputation: 3506
I have two functions, draw_ascii_spinner
and findCluster(companyid)
.
I would like to:
findCluster(companyid)
in the backround and while its processing.... draw_ascii_spinner
until findCluster(companyid)
finishesHow do I begin to try to solve for this (Python 2.7)?
Upvotes: 10
Views: 14445
Reputation: 1
It is possible to have a working example? I am new in Python. I have 6 tasks to run in one python program. These 6 tasks should work in coordinations, meaning that one should start when another finishes. I saw the answers , but I couldn't adopted the codes you shared to my program. I used "time.sleep" but I know that it is not good because I cannot know how much time it takes each time.
# Sending commands
for i in range(0,len(cmdList)): # port Sending commands
cmd = cmdList[i]
cmdFull = convert(cmd)
port.write(cmd.encode('ascii'))
# s = port.read(10)
print(cmd)
# Terminate the command + close serial port
port.write(cmdFull.encode('ascii'))
print('Termination')
port.close()
# time.sleep(1*60)
Upvotes: 0
Reputation: 602735
Use threads:
import threading, time
def wrapper(func, args, res):
res.append(func(*args))
res = []
t = threading.Thread(target=wrapper, args=(findcluster, (companyid,), res))
t.start()
while t.is_alive():
# print next iteration of ASCII spinner
t.join(0.2)
print res[0]
Upvotes: 14
Reputation: 188224
Generally, you will use Threads. Here is a simplistic approach which assumes, that there are only two threads: 1) the main thread executing a task
, 2) the spinner thread:
#!/usr/bin/env python
import time
import thread
def spinner():
while True:
print '.'
time.sleep(1)
def task():
time.sleep(5)
if __name__ == '__main__':
thread.start_new_thread(spinner, ())
# as soon as task finishes (and so the program)
# spinner will be gone as well
task()
Upvotes: 2
Reputation: 13289
You'll want to do some research on threading, the general form is going to be this
Here's a short tutorial in Python - http://linuxgazette.net/107/pai.html
Upvotes: 1
Reputation: 48706
This can be done with threads. FindCluster runs in a separate thread and when done, it can simply signal another thread that is polling for a reply.
Upvotes: 1
Reputation: 77119
Run findCluster()
in a thread (the Threading module makes this very easy), and then draw_ascii_spinner
until some condition is met.
Instead of using sleep()
to set the pace of the spinner, you can wait on the thread's wait()
with a timeout.
Upvotes: 0
Reputation: 51039
You can use multiprocessing. Or, if findCluster(companyid)
has sensible stopping points, you can turn it into a generator along with draw_ascii_spinner
, to do something like this:
for tick in findCluster(companyid):
ascii_spinner.next()
Upvotes: 7