From 89d6c3658481859d69b3b13ec5a1166fd3f7f963 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Andrei=20Minc=C4=83?= Date: Tue, 10 Apr 2018 19:01:44 +0300 Subject: [PATCH] Optimize file handling in the find module (#38192) * Optimize file handling Use the best practice of opening and doing operations on an opened file Signed-off-by: Daniel Andrei Minca * Fix docstring to Sphinx type - update the docstrings to Sphinx type, as suggested by Toshio - Move the pattern object assignment outside the context manager, as suggested by Matt Signed-off-by: Daniel Andrei Minca --- lib/ansible/modules/files/find.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/lib/ansible/modules/files/find.py b/lib/ansible/modules/files/find.py index 3613f1e609..b08105df08 100644 --- a/lib/ansible/modules/files/find.py +++ b/lib/ansible/modules/files/find.py @@ -250,19 +250,24 @@ def sizefilter(st, size): def contentfilter(fsname, pattern): - '''filter files which contain the given expression''' + """ + Filter files which contain the given expression + :arg fsname: Filename to scan for lines matching a pattern + :arg pattern: Pattern to look for inside of line + :rtype: bool + :returns: True if one of the lines in fsname matches the pattern. Otherwise False + """ if pattern is None: return True - try: - f = open(fsname) - prog = re.compile(pattern) - for line in f: - if prog.match(line): - f.close() - return True + prog = re.compile(pattern) + + try: + with open(fsname) as f: + for line in f: + if prog.match(line): + return True - f.close() except: pass