问题描述
我制作了一个python脚本,将数字分解为主要因子。 但是,当处理大量数字时,我可能希望对计算的进度有所了解。 (我简化了脚本)
import time, sys, threading
num = int(input("Input the number to factor: "))
factors = []
def check_progress():
but = input("Press p: ")
if but == "p":
tot = int(num**(1/2))
print("Step ", k, " of ", tot, " -- ", round(k*100/tot,5), "%", end="\r", sep="")
t = threading.Thread(target=check_progress) ?
t.daemon = True ?
t.start() ?
k = 1
while(k != int(num**(1/2))):
k = (k+1)
if num%k == 0:
factors.append(int(k))
num = num//k
k = 1
print(factors)
我想知道是否有一种方法可以显示按需显示的进度,例如,在循环过程中,我按一个键并显示进度?
如何在脚本中实现类似这样的线程?
谢谢,抱歉我的英语
编辑:
def check_progress():
while True:
but = input("## Press return to show progress ##")
tot = int(num**(1/2))
print("Step ", k, " of ", tot, " -- ", round(k*100/tot,5), "%", sep="")
1楼
这是一种可能的设计:
主线程:
- 创建和线程
- 启动进度线程
-
等待用户输入
- 输入时:
-
队列的弹出结果(可能为
None
) - 显示它
- 环
进度线程:
- 把工作放在队列中
我可以提供示例,但我觉得您愿意学习。 随时发表评论以寻求帮助。
编辑:带有队列的完整示例。
from time import sleep
from Queue import Queue
from threading import Thread
# Main thread:
def main():
# create queue and thread
queue = Queue()
thread = Thread(target=worker, args=(queue,))
# start the progress thread
thread.start()
# wait user input
while thread.isAlive():
raw_input('--- Press any key to show status ---')
# pop result from queue (may be None)
status = queue.get_nowait()
queue.task_done()
# display it
if status:
print 'Progress: %s%%' % status
else:
print 'No status available'
# Progress thread:
def worker(queue):
# do the work an put status in queue
# Simulate long work ...
for x in xrange(100):
# put status in queue
queue.put_nowait(x)
sleep(.5)
if __name__ == '__main__':
main()