在python中使用用户提示符退出while循环

时间:2013-07-31 14:06:10

标签: python

我已经浏览了很长时间寻找答案。

我在Unix中使用Python 2.7。

我有一个连续的while循环,我需要一个选项,用户可以中断它,做一些事情,之后循环将继续。

像:

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. 

我开始使用raw_input测试,但由于它提示我每个周期,这是我不需要的东西。

我尝试了这里提到的方法:

Keyboard input with timeout in Python

几次,但这些似乎都不符合我的意愿。

4 个答案:

答案 0 :(得分:4)

>>> 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
>>>

显然,你需要用你正在做的任何东西取代传球,并用善后打印。

答案 1 :(得分:2)

以下是轮询stdin的方法:

import select, sys
p = select.poll()
p.register(sys.stdin, 1) #select the file descriptor, 
            #in this case stdin, which you want the 
            #poll object to pay attention to. The 1 is a bit-mask 
            #indicating that we only care about the POLLIN 
            #event, which indicates that input has occurred

while True:
     for items in hello:
         if "world" in items:
              print "hello"
         else:
              print "world"

     result = p.poll(5) #this handles the timeout too
     if len(result) > 0: #see if anything happened
         read_input = sys.stdin.read(1)
         while len(read_input) > 0:
              if read_input == "u":
                  #do stuff!
              read_input = sys.stdin.read(1) #keep going 
                            #until you've read all input

注意:这可能不适用于Windows。

答案 2 :(得分:1)

你可以做嵌套的while循环,结构如下:

while true:
    go = True
    while go:
     for items in hello:
         if "u" in items:
             go = False
         else if "world" in items:
             print "hello"
         else:
             print "world"
    #Here you parse input to modify things in the nested loop, include a condition to set       
    #go back to true to reenter the loop                     

答案 3 :(得分:0)

import sys
import os
import time

import termios
import tty
import fcntl
import errno

KEY = "u"

def read_characters(f):
    fd = f.fileno()

    # put descriptor in non-blocking mode
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)

    try:
        while 1:
            try:
                yield f.read(1)
            except IOError as e:
                if e.errno == errno.EAGAIN:
                    # no more characters to read
                    # right now
                    break
    finally:
        # restore blocking mode
        fcntl.fcntl(fd, fcntl.F_SETFL, flags)

def main():
    fd = sys.stdin.fileno()

    # save current termios settings
    old_settings = termios.tcgetattr(fd)

    # tty sets raw mode using termios module
    tty.setraw(fd)

    try:
        while True:
            time.sleep(1)

            for c in read_characters(sys.stdin):
                if c == KEY: break
            else:
                c = None

            if c == KEY: break

            sys.stdout.write("still going\r\n")

    finally:
        # restore terminal settings
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

if __name__ == "__main__":
    main()