代码之家  ›  专栏  ›  技术社区  ›  Ethan Kinney

如何继续运行代码并仍然从用户那里获得输入?

  •  0
  • Ethan Kinney  · 技术社区  · 1 年前

    如何继续运行代码,并仍然从用户那里获得输入,以便您可以在运行代码时在终端中选择键入的项目。

    我尝试过这个代码:

    itemA = False
    itemB = False
    itemC = False
    
    while True:
        input = input("input example")
    
        if input == "a":
            # execute a's code
        # execute code
    

    这只会在input()运行后执行input(()下的代码,并再次请求输入。

    如何让它在输入下运行代码而不为每个输入()停止?

    1 回复  |  直到 1 年前
        1
  •  1
  •   Mippy    1 年前

    您可以使用 threading 包来完成此操作。这让你基本上有2个 while 循环同时运行。在您的情况下,一个用于输入,另一个用于其他代码。这里有一些代码可以做到这一点。

    itemA = False
    itemB = False
    itemC = False
    import threading
    
    def execute_code():
        while True:
            # execute code (not waiting for input)
            print("hi")
            continue
    threading.Thread(target=execute_code).start()
    
    while True:
        input("input example")
        # execute code (waiting for input)