我正在编写带有两个子命令的命令行脚本mycli
:
mkcli init
(用于使用.configrc
文件初始化一个空项目)mkcli run
(运行脚本的主要逻辑)。通常,如果在工作目录中找不到mycli run
文件,则.configrc
不起作用。但是,我的用户应该可以查看针对run
的帮助消息:
$ mycli run --help
Usage: mycli run [OPTIONS]
Options:
--dryrun Run in read-only mode
--help Show this message and exit.
但是,如果不存在.configrc
,这将不起作用,因为在组命令FileNotFoundError
中引发了cli
(并且从未到达run
)。我可以先启动init
子命令而无需使用.configrc
来找到ctx.invoked_subcommand
文件(见下文),但是我无法确保run
子命令能够执行如果使用--help
调用总是触发。
如果用户运行mkcli run
,但没有找到.configrc
文件,我的脚本将以run "mycli init" first
退出。但是,即使没有mycli run --help
,.configrc
也应该起作用。我怎样才能做到这一点?还是有人可以建议一种更好的方法来处理init
?
@click.group()
@click.pass_context
def cli(ctx):
ctx.obj = {}
if ctx.invoked_subcommand != "init":
config = yaml.load(open(".configrc").read())
ctx.obj.update({key: config[key] for key in config})
@cli.command()
@click.pass_context
def init(ctx):
print("Initialize project.")
@cli.command()
@click.option("--dryrun", type=bool, is_flag=True, help="Run in read-only mode")
@click.pass_context
def run(ctx, dryrun):
print("Run main program here.")
答案 0 :(得分:1)
我建议更改初始化代码的运行顺序。可以用...
class LoadInitForCommands(click.Group):
def command(self, *args, **kwargs):
def decorator(f):
# call the original decorator
cmd = click.command(*args, **kwargs)(f)
self.add_command(cmd)
orig_invoke = cmd.invoke
def invoke(ctx):
# Custom init code is here
ctx.obj = {}
if cmd.name != "init":
config = yaml.load(open(".configrc").read())
ctx.obj.update({key: config[key] for key in config})
# call the original invoke()
return orig_invoke(ctx)
# hook the command's invoke
cmd.invoke = invoke
return cmd
return decorator
使用click.group()
参数将自定义类传递给cls
,例如:
@click.group(cls=LoadInitForCommands)
def cli():
""""""
之所以可行,是因为click是一个设计良好的OO框架。 @click.group()
装饰器通常会实例化click.Group
对象,但允许使用cls
参数覆盖此行为。因此,从我们自己的类中的click.Group
继承并超越所需的方法是相对容易的事情。
在这种情况下,我们钩住command()
装饰器,并在该钩子中覆盖命令的invoke()
。这样可以在--help
标志已被处理之后 读取初始化文件。
请注意,该代码旨在简化在读取init之前可以使用--help
的许多命令。在问题的示例中,只有一个命令需要init。如果总是这样,那么this answer可能会很有吸引力。
import click
import yaml
@click.group(cls=LoadInitForCommands)
def cli():
""""""
@cli.command()
@click.pass_context
def init(ctx):
print("Initialize project.")
@cli.command()
@click.option("--dryrun", type=bool, is_flag=True,
help="Run in read-only mode")
@click.pass_context
def run(ctx, dryrun):
print("Run main program here.")
if __name__ == "__main__":
commands = (
'init',
'run --help',
'run',
'--help',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for cmd in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + cmd)
time.sleep(0.1)
cli(cmd.split(), obj={})
except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise
Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> init
Initialize project.
-----------
> run --help
Usage: test.py run [OPTIONS]
Options:
--dryrun Run in read-only mode
--help Show this message and exit.
-----------
> run
Traceback (most recent call last):
File "C:\Users\stephen\AppData\Local\JetBrains\PyCharm 2018.3\helpers\pydev\pydevd.py", line 1741, in <module>
main()
File "C:\Users\stephen\AppData\Local\JetBrains\PyCharm 2018.3\helpers\pydev\pydevd.py", line 1735, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Users\stephen\AppData\Local\JetBrains\PyCharm 2018.3\helpers\pydev\pydevd.py", line 1135, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Users\stephen\AppData\Local\JetBrains\PyCharm 2018.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/stephen/Documents/src/testcode/test.py", line 77, in <module>
cli(cmd.split(), obj={})
File "C:\Users\stephen\AppData\Local\Programs\Python\Python36\lib\site-packages\click\core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "C:\Users\stephen\AppData\Local\Programs\Python\Python36\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "C:\Users\stephen\AppData\Local\Programs\Python\Python36\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:/Users/stephen/Documents/src/testcode/test.py", line 26, in invoke
config = yaml.load(open(".configrc").read())
FileNotFoundError: [Errno 2] No such file or directory: '.configrc'