Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exit while loop with user prompt in python

Tags:

python

I've been browsing a long time searching an answer to this.

I'm using Python 2.7 in Unix.

I have a continuous while loop and I need an option where user could interrupt it, do something and after that the loop would continue.

Like:

while 2 > 1:
     for items in hello:
         if "world" in items:
             print "hello"
         else:
             print "world"

      time.sleep(5)
      here user could interrupt the loop with pressing "u" etc. and modify elements inside he loop. 

I started testing out with raw_input, but since it prompts me out every cycle, it's something that I don't need.

I tried methods mentioned here:

Keyboard input with timeout in Python

couple of times, but none of those seem to work how I wish.

like image 693
jester112358 Avatar asked Mar 22 '23 23:03

jester112358


1 Answers

>>> try:
...    print 'Ctrl-C to end'
...    while(True):
...       pass
... except KeyboardInterrupt, e:
...    print 'Stopped'
...    raise
...
Ctrl-C to end
Stopped
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>>

Obviously you need to replace pass with whatever you are doing and print with the aftermath.

like image 105
Steve Barnes Avatar answered Apr 10 '23 22:04

Steve Barnes