刚接触 python 中的多处理,考虑您具有以下函数:
def do_something_parallel(self):
result_operation1 = doit.main(A,B)
do_something_else(C)
现在的重点是我希望 doit.main
在另一个进程中运行并且是非阻塞,所以 do_something_else 中的代码将在第一个之后立即运行已在另一个进程中启动。
- 如何使用 python
subprocess
模块来完成? - 除了另一个进程之外,子进程和创建新进程之间是否有区别,为什么我们需要其他进程的子进程?
注意:我不想在这里使用多线程方法..
编辑:我想知道是否禁止在同一函数中使用子进程模块
和多进程模块
?
我想要这个的原因是我有两个东西要运行:第一个是一个 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?
没有。您可以在同一个函数中同时使用 subprocess
和 multiprocessing
(此外,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/