From 83fc6881c982a30fff77030d5612f9fdc7e5a22b Mon Sep 17 00:00:00 2001 From: Ben Steffen Date: Tue, 26 Nov 2019 14:23:55 -0500 Subject: [PATCH] Update imports and rename lock_file to open_locked and make it more idiomatic --- python/invirt/common.py | 41 +++++++++++++---------------------------- 1 file changed, 13 insertions(+), 28 deletions(-) diff --git a/python/invirt/common.py b/python/invirt/common.py index effb237..7d1eb21 100644 --- a/python/invirt/common.py +++ b/python/invirt/common.py @@ -1,30 +1,10 @@ -import unittest -from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN -import contextlib as clib -import subprocess +import fcntl +import contextlib + class InvirtConfigError(AttributeError): pass - -@clib.contextmanager -def lock_file(path, exclusive = True): - with clib.closing(open(path, 'w')) as f: - if exclusive: - locktype = LOCK_EX - else: - locktype = LOCK_SH - flock(f, locktype) - try: - yield - finally: - flock(f, LOCK_UN) - - -# -# Exceptions. -# - class InvalidInput(Exception): """Exception for user-provided input is invalid but maybe in good faith. @@ -32,17 +12,22 @@ class InvalidInput(Exception): typo) but not setting an invalid boot CD (which requires bypassing the select box). """ + def __init__(self, err_field, err_value, expl=None): - Exception.__init__(self, expl) + super().__init__(expl) self.err_field = err_field self.err_value = err_value class CodeError(Exception): """Exception for internal errors or bad faith input.""" - pass -# -# Tests. -# +@contextlib.contextmanager +def open_locked(path, exclusive=True): + with open(path, 'w') as f: + fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) + try: + yield f + finally: + fcntl.flock(f, fcntl.LOCK_UN) -- 1.7.9.5