如何让我的 python 脚本等待 shutil.move 实际完成?

How can I make my python script wait for a shutil.move to be actually completed?

我正在使用的 python 脚本曾一度将文件列表从一个目录移动到另一个目录。我已经用 shutil.move:

实现了它
for a_file in list_of_filenames:
    src = os.path.join(src_dir, a_file)
    dest = os.path.join(dest_dir, a_file)
    shutil.move(src, dest)

在那之后,我立即将这个文件名列表写入一个命名管道中,该管道插入我的主程序(用 C 编写)中。然后继续读取这些文件,假设它们已到达目标目录。问题是,如果我不告诉我的 python 脚本在写入管道之前等待几秒钟,我的主程序就会阻塞说其中一个文件确实存在。

根据我目前的研究,以及我对问题的有限理解,OS 似乎可以通知我的脚本移动已完成,而实际上它还没有实际完成。

现在等待几秒钟听起来还不错,但是如果我必须移动 100、1000 甚至 10000 个文件怎么办?是否足够,还是我需要等待更长的时间?我如何才能真正确保我的文件在处理它们之前已被移动?

到目前为止我的想法是这样的:

was_moved = [False for _ in range(len(list_of_files))]
while not all(was_moved):
    for i, a_file in enumerate(files):
        if was_moved[i]:
            continue

        try:
            # try to open the file in read mode to see if it actually exists
            open_file = open(os.path.join(dest_dir, a_file), "r")
        except FileNotFoundError:
            continue

        open_file.close()
        was_moved[i] = True

虽然这感觉像是笨拙的编程,但我什至不确定 open 是否正确测试了文件,或者 运行 循环所花费的时间是否是移动的原因成功的。欢迎任何实现这一目标的见解或更好的想法。

您可以使用 subprocess.call() 调用命令行操作来完成您想要的操作。它不会 return 直到子进程完成,这意味着您的文件已移动:

在 linux 上:

import subprocess
for a_file in list_of_filenames:
    src = os.path.join(src_dir, a_file)
    dest = os.path.join(dest_dir, a_file)
    subprocess.call('mv ' + src + ' ' + dest)

在 windows 上:

import subprocess
for a_file in list_of_filenames:
    src = os.path.join(src_dir, a_file)
    dest = os.path.join(dest_dir, a_file)
    subprocess.call('move ' + src + ' ' + dest, shell=True)

我知道这是一个老问题,但我最近自己 运行 遇到了这个问题。为确保文件确实被移动,更改需要同步到磁盘。 Python 自 Python 3.3.

起就对其进行了巧妙的调用
os.sync()

对于 python 的旧版本,您可以使用:

from subprocess import check_call
check_call(['sync'])