-6

I'm a total newbie and I have question about asking about input while the loop is working. Lets pretend that i have simple loop.

x = 1    
y = 1
while x == 1:
   y += 1
   print(y)

And now i want user input to stop this script but only if he types cancel and the loop is supposed to run while python is waiting for input.

martineau
  • 119,623
  • 25
  • 170
  • 301
Rav
  • 13
  • 1
  • 3
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Elis Byberi Nov 19 '17 at 14:53
  • You will probably have to check on the `threading` module but it may be a bit difficult if you aren't that confortable with python... – jadsq Nov 19 '17 at 14:56
  • @jadsq Maybe OP wants the loop to wait (run as he understands it) on user input. – Elis Byberi Nov 19 '17 at 14:58
  • I can't think of a way off the top of my head, but something else is that you should write `while True:` instead of `x = 1; while x == 1:` – paper man Nov 19 '17 at 15:00
  • @ElisByberi I think the question is pretty clear, the loop has to run while waiting for the input, the loop doesn't stop to wait for user input. – jadsq Nov 19 '17 at 15:03
  • @jadsq How will loop run (continue looping) while it is waiting for input? How will you use `threading` to do it? Do not reply in comments if you have an answer. – Elis Byberi Nov 19 '17 at 15:07
  • @ElisByberi That's called parallel programing, it's a fairly common thing in programming, it allows a program to execute two "sub-programs" (called threads) at the same time, this way you can have on thread that makes calculation and an other thread that waits for user input. In python you can do this with `threading` but it's not trivial and it involves knowing about how to make threads talk to each other but as I mentioned that will probably be a bit complex for someone that just began with Python. – jadsq Nov 19 '17 at 15:21

1 Answers1

0

As I mentioned in the comments you can achieve "running the loop while waiting for input" using threads from the threading module.

The idea is to have two threads that will run in parallel (ie at the same time) and each of them will do its own thing. The first one will do only one thing : wait for input. The second one will do the work that you would have put in the loop, and only check at the start of each loop if it should stop or not according to the information it gets from the first thread.

The following code illustrate this (note this requires python3):

from threading import Thread
import time


class Input_thread(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.keep_working = True

    def run(self):
        while True:
            a = input("Type *cancel* and press Enter at anytime to cancel \n")
            print("You typed "+a)
            if a == "cancel":
                self.keep_working = False
                return
            else:
                pass


class Work_thread(Thread):
    def __init__(self, other_thread):
        Thread.__init__(self)
        self.other_thread = other_thread

    def run(self):
        while True:
            if self.other_thread.keep_working is True:
                print("I'm working")
                time.sleep(2)
            else : 
                print("I'm done")
                return



# Creating threads
input_thread = Input_thread()
work_thread = Work_thread(input_thread)

# Lanching threads
input_thread.start()
work_thread.start()

# Waiting for threads to end
input_thread.join()
work_thread.join()

As you can see using threading isn't trivial and requires some knowledge about classes.

A way of achieving something similar in a slightly simpler way would be to use the python's exception called KeyboardInterrupt. If you are not familiar with exceptions : there are python's way of handling errors in your code, that means if at some point in your code Python finds a line it can't run, it will raise an exception, and if nothing was planned to deal with that error (aka if you don't catch the exception with the try/except syntax), python stops running and display that exception and the traceback in the terminal window.

Now the thing is when you press Ctrl-c (same as the copy shortcut) in the terminal window while your program runs, it will automaticaly raise an exception called KeyboardInterupt in your program, and you can catch it to use it as way to send cancel to your program. See that code for an example of how to do that :

import time 

y=1
try:
    while True:
        y+=1
        print(y)
        time.sleep(1)

except KeyboardInterrupt:
    print("User pressed Ctrl-c, I will now exit gracefully")

print("Done")
jadsq
  • 3,033
  • 3
  • 20
  • 32
  • You misunderstood OP statement: `the loop is supposed to run while python is waiting for input`. Even in your code, `while True: a = input()` will **wait** for user input, it is not running (looping). – Elis Byberi Nov 19 '17 at 20:41
  • @ElisByberi Try running my code, you don't seem to understand how threads work... – jadsq Nov 19 '17 at 20:48
  • @ElisByberi I'm serious, just try running the code, and type `cancel` at any time and see what happens. – jadsq Nov 19 '17 at 20:55
  • Have you pressed `enter` after typing cancel ? – jadsq Nov 19 '17 at 21:01