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

明らかに、パスを実行しているものに置き換え、余波で印刷する必要があります。

于 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 に答える