Click here to Skip to main content
15,887,335 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to make a loop that user can stop and resume, but it looks like the loop waits for user input regardless of not typing anything.

What I have tried:

I tried doing it like this, but it doesn't seem to work correctly and breaks the loop completely:

Python
while True:
print(" ")
print("Info will now update every 30 seconds (if you want to stop this, type stop)")
if input() == "stop":
  print ("\nstoping...")
  time.sleep(2)
  print ("Stopped successfully, you can resume by typing resume")
  time.sleep(999999999999999999999999999999999999999999999999999999999999)
  if input() == "resume":
    print("\nResuming...")
    repeat2()
    time.sleep(2)
else:
  repeat2()
  time.sleep(30)
Posted
Updated 1-Oct-23 8:29am
v2

Look at your code:
Python
print ("Stopped successfully, you can resume by typing resume")
time.sleep(999999999999999999999999999999999999999999999999999999999999)
if input() == "resume":
The parameter to sleep is the number of seconds to wait before executing the next statement!
That code will wait for 3 * 1052 years before continuing ... in theory. In practice your computer will have died many, many megayears before that.

You would probably have to look at multithreading your app to do what you want: multithreading python - Google Search[^] you will find a lot of info there, but be aware that this is not a novice subject, and you have to think really carefully before converting to a multithreaded app.
 
Share this answer
 
Here is a quick and dirty solution that does not require the use of threads:
Python
while True:
    try:
        print("working")
        # do other work here
        time.sleep(3)

    except KeyboardInterrupt:
        print("interrupted")
        while True:
            if input("Resume?") == "y":
                break
            # also check if application should terminate
            time.sleep(2)

Pressing Ctrl-C whil the "working" message is displayed, raises the KeyboardInterrupt exception, which causes the second loop to be entered. Answering anything other than "y" to the "Resume?" message, pauses the work in the main loop.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900