挑战
我有一个使用两个线程编写的程序。一个线程更改文本的颜色和命令提示符的背景。另一个线程显示帮助菜单,或循环浏览1000个数字。问题是我希望程序返回提示并等待新的指令,而不是在色谱中循环。我想要的是该程序在色谱中循环显示,并且还等待最终用户在命令提示符下键入其他内容。这不可能吗?不幸的是,该程序只能在Windows操作系统(OS)上运行。
此外,如果愿意,我什至无法从程序中退出Control-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()