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.

Was it helpful?

Solution

  1. Start a thread by giving it the function, don't call the function immediately :)

  2. The default output is buffered. Use sys.stderr, or the logging 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()
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top