многопроцессорная обработка с python 3: когда мой дочерний процесс завершен, он уничтожает другой процесс - PullRequest
0 голосов
/ 22 марта 2020

Я постараюсь объяснить вам мою проблему.

Я хочу запускать разные процессы одновременно.

Итак, моя цель:

  • Загрузка нескольких файлов одновременно

  • Когда zip загружен, я хочу применить обработку ко всем содержащимся в нем файлам, используя многопроцессорную обработку

Проблема в том, что как только один файл обрабатывается, все остальные процессы уничтожаются.

Вот часть моего кода:

IE: я создаю некоторый процесс с main .py и reidentify.py

MAIN.PY
class NoDaemonProcess(multiprocessing.Process):
    @property
    def daemon(self):
        return False

    @daemon.setter
    def daemon(self, value):
        pass

class NoDaemonContext(type(multiprocessing.get_context())):
    Process = NoDaemonProcess

class MyPool(multiprocessing.pool.Pool):
    def __init__(self, *args, **kwargs):
        kwargs['context'] = NoDaemonContext()
        super(MyPool, self).__init__(*args, **kwargs)

def parse_args():
    """Parse arguments"""
    # Some code

def execute(args, row):
    """Execute function"""
    try:
      upload_file = #some code

        # Download study
        download_ = download.Download(
            upload_file,
            # Some code
        )

        # Re-identification
        reidentify_ = reidentify.Reidentify(
            upload_file,
        )
        reidentify_.check_if_dicom_is_reidentify()
        download_.download_study()
        reidentify_.reidentify()

    except Exception as error:
        raise

def main():
    """Main function"""
    try:
        args = parse_args()

        csv_file = pd.read_csv(args.fpath_csv)

        msg = 'Some required CSV columns are missing'
        assert set(csv_file.columns) >= required_columns, msg

        # Create a multiprocessing Pool
        with MyPool() as pool:
            func = partial(execute, args)
            pool.map(func, zip(csv_file.iterrows()))

        LOGGER.info("Completed")

    except Exception as error:
        LOGGER.error(error)
        sys.exit(1)
REIDENTIFY.PY

class Reidentify:
    """Re-identify class"""
    def processing_data(self, archive_, file):
        """Processing data"""
        # Edit Dicom general fields

    def reidentify(self):
        """Re-identify dicom and save to filepath_output"""
        try:
            # Re-identification of the Dicom
            archive_ = archive.Archive(self.download.filepath_download)
            with multiprocessing.Pool() as pool:
                func = partial(self.processing_data, archive_)
                pool.map(func, archive_.list_archive_files())

            LOGGER.info(f"{self.filepath_output} is re-identified")

        except DicomAlreadyReidentified as error:
            LOGGER.info(error)
            return
        except Exception:
            raise
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...