| 1 |
# Copyright 2014-2015 Nathan West |
| 2 |
# |
| 3 |
# This file is part of autocommand. |
| 4 |
# |
| 5 |
# autocommand is free software: you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU Lesser General Public License as published by |
| 7 |
# the Free Software Foundation, either version 3 of the License, or |
| 8 |
# (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 of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
# GNU Lesser General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU Lesser General Public License |
| 16 |
# along with autocommand. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
|
| 18 |
import sys |
| 19 |
from .errors import AutocommandError |
| 20 |
|
| 21 |
|
| 22 |
class AutomainRequiresModuleError(AutocommandError, TypeError): |
| 23 |
pass |
| 24 |
|
| 25 |
|
| 26 |
def automain(module, *, args=(), kwargs=None): |
| 27 |
''' |
| 28 |
This decorator automatically invokes a function if the module is being run |
| 29 |
as the "__main__" module. Optionally, provide args or kwargs with which to |
| 30 |
call the function. If `module` is "__main__", the function is called, and |
| 31 |
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 not |
| 33 |
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 then |
| 42 |
sys.exit called with the return value. |
| 43 |
''' |
| 44 |
|
| 45 |
# Check that @automain(...) was called, rather than @automain |
| 46 |
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 traceback |
| 54 |
def automain_decorator(main): |
| 55 |
sys.exit(main(*args, **kwargs)) |
| 56 |
|
| 57 |
return automain_decorator |
| 58 |
else: |
| 59 |
return lambda main: main |