获取用户输入以停止while循环

时间:2020-08-14 07:20:43

标签: python python-3.x

我需要一种通过获取用户输入来停止循环的方式,而不会阻塞跨平台工作的循环本身。

我尝试过的事情:

  • 进程(关闭标准输入,所以我不能使用input()
  • 线程(如果while循环终止并且我不再需要input(),则无法杀死线程)
FLAG = False

def break_main_loop():  # how do I get this to execute?
  global FLAG
  user_in = input()
  if user_in == 'stop':
    FLAG = True
    return
  else:
    break_main_loop()


def stuff():
  pass


def main():
  # do stuff, e.g. getting other user input()
  while True:
    stuff()
    if FLAG:
      break

 return  # if I return here, I need to cancel break_main_loop's input()

main()

3 个答案:

答案 0 :(得分:5)

这将为您工作并且易于使用。以此替换主要功能

def main():
  # do stuff, e.g. getting other user input()
  try:
     while True:
        stuff()
  except KeyboardInterrupt:
     print("Press 1 to quit")
 return  # if I return here, I need to cancel break_main_loop's input()

main()

答案 1 :(得分:2)

尝试一下:

class run_game:
    
    start_game = True
    # end_game = False

    def break_main_loop(self):  # how do I get this to execute?
        print("game is ending!")
    

    def stuff(self):
        print("this is stuff happening....now...game is: ", self.start_game)
        
    def main(self):
        user_in = int(input("enter '2' to end game or '1' to keep playing:" ))
       
        if user_in == 1:
       
        
            self.stuff()
            self.main()
        else:
            return self.break_main_loop()
 
Test_game = run_game()

Test_game.main()

答案 2 :(得分:2)

我很想回答你的问题。您会看到,一旦进入主循环,就不必使用FLAG变量,而是建议这样做:

def break_main_loop():  # how do I get this to execute?
  user_in = input()
  if user_in == 'stop': 
    return True # Returning integer 1 also works just fine
  else:
    return False # Returning integer 0 also works just fine


def stuff():
  pass


def main():
  # do stuff, e.g. getting other user input()
  while True:
    stuff()
    if break_main_loop(): # If the user inputs stop, the loop stops via the return statement automatically
      return

main()

如果您希望退出循环而又不返回任何其他内容,并继续运行main()函数以完成工作:

def break_main_loop():  # how do I get this to execute?
  user_in = input()
  if user_in == 'stop': 
    return True # Returning integer 1 also works just fine
  else:
    return False # Returning integer 0 also works just fine


def stuff():
  pass


def main():
  # do stuff, e.g. getting other user input()
  while True:
    stuff()
    if break_main_loop(): 
      break
  #continue doing stuff

main()

现在,有一种更好的方法可以在不使用辅助函数break_main_loop()的情况下跳出循环,并且这样做就像这样:

def stuff():
  pass


def main():
  # do stuff, e.g. getting other user input()
  while True:
    stuff()
    if str(input("Do you wish to continue:[y/n]")) == 'n': 
      break
  #continue doing stuff

main()

这使您完全摆脱了辅助功能。

我希望这个答案会有所帮助。 :D