I am working on a project, and I run a thread. Inside this thread, there is a blocking function (win32file.ReadDirectoryChangesW
) that doesn't allow me to close the thread from within. I tried a few things like closing the tread by getting its id but nothing seems to work:
threading.get_ident()
- crashes when I try to close the thread with that id.os.getpid()
- closes the entire project and not just the thread itself.
Is there a way to close the thread from the outside? Thanks in advance.
import os
import win32file
import win32con
import multiprocessing
import psutil
import threading
import queue
from pubsub import pub
import wx
import time
class monitoring:
@staticmethod
def monitor(path_to_watch, path):
q = queue.Queue()
folderpath = path_to_watch[:path_to_watch.rfind('\\')]
filename = path_to_watch[path_to_watch.rfind('\\') + 1:]
tempfilename = f'~${filename}'
t = threading.Thread(target=monitoring.checkforupdates, args=(q, folderpath,))
t.start()
id = q.get()
while True:
if not q.empty():
results = q.get()
for action, file in results:
if action <= 3:
if file == filename and action == 3:
with open(path_to_watch, 'rb')as f:
wx.CallAfter(pub.sendMessage, 'update_file_flag', filename=path, file=f.read())
elif file == tempfilename and action == 2:
print("temp file closed")
# here i need to close the thread
os.remove(path_to_watch)
print(10)
exit()
else:
time.sleep(5)
@staticmethod
def checkforupdates(q, folderpath):
ACTIONS = {
1: "Created",
2: "Deleted",
3: "Updated",
}
FILE_LIST_DIRECTORY = 0x0001
hDir = win32file.CreateFile(
folderpath,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
while True:
#
# ReadDirectoryChangesW takes a previously-created
# handle to a directory, a buffer size for results,
# a flag to indicate whether to watch subtrees and
# a filter of what changes to notify.
#
# NB Tim Juchcinski reports that he needed to up
# the buffer size to be sure of picking up all
# events when a large number of files were
# deleted at once.
#
results = win32file.ReadDirectoryChangesW(
hDir,
1024,
False,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None
)
q.put(results)