python - 使用子进程模块并行工作(多进程)

标签 python linux python-2.7 multiprocessing subprocess

刚接触 python 中的多处理,考虑您具有以下函数:

def do_something_parallel(self):
    result_operation1 = doit.main(A,B)    
    do_something_else(C)

现在的重点是我希望 doit.main 在另一个进程中运行并且是非阻塞,所以 do_something_else 中的代码将在第一个之后立即运行已在另一个进程中启动。

  1. 如何使用 python subprocess 模块来完成?
  2. 除了另一个进程之外,子进程和创建新进程之间是否有区别,为什么我们需要其他进程的子进程?

注意:我不想在这里使用多线程方法..

编辑:我想知道是否禁止在同一函数中使用子进程模块多进程模块
我想要这个的原因是我有两个东西要运行:第一个是一个 exe 文件,第二个是一个函数,每个都需要它自己的进程。

最佳答案

如果你想在一个单独的进程中运行 Python 代码,你可以使用 multiprocessing module :

import multiprocessing

if __name__ == "__main__":
    multiprocessing.Process(target=doit.main, args=[A, B]).start()
    do_something_else() # this runs immmediately without waiting for main() to return

I wondered whether using a subprocess module and multiprocess module in the same function is prohibited?

没有。您可以在同一个函数中同时使用 subprocessmultiprocessing(此外,multiprocessing 可以使用 subprocess 来启动它的 worker内部处理)。

Reason I want this is that I have two things to run: first an exe file, and second a function, each needs it own process.

您不需要multprocessing 来无阻塞地运行外部命令(显然,在它自己的进程中); subprocess.Popen()够了:

import subprocess

p = subprocess.Popen(['command', 'arg 1', 'arg 2'])
do_something_else() # this runs immediately without waiting for command to exit
p.wait() # this waits for the command to finish

关于python - 使用子进程模块并行工作(多进程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31429849/

相关文章:

python - 在 Google Compute Engine 上设置静态出站/源 IP 地址

python - 执行 'if list in list' python 的正确方法

c - 如何在C中找到挂载的U盘大小?

查询 ArcGIS Web 服务时出现 Python MemoryError

python - 使用 pytz 的日期时间时区转换

python 列表迭代

python - Seaborn FacetGrid,如何在所有子图中显示 y 刻度标签

Python [Errno 98] 地址已被使用

ruby-on-rails - 如何使用 capistrano 进行部署

python - 如何调用右侧定义的类中存在的方法。 Python继承。多重继承。 Dimond场景python继承