Search code examples
pythonpython-2.7timercountdowncountdowntimer

How to implement timer in Python


I wish to implement timer in python, but could not find any useful articles on that. My main aim is to implement the following logic:

`timer -> 60 seconds to zero
     #do stuff
     if the user selects to manually reset the timer -> start the time loop again
     if user exits -> exit the time loop
 reset the timer and again do above steps`

Am looking for articles / information of the syntax to implement the above logic.


Solution

  • Put it in your /usr/bin/stopwatch and give appropriate permission (chmod +x script)

    eg: sudo chmod +x /usr/bin/stopwatch
    

    Here is the code

    #!/usr/bin/python
    
    from __future__ import print_function
    
    import sys
    import time
    
    
    if len(sys.argv) != 2:
        print("Needs seconds as argument, Eg: stopwatch 10")
    else:
        seconds = sys.argv[1]
        for i in range(int(seconds), 0, -1):
            print(str(" "*50), end='\r')
            print(str(i), end='\r')
            sys.stdout.flush()
            time.sleep(1)
        print("Time over {}".format(seconds))
    

    Usage

    stopwatch 10