命令行应用程序帮助程序库
arseparse的Python项目详细描述
arseparse是一个用于编写命令的简单python实用程序/微框架 线路接口。它提供了一些围绕argparse的功能 包括一些常见的场景。
安装:
pip install arseparse
基本用法:
from arseparse import Parser, Option parser = Parser() # register a command that returns the square of an int parser.register('square', lambda value: value**2, [Option('value', type=int)]) # register a command that simply returns a string parser.register('ping', lambda: 'pong') # or with a decorator @parser.register_dec([Option('value', type=int)]) def cube(value): return value**3 sys.exit(parser.run())
然后可以将应用程序入口指向脚本或执行 文件:your-entrypoint.py square 2
到目前为止很无聊。更常见的情况是将配置文件作为 第一个参数,解析它,创建命令所依赖的对象, 并将它们与解析的属性一起传递。root_options和 bootstrap构造函数参数到Parser允许我们实现这一点:
from arseparse import Parser, Option import myapp # these are options that come before our main command root_options = [Option('config', type=str, help='path to ini file')] # this lets us process/modify the kwargs before we execute the callable. # we can rely on attributes resulting from root_options to be set. # here config gets replaced by three objects: settings, db_session and user_svc def bootstrap(**kwargs): config_uri = kwargs.pop('config') settings = myapp.parse_app_config(config_uri) dbsession = myapp.get_sessionmaker(settings)() user_svc = myapp.UserService(dbsession) kwargs.update(dict(settings=settings, dbsession=dbsession, user_svc=user_svc)) return kwargs parser = Parser(root_options, bootstrap) @parser.register_dec([Option('username', type=str), Option('secret', type=str)]) def create_user(username, secret, user_svc, **kwargs): user_svc.create_user(username, secret) @parser.register_dec([Option('user_id', type=int)]) def ban_user(user_id, user_svc, **kwargs): user_svc.ban_user(user_id) @parser.register_dec() def print_settings(settings, **kwargs): print(settings)
现在可以提供配置文件的路径作为第一个参数: your-entrypoint.py config.ini ban_user 23
另一个常见的要求是能够跳入 已经为我们预先配置了对象。这里有一个简单的方法:
@parser.register_dec() def shell(**kwargs): import IPython IPython.embed(user_ns=kwargs)
调用your-entrypoint.py config.ini shell
将把您放入一个ipython shell中,其中dbsession
、settings
和user_svc
在作用域中。