当条件为假时,为什么代码在 if 语句 运行 中?

Why is code inside an if statement running when the condition is false?

我有一个 if 语句来检查目录是否已经存在:

if not os.path.exists(os.path.dirname(save_to)):
     os.makedirs(os.path.dirname(save_to))

在此之后,文件被添加到目录 save_to,无论它以前是否存在。

有时,即使目录已经存在,也会执行 if 语句中的代码。这完全是随机的。

我相信这是因为我正在使用 multiprocessing.Pool.map 将此任务分配给多个 CPU。我认为过程 1 和 2 进入 if 语句。我认为进程 1 然后创建目录,然后进程 2 尝试并失败。

这是我遇到的错误:

multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "/home/WNeill/anaconda3/lib/python3.8/multiprocessing/pool.py", line 125, in worker
    result = (True, func(*args, **kwds))
  File "/home/WNeill/anaconda3/lib/python3.8/multiprocessing/pool.py", line 51, in starmapstar
    return list(itertools.starmap(args[0], args[1]))
  File "/home/WNeill/who-said-what/wsw/preprocessing.py", line 147, in clip_audio ****!!!****
    os.makedirs(os.path.dirname(save_to))                                         ****!!!****
  File "/home/WNeill/anaconda3/lib/python3.8/os.py", line 223, in makedirs
    mkdir(name, mode)
FileExistsError: [Errno 17] File exists: '/home/WNeill/clipped/clipped/aldfly'

我想不出第 147 行的任何其他原因,它对应于上面的代码片段(也在堆栈跟踪中标记)执行。

问题:

我该如何解决这个问题(无论我的假设是否正确)?

建议的解决方案:

我唯一的想法是也许使用参数 exist_ok=True 并去掉 if 语句。如果我使用这种方法,我担心会覆盖工作。我有大约 8 个小时的处理时间,如果有什么东西我会讨厌 deleted/overwritten。

有点沉重的解决方案是参考这个 post Python sharing a lock between processes.

您可以使用此处提到的 ManagerLock 在该部分代码中创建关键部分。换句话说,这会导致第一个到达那里的线程阻止其他线程执行那部分代码,只有释放锁后才能继续他们的快乐。