【发布时间】:2016-09-12 22:36:20
【问题描述】:
我想完成一个具有以下功能的python脚本(func):
1.有两个线程,一个线程打印一个更新行,显示输入到终端之前的剩余时间
2.另一个线程等待我对终端的输入(sys.stdin)
3.我的问题是,当我使用我的功能时:
print '''input your file path,the default value will be "/root/targets.txt":>'''
get_input_intime([''],'/root/targets.txt',20)
但是我不能输入一个长文件abs路径,因为第一个线程总是打印剩下的时间,我想实现:
a)终端有两行
b)第一行作为第一个线程的打印字符串的位置
c)第二行将接受我的输入,因此我可以输入我需要的文件路径,并且不会被第一个线程刷新,如下所示:
在终端:
第一行:sys.stdout.write("还剩%s秒...请输入您的选择:>\r" % timeout)
第二行:(等待我的输入)
4.我的代码是:
1) 几秒钟后得到选择,如果没有输入,返回默认选择
2)第一个参数是一个包含非默认选择的列表。
eg.有四个选择1,2,3,4,如果我想将默认选择设为2,那么undefault_chioce_list是['1','3','4'],每个列表是str类型。
3)第二个参数是默认的选择值
4)第三个参数是输入前的时间(选择)
5)返回值是来自raw_input()的选择
class MyThread(threading.Thread):
def __init__(self,func,args,name=''):
threading.Thread.__init__(self)
self.name=name
self.func=func
self.args=args
def run(self):
self.result=apply(self.func,self.args)
def get_result():
return self.result
def get_input_intime(undefault_chioce_list,default_choose,timeout=5):
default_choose=[default_choose]
timeout=[timeout]
choosed=[0]
chioce=['']
def print_time_func():
while (choosed[0]==0 and timeout[0]>0):
sys.stdout.write("%s seconds left...please input your chioce:>\r" % timeout)
sys.stdout.flush()
time.sleep(1)
timeout[0]-=1
if choosed[0]==0:
chioce[0]=default_choose[0]
def input_func():
rlist, _, _ = select([sys.stdin], [], [], timeout[0])
if rlist:
chioce_and_enter = sys.stdin.readline()
choosed[0]=1
if chioce_and_enter[0] not in undefault_chioce_list:
chioce[0]=default_choose[0]
else:
chioce[0]=chioce_and_enter[0]
print "you choosed %s" % chioce[0]
else:
print "\nyou didn't input..."
print "I will choose the default chioce for you:%s" % default_choose[0]
time_left_thread=MyThread(print_time_func,())
input_thread=MyThread(input_func,())
time_left_thread.start()
input_thread.start()
time_left_thread.join()
input_thread.join()
return chioce[0]
【问题讨论】: