From: Ben Steffen Date: Tue, 26 Nov 2019 19:23:55 +0000 (-0500) Subject: Update imports and rename lock_file to open_locked and make it more idiomatic X-Git-Url: http://xvm.mit.edu/gitweb/invirt/packages/invirt-base.git/commitdiff_plain/83fc6881c982a30fff77030d5612f9fdc7e5a22b Update imports and rename lock_file to open_locked and make it more idiomatic --- 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)