Python文件复制会删除原始文件

Python文件复制会删除原始文件,python,linux,Python,Linux,我有下面的程序,它通过cron运行并备份星号通话录音 它在大多数情况下都可以正常工作,但是,如果当时正在进行呼叫,那么尝试复制它的行为似乎会杀死它,即它从源和目标都会消失 是否有任何方法可以防止这种情况,例如,在尝试复制文件之前,是否可以测试文件是否正在使用 谢谢 from datetime import datetime from glob import iglob from os.path import basename, dirname, isdir from os import make

我有下面的程序,它通过cron运行并备份星号通话录音

它在大多数情况下都可以正常工作,但是,如果当时正在进行呼叫,那么尝试复制它的行为似乎会杀死它,即它从源和目标都会消失

是否有任何方法可以防止这种情况,例如,在尝试复制文件之前,是否可以测试文件是否正在使用

谢谢

from datetime import datetime
from glob import iglob
from os.path import basename, dirname, isdir
from os import makedirs
from sys import argv
from shutil import copyfile


def copy_asterisk_files_tree(src, fullpath=None):
DEST = datetime.now().strftime('/mnt/shardik/asteriskcalls/' + src)

if fullpath is None:
    fullpath = src

if not isdir(DEST):
    makedirs(DEST)

for path in iglob(src + '/*'):
    if isdir(path):
        copy_asterisk_files_tree(path, fullpath)
    else:
        subdir = '%s/%s' % (
            DEST, dirname(path)[len(fullpath) + 1:]
        )
        if not isdir(subdir):
            makedirs(subdir)
        copyfile(path, '%s/%s' % (
            subdir, basename(path).replace(':', '-')
        ))

if __name__ == '__main__':
if len(argv) != 2:
    print 'You must specify the source path as the first argument!'
    exit(1)
copy_asterisk_files_tree(argv[1])

你需要做的是使用锁。看看这些文件

这一点在前面的问题中也得到了回答,比如这个:,它使用
filelock
()。Filelock是独立于平台的

您也可以写入临时文件并合并它们,但我更愿意这样做

fcntl.flock(fd, op)

Perform the lock operation op on file descriptor fd (file objects
providing a fileno() method are accepted as well). See the Unix manual
flock(2) for details. (On some systems, this function is emulated 
using fcntl().)