2019-07-12
I have some code and I would like some troubleshooting on it
stackoverflow
Question

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, "minutes")
        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.

Answer
1

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())
I have some code and I would like some troubleshooting on it
See more ...