2016-08-23 50 views
0

我正在運行python 2.7.12停止,而真正的循環與控制檯輸入

現在,我可以告訴它開始,它會開始循環...沒有問題。但我無法阻止它。它會陷入循環中,所以我無法輸入命令使其停止。

怎樣才能擺脫循環,所以我可以給命令?

def dothis(): 
    while True 
     # Loop this infinitely until I tell it stop 


while True: 
    command = raw_input("Enter command:") 

    if command = "start": 
     dothis() 
    if command = "stop": 
     #Stop looping dothis() 
+0

你不知道。它永遠不會讀到你的下一個命令的程序部分。你可以用'CTRL-C'打破無限循環,你可以捕獲它(它被稱爲'KeyboardInterrupt')。 –

回答

1

使用線程這樣的:

import threading 
import time 

class DoThis(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 

     self.stop = False 

    # run is where the dothis code will be 
    def run(self): 
     while not self.stop: 
      # Loop this infinitely until I tell it stop 
      print('working...') 
      time.sleep(1) 

a = None 
while True: 
    command = raw_input("Enter command:") 

    if command == "start": 
     a = DoThis() 
     a.start() 

    if command == "stop": 
     a.stop = True 
     a.join() 
     a = None 
+0

是的!這正是我所追求的。 這就是所謂的多線程,對吧? –

+0

是的,它是多線程的。請注意,對於任何程序來說,更復雜一些,您都需要查看python線程安全隊列和鎖。 –