执行parallel.py脚本

2024-05-19 19:18:25 发布

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

假设我有刮痧1.py,刮痧2.py,刮痧3.py。你知道吗

我现在运行它的方式是从pycharm单独运行/执行每一个,这样我就可以看到3python.exe在任务管理器中执行。你知道吗

现在我正试图写一个主脚本说刮痧_跑步者.py它将这些刮板作为模块导入并并行运行,而不是按顺序运行。你知道吗

我尝试了子进程,甚至多进程的例子操作系统从各种各样的帖子。。。但是没有任何运气。。。从日志中,它们都是按顺序运行的,从任务管理器中,我只看到一个python.exe执行。你知道吗

这是这种过程的正确模式吗?你知道吗

编辑:1(尝试期货ProcessPoolExecutor)它按顺序运行。你知道吗

from concurrent.futures import ProcessPoolExecutor

import scrapers.scraper_1 as scraper_1
import scrapers.scraper_2 as scraper_2
import scrapers.scraper_3 as scraper_3

## Calling method runner on each scrapper_x to kick off processes
runners_list = [scraper_1.runner(), scraper_1.runner(), scraper_3.runner()]



if __name__ == "__main__":


    with ProcessPoolExecutor(max_workers=10) as executor:
        for runner in runners_list:
            future = executor.submit(runner)
            print(future.result())

Tags: pyimport管理器进程顺序asfuturescraper
2条回答

python中的子进程可能显示为一个单独的进程,也可能不显示为一个单独的进程,这取决于操作系统和任务管理器。^例如,linux中的{}将在树视图中显示父进程下的子进程。你知道吗

我建议看一下这个关于python中multiprocessing模块的深入教程:https://pymotw.com/2/multiprocessing/basics.html

但是,如果python内置的多处理/线程方法不起作用或者对您没有意义,那么您可以通过使用bash调用python脚本来实现所需的结果。下面的bash脚本将生成附加的屏幕截图。你知道吗

#!/bin/sh
./py1.py &
./py2.py &
./py3.py &

parallel python scripts

说明:每个调用末尾的&告诉bash将每个调用作为后台进程运行。你知道吗

您的问题在于如何设置流程。您没有并行运行进程,即使您认为是这样。当您将它们添加到runners_list中,然后将每个运行程序的结果作为多个进程并行运行时,实际上是在运行它们。你知道吗

您要做的是将函数添加到runners_list而不执行它们,然后在多处理pool中执行它们。实现这一点的方法是添加函数引用,即函数的名称。要做到这一点,您不应该包括paranthese,因为这是调用函数的语法,而不仅仅是命名函数。你知道吗

另外,要使未来异步执行,不可能直接调用future.result,因为这将强制代码按顺序执行,以确保结果与调用函数的顺序相同。你知道吗

这意味着你的问题的解决方法是

from concurrent.futures import ProcessPoolExecutor

import scrapers.scraper_1 as scraper_1
import scrapers.scraper_2 as scraper_2
import scrapers.scraper_3 as scraper_3

## NOT calling method runner on each scrapper_x to kick off processes
## Instead add them to the list of functions to be run in the pool
runners_list = [scraper_1.runner, scraper_1.runner, scraper_3.runner]

# Adding callback function to call when future is done.
# If result is not printed in callback, the future.result call will
# serialize the call sequence to ensure results in order
def print_result(future):
    print(future.result)

if __name__ == "__main__":
    with ProcessPoolExecutor(max_workers=10) as executor:
        for runner in runners_list:
            future = executor.submit(runner)
            future.add_done_callback(print_result)

如您所见,在这里,运行程序的调用不会在创建列表时发生,而是在稍后将runner提交给执行器时发生。并且,当结果准备就绪时,调用回调函数,将结果打印到屏幕上。你知道吗

相关问题 更多 >