diff options
author | Michael Schwarz <michi.schwarz@gmail.com> | 2015-09-11 21:55:58 +0200 |
---|---|---|
committer | Michael Schwarz <michi.schwarz@gmail.com> | 2015-09-16 01:50:23 +0200 |
commit | 096db19a9a465cc667aa5d0ef92df2eeac5955b2 (patch) | |
tree | eba053a06141adb569d6f33fb9e28675faecc0a6 /support/lib | |
parent | 93f96964914ae30686d30e5667bff92f2d17b791 (diff) | |
download | pogojig-096db19a9a465cc667aa5d0ef92df2eeac5955b2.tar.gz pogojig-096db19a9a465cc667aa5d0ef92df2eeac5955b2.tar.bz2 pogojig-096db19a9a465cc667aa5d0ef92df2eeac5955b2.zip |
Wrap all Python main functions with decorator.
This decorator check if a module was called as the main module and catches exceptions.
Diffstat (limited to 'support/lib')
-rw-r--r-- | support/lib/util.py | 23 |
1 files changed, 22 insertions, 1 deletions
diff --git a/support/lib/util.py b/support/lib/util.py index e343b73..d14b342 100644 --- a/support/lib/util.py +++ b/support/lib/util.py @@ -1,4 +1,4 @@ -import contextlib, subprocess, tempfile, shutil, re, os +import sys, contextlib, subprocess, tempfile, shutil, re, os, inspect class UserError(Exception): @@ -6,6 +6,27 @@ class UserError(Exception): super(UserError, self).__init__(message.format(*args)) +def main(fn): + """Decorator for "main" functions. Decorates a function that should be called when the containing module is run as a script (e.g. via python -m <module>).""" + + frame = inspect.currentframe().f_back + + def wrapped_fn(*args, **kwargs): + try: + fn(*args, **kwargs) + except UserError as e: + print >> sys.stderr, 'Error:', e + sys.exit(1) + except KeyboardInterrupt: + sys.exit(2) + + if frame.f_globals['__name__'] == '__main__': + wrapped_fn(*sys.argv[1:]) + + # Allow the main function also to be called explicitly + return wrapped_fn + + def rename_atomic(source_path, target_path): """ Move the file at source_path to target_path. |