Aluode/PerceptionLabPortable
0
1# Copyright 2014-2015 Nathan West2#3# This file is part of autocommand.4#5# autocommand is free software: you can redistribute it and/or modify6# it under the terms of the GNU Lesser General Public License as published by7# the Free Software Foundation, either version 3 of the License, or8# (at your option) any later version.9#10# autocommand is distributed in the hope that it will be useful,11# but WITHOUT ANY WARRANTY; without even the implied warranty of12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13# GNU Lesser General Public License for more details.14#15# You should have received a copy of the GNU Lesser General Public License16# along with autocommand. If not, see <http://www.gnu.org/licenses/>.17 18import sys19from .errors import AutocommandError20 21 22class AutomainRequiresModuleError(AutocommandError, TypeError):23 pass24 25 26def automain(module, *, args=(), kwargs=None):27 '''28 This decorator automatically invokes a function if the module is being run29 as the "__main__" module. Optionally, provide args or kwargs with which to30 call the function. If `module` is "__main__", the function is called, and31 the program is `sys.exit`ed with the return value. You can also pass `True`32 to cause the function to be called unconditionally. If the function is not33 called, it is returned unchanged by the decorator.34 35 Usage:36 37 @automain(__name__) # Pass __name__ to check __name__=="__main__"38 def main():39 ...40 41 If __name__ is "__main__" here, the main function is called, and then42 sys.exit called with the return value.43 '''44 45 # Check that @automain(...) was called, rather than @automain46 if callable(module):47 raise AutomainRequiresModuleError(module)48 49 if module == '__main__' or module is True:50 if kwargs is None:51 kwargs = {}52 53 # Use a function definition instead of a lambda for a neater traceback54 def automain_decorator(main):55 sys.exit(main(*args, **kwargs))56 57 return automain_decorator58 else:59 return lambda main: main60 