简体   繁体   English

使用多处理从两个不同的目录并行运行两个 python 代码

[英]Running two python code in parallel from two different directory using Multiprocessing

Below is my code for running two python code in parallel using multiprocessing:下面是我使用多处理并行运行两个 python 代码的代码:

defs.py定义文件

import os 

def pro(process):      
    #print(process)                                                       
    os.system('python {}'.format(process)) 

Multiprocessing.py多处理.py

import os                                                                       
from multiprocessing import Pool
import multiprocessing as mp
import defs
import datetime
import pandas as pd

processes = ('python_code1.py','python_code2.py')

if __name__ == '__main__':                                                                                
    pool = Pool(processes=4)
    start = datetime.datetime.now()
    print('Start:',start)   
    pool.map(defs.pro, processes)
    end = datetime.datetime.now()
    print('End :',end)   
    total = end-start
    print('Total :', end-start)

This code is running perfectly fine.这段代码运行得很好。 But my requirement is I need to run the python code 'python_code1.py' and 'python_code2.py' from two different directory.但我的要求是我需要从两个不同的目录运行 python 代码“python_code1.py”和“python_code2.py”。

so I made the below changes in Multiprocessing.py :所以我在Multiprocessing.py中进行了以下更改:

path1 = r'C:\Users\code1\python_code1.py'
path2 = r'C:\Users\code2\python_code2.py'

processes = (path1,path2) 

but this is not working for me.但这对我不起作用。

My Multiprocessing.py and defs.py are kept on path `C:\Users\Multiprocessing\'我的Multiprocessing.pydefs.py保存在路径“C:\Users\Multiprocessing\”上

Well an elegant solution using asyncio .使用asyncio的优雅解决方案。 It is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc. Plus it has both high-level and low-level APIs to accomodate any kind of problem.它被用作多个 Python 异步框架的基础,提供高性能网络和 Web 服务器、数据库连接库、分布式任务队列等。此外,它同时具有高级和低级 API 以适应任何类型的问题. And you might find syntax easier as I do:你可能会像我一样发现语法更简单:

import os
import asyncio
    def background(f):
        def wrapped(*args, **kwargs):
            return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)

        return wrapped

    @background
    def pro(process):      
    #print(process)                                                       
    os.system('python {}'.format(process)) 

processes = (r'C:\Users\code1\python_code1.py',r'C:\Users\code2\python_code2.py')
for process in processes:
    pro(process)

Detailed answer on parallelizing for loop.有关并行化 for 循环的详细答案 You might find useful.你可能会觉得有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM