Reputation: 4192
I have a python system call that takes a while to finish.
os.system("call_that_takes_quite_some_time")
In the meanwhile I want to keep throwing a message that says "waiting..." every now and then till the os.system returns 0 or an error. / How do I do this? Is there something in python that I can "listen" to in a while loop?
Upvotes: 3
Views: 9287
Reputation: 9117
You can use threading
import os
import time
import threading
def waiter():
waiter.finished = False
while not waiter.finished:
print 'Waiting...'
time.sleep(1)
os_thread = threading.Thread(target=waiter)
os_thread.daemon = True
os_thread.start()
return_value = os.system('sleep 4.9')
return_value >>= 8 # The return code is specified in the second byte
waiter.finished = True
time.sleep(3)
print 'The return value is', return_value
This will print "Waiting..." message every 1 second, and it stops after waiter.finished
is set to True
(in this case there will be 5 "Waiting..." messages)
But os.system
is not recommended. The documentation recommends using subprocess
module.
Upvotes: 1
Reputation: 4318
os.system
waits till your command execution is complete.
use subprocess.Popen
you can check output or error. Popen gives handle and you can check return code using wait to find out command is successful/failure. For ex:
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while proc.poll() is None:
print proc.stdout.readline() #give output from your execution/your own message
self.commandResult = proc.wait() #catch return code
Upvotes: 8