gpt4 book ai didi

Python:如何让程序等到函数或方法完成

转载 作者:太空宇宙 更新时间:2023-11-03 15:14:33 25 4
gpt4 key购买 nike

程序经常需要等待一个函数完成它的工作。有时恰恰相反:主程序不需要等待。我举了一个简单的例子。有四个按钮。单击每个将调用相同的 calculate() 函数。唯一的区别是调用函数的方式。

  1. “直接调用” 按钮直接调用 calculate() 函数。由于打印出“函数结束”,因此很明显该程序正在等待计算函数完成其工作。
  2. “通过线程调用” 这次使用线程机制调用相同的函数。由于程序在按下按钮后立即打印出“: Function End”消息,因此我可以得出结论,程序不会等待 calculate() 函数完成。 如何覆盖这种行为?如何让程序等到 calculate() 函数完成?
  3. “通过多处理调用” 按钮利用多处理来调用 calculate() 函数。就像线程多处理一样,不等待函数完成。为了让它等待,我们必须写什么声明?

  4. “通过子进程调用” 按钮没有做任何事情,因为我没有找到 Hook 子进程以运行内部脚本函数或方法的方法.看看怎么做会很有趣......

示例:

from PyQt4 import QtCore, QtGui    
app = QtGui.QApplication(sys.argv)


def calculate(listArg=None):
print '\n\t Starting calculation...'
m=0
for i in range(50000000):
m+=i
print '\t ...calculation completed\n'


class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(Dialog_01, self).__init__()

myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()

directCall_button = QtGui.QPushButton("Call Directly")
directCall_button.clicked.connect(self.callDirectly)
myBoxLayout.addWidget(directCall_button)

Button_01 = QtGui.QPushButton("Call via Threading")
Button_01.clicked.connect(self.callUsingThreads)
myBoxLayout.addWidget(Button_01)

Button_02 = QtGui.QPushButton("Call via Multiprocessing")
Button_02.clicked.connect(self.callUsingMultiprocessing)
myBoxLayout.addWidget(Button_02)

Button_03 = QtGui.QPushButton("Call via Subprocess")
Button_03.clicked.connect(self.callUsingSubprocess)
myBoxLayout.addWidget(Button_03)


myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.setWindowTitle('Dialog 01')

def callUsingThreads(self):
print '------------------------------- callUsingThreads() ----------------------------------'
import threading
self.myEvent=threading.Event()
self.c_thread=threading.Thread(target=calculate)
self.c_thread.start()

print "\n\t\t : Function End"


def callUsingMultiprocessing(self):
print '------------------------------- callUsingMultiprocessing() ----------------------------------'
from multiprocessing import Pool

pool = Pool(processes=3)
try: pool.map_async( calculate, ['some'])
except Exception, e: print e

print "\n\t\t : Function End"


def callDirectly(self):
print '------------------------------- callDirectly() ----------------------------------'
calculate()
print "\n\t\t : Function End"


def callUsingSubprocess(self):
print '------------------------------- callUsingSubprocess() ----------------------------------'
import subprocess
print '-missing code solution'
print "\n\t\t : Function End"


if __name__ == '__main__':
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())

最佳答案

使用队列:每个线程完成后将结果放入队列,然后您只需要读取适当数量的结果并忽略其余部分:

#!python3.3
import queue # For Python 2.x use 'import Queue as queue'
import threading, time, random

def func(id, result_queue):
print("Thread", id)
time.sleep(random.random() * 5)
result_queue.put((id, 'done'))

def main():
q = queue.Queue()
threads = [ threading.Thread(target=func, args=(i, q)) for i in range(5) ]
for th in threads:
th.daemon = True
th.start()

result1 = q.get()
result2 = q.get()

print("Second result: {}".format(result2))

if __name__=='__main__':
main()

Queue.get() 的文档(没有参数,它等同于 Queue.get(True, None):

    Queue.get([block[, timeout]])

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

How to wait until only the first thread is finished in Python

您也可以使用 .join() 方法。 what is the use of join() in python threading

关于Python:如何让程序等到函数或方法完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22467338/

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