多处理问题[pyqt,py2exe]

2024-05-29 03:08:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用PyQt4编写一个GUI程序。 我的主窗口有个按钮 然后点击这个按钮。 我希望启动一个后台进程 它是派生类的实例 从processing.Process。

class BackgroundTask(processing.Process):
    def __init__(self, input):
        processing.Process.__init__(self)
        ...

    def run(self):
        ...

(注意,我使用的是Python2.5端口 得到的python多处理 从 http://code.google.com/p/python-multiprocessing/ 这就是它正在处理的原因 而不是多处理。 我想这没什么区别。 我说得对吗?)

连接到按钮点击信号的代码 就像是

 processing.freezeSupport()
 task = BackgroundTask(input)
 task.start()

该程序在python intepreter下按预期工作,即。 如果它是从命令行“python myapp.py”启动的。

但是,在我使用py2exe打包程序之后, 每次我按那个按钮的时候 启动后台任务的副本 从主窗口弹出。我不确定 这种行为的原因是什么。我猜 它与以下注释有关 在 http://docs.python.org/library/multiprocessing.html#multiprocessing-programming

“此包中的功能要求main方法可由子级导入。这在编程指南中有介绍,但是这里值得指出。这意味着一些示例,例如multiprocessing.Pool示例在交互式解释器中不起作用 “。”

如果name==“main”在主模块中,我只有一个地方 在典型的pyqt程序中

if __name__ == "__main__":
    a = QApplication(sys.argv)
    QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))
    w = MainWindow()
    w.show()
    a.exec_()

有没有解决这个问题的办法?谢谢!


Tags: self程序http示例taskinputinitmain
3条回答

这个问题是关于Python 2的,已经解决了。对于Python 3,它看起来像:

from multiprocessing import freeze_support

if __name__ == '__main__':
    freeze_support()

    a = QApplication(sys.argv)
    ...

“此包中的功能要求主方法可由子方法导入。”

我认为这意味着您必须在某个地方定义main()函数。

我认为你的实际问题与此有关:

The program works as expected under the python intepreter, i.e. if it is started from the command line "python myapp.py".

However, after I package the program using py2exe, every time when I click that button, > instead of starting the background task, a copy of the main window pops up.

您需要向freeze_support()函数添加一个特殊调用,以使多处理模块与“冻结”可执行文件(例如,使用py2exe生成的可执行文件)一起工作:

if __name__ == "__main__":
    # add freeze support
    processing.freeze_support()
    a = QApplication(sys.argv)
    QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))
    w = MainWindow()
    w.show()
    a.exec_()

引用:http://docs.python.org/library/multiprocessing.html#multiprocessing.freeze_support

相关问题 更多 >

    热门问题