Python多线程随机行为

2024-06-16 08:34:34 发布

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

我有一个多线程的python应用程序,它对文件进行一系列处理。在

主应用程序正在扫描目录以查找新文件。只要找到文件,就会在其他Python线程中处理该文件(图像/视频编辑、FTP上载、将元数据保存到DB…)。这些处理器的很大一部分都在使用Popen运行外部命令,并等待它们返回。在

当我处理一个文件时,我没有任何问题,一切都很好,但是当主应用程序运行时,它会导致随机行为,最后我会出现一堆错误,比如Popen命令没有返回,FTP服务器断开连接等等。。。在

以下是我的应用程序的简化版本,用于说明:

class VideoEditor(Thread):
    def __init__(self, file, manager):
        Thread.__init__(self);
        self.manager = manager
        self.file = file


    def run(self):
        Popen('some video editing command').wait()

        self.manager.on_video_editing_finished(self)

class FileUploader(Thread):
    def __init__(self, file, manager):
        Thread.__init__(self);
        self.manager = manager
        self.file = file

    def run(self):
        # Uploading the file to ftp server

        self.manager.on_upload_finished(self)

class Manager():
    def __init__(self):
        self.video_editors = []
        self.uploaders = []

    def on_upload_finished(self, uploader):
        self.uploaders.remove(uploader)
        file = uploader.file
        print "Processing finished for %s" % file


    def on_video_editing_finished(self, video_editor):
        self.video_editors.remove(video_editor)
        file = video_editor.file
        u = FileUploader(file, self)
        u.start()
        self.uploaders.append(u)

    def scan_and_process(self):
        # Detect new file
        ve = VideoEditor(new_file, self)
        ve.start()
        self.video_editors.append(ve)

if __name__ == "__main__":
    manager = Manager()
    while True:
        manager.scan_and_process()
        sleep(60)

有更好的设计吗?我是不是做错了什么?在

编辑:创意 这样更好吗?在

^{pr2}$

谢谢!在


Tags: 文件self应用程序initondefvideomanager