在使用控制台输入的True循环时停止

时间:2016-08-23 20:58:45

标签: python-2.7

我正在运行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()

1 个答案:

答案 0 :(得分: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