多线程程序不立即返回主线程

2024-07-03 06:13:24 发布

您现在位置:Python中文网/ 问答频道 /正文

挑战

我有一个我写的程序,它使用两个线程。一个线程更改文本的颜色和命令提示符的背景。另一个线程显示一个帮助菜单或循环1000个数字的列表。问题是我希望程序返回到提示符并等待新的指令,而不是在光谱中循环。我想要的是让程序在颜色光谱中循环,同时等待最终用户在命令提示符下键入其他内容。这不可能吗?不幸的是,该程序只能在Windows操作系统(OS)上运行

此外,如果我想的话,我甚至不能将-C控制在程序之外,因为我创建的线程显然不会侦听输入。奇怪

代码

import os
import getopt
import time
import sys
import threading


def whiteRabbit():
    """Change the color of the command prompt while the program is executing."""

    for i in range(60):
        os.system('color %d' % i)
        time.sleep(1)

def goGoGo():
    for i in range(1000):
        print("Hey we have another number, %d " % i)

def howTo():
    print("Here are the options for this program")
    print ("%s -h (help menu. What you are reading now.)" % sys.argv[0])
    print("%s -g (goGoGo() mode. This prints a list of numbers to the console. Wow. :0" % sys.argv[0])
    print("%s --whiteRabbit (This changes the color of the console. Windows only. Sorry cool Unix people." % sys.argv[0])



if __name__ == "__main__":

    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], 'hg', ['whiteRabbit'])

        for opt, arg in opts:

            if opt in ('-h'):
                howTo()
            elif opt in ('-g'):
                goGoGo()
            elif opt in ('--whiteRabbit'):
                wr = threading.Thread(target=whiteRabbit)
                wr.start()

    except getopt.GetoptError as crap:
        howTo()

Tags: oftheinimport程序fordefsys