Add argparse-checker for file allowing empty
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Mon, 8 Nov 2021 08:24:40 +0000 (09:24 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Mon, 8 Nov 2021 08:24:40 +0000 (09:24 +0100)
Often one needs to give as argument an existing file, so we have a check for
that, that can be used with argparse. However, sometimes you want to give
users the option to not give a filename at all, which is what this new
checker allows.

src/argparse_helpers.py

index e18a1c2..91e64d2 100644 (file)
@@ -79,3 +79,12 @@ def existing_file(filename):
     if isfile(filename):
         return filename
     raise ArgumentTypeError('{} is not an existing file'.format(filename))
+
+
+def existing_file_or_empty(filename=''):
+    """
+    Like :py:func:`existing_file` but accepts empty filename (returns '' then).
+    """
+    if not filename.strip():
+        return ''
+    return existing_file(filename)