简体   繁体   English

如何在 python 中运行两个单独的 while 循环?

[英]How do I run two separate while loops in python?

Say I have a while loop that prints me the time every second假设我有一个 while 循环每秒打印我的时间

while True:
    print(strftime("%a, %d %b %Y %I:%M:%S %p %Z", gmtime())
    sleep(1)

and I have another while loop that lets me choose between menu options我还有另一个 while 循环让我在菜单选项之间进行选择

while not exit:
    choice = input("[1] " + "Menu1\n" +
                   "[2] " + "Menu2 \n" +
                   "[3] " + "Exit\n" + Fore.RESET)
    if choice == "1":
        menu_1(exit, args)
        return
    elif choice == "2":
        menu_2(exit, args)
        return
    elif choice == "3":
        print("Exiting...")
        exit = True
        return
    else:
        # invalid option

I want the desired result to have the time on top changing every second while allowing me to choose the menu options.我希望期望的结果每秒都在变化,同时允许我选择菜单选项。

ie IE

Tue, 12 Jul 2022 06:38:56 PM GMT

[1] Menu 1
[2] Menu 2
[3] Exit

You could use multiprocess.你可以使用多进程。 Then again I'm not sure this code will work but I know multiprocess could be the easiest solution.再说一次,我不确定这段代码是否有效,但我知道多进程可能是最简单的解决方案。 Refer to the Python documentation on multiprocessing for more information .有关更多信息,请参阅有关多处理的 Python 文档

from multiprocessing import Process

def a():
    while True:
    print(strftime("%a, %d %b %Y %I:%M:%S %p %Z", gmtime())

def b():
while not exit:
    choice = input("[1] " + "Menu1\n" +
               "[2] " + "Menu2 \n" +
               "[3] " + "Exit\n" + Fore.RESET)
    if choice == "1":
        menu_1(exit, args)
        return
    elif choice == "2":
        menu_2(exit, args)
        return
    elif choice == "3":
        print("Exiting...")
        exit = True
        return
    else:
        # invalid option

if __name__=='__main__':
    Process(target=a).start()
    Process(target=b).start()

Then again, I'm not sure if this will work or not as I have not tried it yet.再说一次,我不确定这是否可行,因为我还没有尝试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM