#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May  8 16:19:07 2017

@author: ajaver
"""
import os
import cv2
import sys
import glob
import threading
from functools import partial

main_dir = '/Volumes/behavgenom_archive$/Celine/raw/'
fnames = glob.glob(os.path.join(main_dir, '**', '*.avi'))
fnames = [x for x in fnames if not x.endswith('_seg.avi')]
fnames = sorted(fnames)

def get_and_release(video_file):
    original = sys.stderr
    f = open(os.devnull, 'w')
    sys.stderr = f
    print('here')
    vid = cv2.VideoCapture(video_file)
    vid.release()
    
    sys.stderr = original
    
    return vid

all_threads = []
for ii, video_file in enumerate(fnames):
    print(ii, video_file)
    vid = cv2.VideoCapture(video_file)
    vid.release()
    t = threading.Thread(target = partial(get_and_release, video_file))
    t.start()
    all_threads.append((video_file, t))
    
    
    
[((16, 19, 16, 56), 'os.path.join', 'os.path.join', ({(16, 32, 16, 40): 'main_dir', (16, 42, 16, 46): '"""**"""', (16, 48, 16, 55): '"""*.avi"""'}, {}), "(main_dir, '**', '*.avi')", False, 'import os\n'), ((25, 10, 25, 38), 'cv2.VideoCapture', 'cv2.VideoCapture', ({(25, 27, 25, 37): 'video_file'}, {}), '(video_file)', False, 'import cv2\n'), ((35, 10, 35, 38), 'cv2.VideoCapture', 'cv2.VideoCapture', ({(35, 27, 35, 37): 'video_file'}, {}), '(video_file)', False, 'import cv2\n'), ((37, 34, 37, 70), 'functools.partial', 'partial', ({(37, 42, 37, 57): 'get_and_release', (37, 59, 37, 69): 'video_file'}, {}), '(get_and_release, video_file)', False, 'from functools import partial\n')]