Python创建一个线程并在按下键时启动它

时间:2015-10-25 09:44:40

标签: python multithreading math

我制作了一个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 个答案:

答案 0 :(得分:2)

这是一种可能的设计:

主线程:

  • 创建queue和线程
  • 启动进度线程
  • 等待用户输入
    • 关于输入:
    • 从队列中弹出结果(可能是None
    • 显示

进度主题:

  • 在队列
  • 中执行put状态

我可以举例,但我觉得你愿意学习。随意发表评论以寻求帮助。

编辑:队列的完整示例。

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