Reputation: 609
I've got the program below which runs via cron and backs up asterisk call recordings.
It works fine for the most part, however if a call is in progress at the time then the act of trying to copy it seems to kill it, i.e. it disappears from both the source and destination.
Is there any way to prevent this, i.e. could I test if a file is in use somehow before trying to copy it?
Thanks
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])
Upvotes: 1
Views: 58
Reputation: 12599
What you need to do is use a lock. Take a look at the docs ...
https://docs.python.org/2/library/fcntl.html#fcntl.flock
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().)
This has also been answered on SO in previous questions, such as this one: Locking a file in Python, which uses filelock
(https://pypi.python.org/pypi/filelock/). Filelock is platform independant.
You could also write to a temporary file/s and merge them, but I'd much prefer
Upvotes: 1