4

我已经浏览了很长时间来寻找这个问题的答案。

我在 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 进行测试,但由于它在每个周期都提示我,所以我不需要它。

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

Python中超时的键盘输入

几次,但似乎没有一个能如我所愿。

4

4 回答 4

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

显然,您需要将 pass 替换为您正在做的任何事情,然后进行打印。

于 2013-07-31T14:40:10.880 回答
2

以下是通过轮询标准输入的方法:

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。

于 2013-07-31T15:16:02.777 回答
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                     
于 2013-07-31T14:22:18.960 回答
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()
于 2013-07-31T14:48:48.230 回答