Im running a very simple code snippet in my flask app that downloads a local tmp .mp4 file as the output.
The output file is then uploaded to cloud and ideally, the local tmp file removed to free server space.
import os
import gc
import sieve
def run_autocrop(video_path, s3_client):
file = sieve.File(path = video_path)
active_speaker_detection = True
aspect_ratio = "9:16"
return_video = True
start_time = 0
end_time = -1
speed_boost = True
smart_edit = False
visualize = False
include_subjects = False
include_non_active_layouts = False
prompt = "person"
negative_prompt = ""
single_crop_only = False
crop_movement_speed = 0.0
crop_sampling_interval = 7
autocrop = sieve.function.get("sieve/autocrop")
output = autocrop.run(file, active_speaker_detection, aspect_ratio, return_video, start_time, end_time, speed_boost, smart_edit, visualize, include_subjects, include_non_active_layouts, prompt, negative_prompt, single_crop_only, crop_movement_speed, crop_sampling_interval)
#release resources
del file
gc.collect()
#get output file path
for output_object in output:
temp_path = output_object.path
# upload the file to Wasabi
s3_client.upload_file(temp_path, 'my-cloud-bucket', 'cloud-path-and-filename')
# delete the local file
if os.path.exists(temp_path):
os.remove(temp_path)
return print('Done!')
The script executes normally until it’s time to remove the local file, then I get this error:
ERROR:root:Error: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\myUser\AppData\Local\Temp\tmptjengzrw.mp4'
Turns out that the actual process using the file is Python.exe
. I can’t kill Python so I can’t force-close the process using it, and at the same time the code is so “simple” that I can’t point out where and how Python would have the file still open. There are other modules in my code where im creating and removing video files without a problem, it’s just this specific file created by the autocrop function. Even if I try to manually deleting it via the file explorer I get a pop up indicating is being used by Python. exe and it’s not until I terminate my flask app (Ctr+C) that I’m able to delete the file.
How can I make sure the file is closed so I can delete it in the same script after uploading to the cloud?
Thanks!