how can i show two output in a same time in terminal with python?
-
21-12-2019 - |
Question
I need this output in my program:
from __future__ import print_function
import time
import threading
def timer():
for h in range(0, 24):
for m in range(0, 60):
for s in range(0, 60):
time.sleep(1)
print ("Elapsed time : %s:%s:%s" % (h, m, s), end="\r")
def insert_record():
#do insert record operation below code is sample
count = 0
for i in range(1, 100):
count += 1
time.sleep(1)
print ("Inserted records in mysql database : %s " % count, end="\r")
if __name__ == "__main__":
threading.Thread(target=insert_record()).start()
threading.Thread(target=timer()).start()
until insert_record function() is working, timer() function show elapsed time in next line. but didn't show elapsed time in terminal :-( just showed insert_record() output in terminal.
i want this output :
Inserted records in mysql database : 5456672
Elapsed time : 20:15:30
please help me ,sorry about bad english dictate.
Solution
Start a thread by giving it the function, don't call the function immediately :)
The default output is buffered. Use
sys.stderr
, or thelogging
module.from future import print_function import sys, time import threading
def timer(): for h in range(0, 24): for m in range(0, 60): for s in range(0, 60): time.sleep(1) sys.stderr.write( "Elapsed time : %s:%s:%s\n" % (h, m, s) )
def insert_record(): #do insert record operation below code is sample
count = 0 for i in range(1, 100): count += 1 time.sleep(1) sys.stderr.write( "Inserted records in mysql database : %s\n" % count )if name == "main": print('start') threading.Thread(target=insert_record).start() threading.Thread(target=timer).start()
print('join') for t in threading.enumerate(): if t != threading.current_thread(): t.join()