Deleting folder in python in the background
Question:
The standard way of deleting folders in python I am aware of is
shutil.rmtree('/path/to/folder')
However, this command blocks until the deletion is completed, which in the case of large folders can take a long time.
Is there a non-blocking alternative? I.e. a function that would delete the folder in the ‘background’ but return immediately?
Answers:
Since most of the time spent is spent in system calls, a thread can help
import threading,shutil
threading.Thread(target = lambda : shutil.rmtree('/path/to/folder')).start()
that is the shortest way. Maybe a better way would be to create a proper function so the call can be wrapped in a try/except block. Alternatives here: Deleting folders in python recursively
Another alternative would be to call a system command like rm
in the background but that is not very portable, even if this would be faster, but only slightly since most of the time is spent in the operating system anyway.
The standard way of deleting folders in python I am aware of is
shutil.rmtree('/path/to/folder')
However, this command blocks until the deletion is completed, which in the case of large folders can take a long time.
Is there a non-blocking alternative? I.e. a function that would delete the folder in the ‘background’ but return immediately?
Since most of the time spent is spent in system calls, a thread can help
import threading,shutil
threading.Thread(target = lambda : shutil.rmtree('/path/to/folder')).start()
that is the shortest way. Maybe a better way would be to create a proper function so the call can be wrapped in a try/except block. Alternatives here: Deleting folders in python recursively
Another alternative would be to call a system command like rm
in the background but that is not very portable, even if this would be faster, but only slightly since most of the time is spent in the operating system anyway.