gpt4 book ai didi

Python 多处理 : how to safely change working directory of one of the processes

转载 作者:行者123 更新时间:2023-11-28 17:04:45 25 4
gpt4 key购买 nike

我需要运行多个并行进程,每个进程执行一组函数。像这样:

import multiprocessing as mp  

data = [set1, set2, set3]
functions = [func1, func2, func3, func4]
# each func is run in its own separate directory

def myProcess(dataset, functions_list):
for func in functions_list:
func(dataset)

for set_i in data:
p = mp.Process(target = myProcess, args = (set_i, functions))
p.start()

问题是 functions 列表中的每个函数都需要在其单独的目录中运行。据我所知,os.chdir 为正在运行的所有进程切换目录。如何确保每个进程在适当的目录中安全运行,而不会突然被另一个进程踢出?

最佳答案

您的出发点不正确:

And os.chdir switches the directory for all processes being run, as far as I know.

没有。它切换当前进程的目录,而不是系统上的每个进程(甚至是组中的每个进程,或类似的东西)。

当然,如果您在启动子目录之前在父目录中chdir,那么子目录将在那个新目录中启动。但是如果你在任何一个 child 中chdir,它不会影响任何其他人。如果您在启动子级后在父级中 chdir,它也不会影响其他任何人。


How can I ensure that each process safely runs in an appropriate directory without suddenly being kicked out of it by another one?

你什么都不用做;这就是每个操作系统的工作方式。


如果您想自己验证这一点,请尝试运行该程序。在您想要的任何平台上,通过该平台支持的每个 startmethod,您将看到子级可以独立更改目录,而不会相互影响或父级。

import multiprocessing
import os

def func():
pid = str(os.getpid())
print(f'{pid}: {os.getcwd()}')
try:
os.mkdir(pid)
except FileExistsError:
pass
os.chdir(pid)
print(f'{pid}: {os.getcwd()}')

if __name__ == '__main__':
import sys
startmethod = sys.argv[1] if len(sys.argv)>1 else 'fork'
multiprocessing.set_start_method(startmethod)
print(f'{os.getpid()}: {os.getcwd()}')
children = [multiprocessing.Process(target=func) for _ in range(2)]
for child in children:
child.start()
for child in children:
child.join()
print(f'{os.getpid()}: {os.getcwd()}')

关于Python 多处理 : how to safely change working directory of one of the processes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51755534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com