gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:24:12 25 4
gpt4 key购买 nike

我制作了一个 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="")

最佳答案

这是一种可能的设计:

主线程:

  • 创建queue和线程
  • 启动进度线程
  • 等待用户输入
    • 输入时:
    • 从队列中弹出结果(可能是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()

关于Python 创建一个线程并在按下按键时启动它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33328279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com