简体   繁体   中英

How do I run two separate while loops in python?

Say I have a while loop that prints me the time every second

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 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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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