Duhon
Duhon

Reputation: 23

I have some code and I would like some troubleshooting on it

My timer won't work properly, since it keeps printing forever, not what I want.

I've already tried re-organizing the script in many ways, but the result is always the same.

import time
CommandInput = input()
#execution [uptime]
def uptime(y):
    while 1 == 1:
        if (CommandInput == "uptime"):
            print(y, " seconds")
        y = y + 1
        time.sleep(1)


uptime(9)

I wanted to make some sort of "background timer" that kept running from when the script was executed up to when it was closed, and if I typed a certain line in the input it would show the current number it is in. The problem is that it keeps printing the timer forever, for every single number it counts. I wanted to do a one-time thing, where you could wait as much as you want and type the input, which would show the number the timer is in.

Upvotes: 1

Views: 66

Answers (2)

Jo Bay
Jo Bay

Reputation: 106

Your current program has to wait for input() to finish. The compiler does not move past the second line until the user hits enter. Thus the functions starts once the input is finished.

This timer could be done several way, such as threading or timers. There are some examples of that here and here. For threading, you need one process for user inputs and one for timers. But the better and easier way is to to use a timer and store the current time. I believe the following code is somewhat similar to what you want:

import time

start_time = time.time()

def get_time():
    current_time = time.time()
    total = current_time - start_time
    return total

while True:
    CommandInput = input()
    if CommandInput == "uptime":
        y = get_time()
        print(str(round(y)) + " seconds")

The variable start_time records the current time at the start. time.time() gets the current time in seconds on the computer. The get_time function is called after an input and sees how much time has pasted by subtracting the current time minus the start time. This way the you do not need multiple loops.

The while True loops just waits for the user input and then prints the time. This then repeats until the program is exited.

Upvotes: 1

JonPizza
JonPizza

Reputation: 129

To write a script like that you would need to look into a module called asyncio (https://docs.python.org/3/library/asyncio.html), which would allow you to run multiple things at the same time.

Here is a asyncio hello world:

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())

Upvotes: 0

Related Questions