From 4a0bd6fce593b48b5f360f6982449a7685ba0c9b Mon Sep 17 00:00:00 2001 From: Benjamin Loison Date: Fri, 24 Feb 2023 15:15:42 +0100 Subject: [PATCH] Use `with open(filePath) as f:` instead of `f = open(filePath)` in `search.py` --- website/search.py | 53 ++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/website/search.py b/website/search.py index b90e0e0..2864931 100755 --- a/website/search.py +++ b/website/search.py @@ -15,20 +15,19 @@ searchOnlyCaptions = pathSearchMessageParts[0] == 'search-only-captions' clientFilePath = f'users/{clientId}.txt' def write(s): - f = open(clientFilePath, 'r+') - try: - fcntl.flock(f, fcntl.LOCK_EX) - # If the output file is empty, then it means that `websocket.php` read it. Anyway we don't wait it and we append what we want to output. - read = f.read() - # We are appening content, as we moved in-file cursor. - if read != '': - f.write("\n") - f.write(s) - f.flush() - fcntl.flock(f, fcntl.LOCK_UN) - f.close() - except Exception as e: - sys.exit(e) + with open(clientFilePath, 'r+') as f: + try: + fcntl.flock(f, fcntl.LOCK_EX) + # If the output file is empty, then it means that `websocket.php` read it. Anyway we don't wait it and we append what we want to output. + read = f.read() + # We are appening content, as we moved in-file cursor. + if read != '': + f.write("\n") + f.write(s) + f.flush() + fcntl.flock(f, fcntl.LOCK_UN) + except Exception as e: + sys.exit(e) def cleanCaption(caption): return caption.replace('\n', ' ') @@ -69,17 +68,15 @@ for fileIndex, file in enumerate(files): write(toWrite) break -f = open(clientFilePath) -while True: - try: - fcntl.flock(f, fcntl.LOCK_EX) - if f.read() == '': - os.remove(clientFilePath) - break - else: - fcntl.flock(f, fcntl.LOCK_UN) - time.sleep(1) - except Exception as e: - sys.exit(e) - -f.close() +with open(clientFilePath) as f: + while True: + try: + fcntl.flock(f, fcntl.LOCK_EX) + if f.read() == '': + os.remove(clientFilePath) + break + else: + fcntl.flock(f, fcntl.LOCK_UN) + time.sleep(1) + except Exception as e: + sys.exit(e)