我有一个像这样的脚本:
#myscript.py
import click
def step1(arg1):
print('Step 1: ' + arg1)
def step2(arg2):
print('Step 2: ' + arg2)
def main(arg1, arg2):
step1(arg1)
step2(arg2)
Run Code Online (Sandbox Code Playgroud)
大多数时候我想使用 运行脚本myscript arg1 arg2,但有时我可能只想运行一个步骤:例如myscript step1 arg1。如何设置点击来执行此操作?有没有一种方法可以让一个默认命令和其他可选命令一起使用?
这似乎是Click 不鼓励的一件事:
有时,从一个命令调用另一个命令可能会很有趣。Click 通常不鼓励这种模式,但尽管如此,这种模式还是有可能的。
我需要使用这个click.invoke()模式吗?
我有这行代码,预计会获取传递给我的 Python 脚本的所有文件名:
@click.argument("logs", nargs=-1, type=click.File('r'), required=1)
Run Code Online (Sandbox Code Playgroud)
当没有传递文件名时,我想默认为-,即标准输入。所以,如果我尝试:
@click.argument("logs", nargs=-1, type=click.File('r'), required=1, default="-")
Run Code Online (Sandbox Code Playgroud)
单击变得不高兴并抛出此错误:
TypeError: 不支持 nargs=-1 与默认值的组合。
有解决方法吗?我尝试设置nargs=0但引发了不同的错误:
IndexError:元组索引超出范围
python command-line-interface command-line-arguments python-click
Context:
I'm having several scripts with loads of sub commands that I'd like to convert to using click
目前,所有这些命令都接受-h和--help以便显示帮助选项。我想保持这种行为。
问题:
单击接受默认--help显示帮助文本,但不显示-h
对于单击命令,可以通过添加轻松更改。
@click.group()
@click.help_option("--help", "-h")
def cli():
""" the doc string """
enter code here
@cli.command()
@click.help_option("--help", "-h")
def mycommand()
pass
@cli.command()
@click.help_option("--help", "-h")
def mycommand1()
pass
...
Run Code Online (Sandbox Code Playgroud)
但是,如果我有数十个命令,我必须重新应用装饰器行
@click.help_option("--help", "-h")
Run Code Online (Sandbox Code Playgroud)
堡垒每个子命令。
有什么技巧可以避免到处写这一行吗?
我正在尝试做一个接受多个参数的 CLI,我猜你会说这些参数是嵌套的并且是预定义的。例如,假设我正在尝试创建一个管理关系数据库的实用程序。我想要如下命令:
dbmgr.py create table --name="mytab"
dbmgr.py create view --name="myview" --other-opt=...
dbmgr.py drop table --name=...
dbmgr.py drop user --username=...
Run Code Online (Sandbox Code Playgroud)
在这种情况下,存在一组预定义的操作(“创建”、“删除”等),并且每个操作都有一组特定的预定义对象,每个操作都可以对其进行操作。在这种情况下,“创建”操作只能接受“表”或“视图”对象。
在“drop”操作的情况下,用户只能指定“表”和“用户”对象。在单击的情况下,“创建”、“表”、“视图”和“删除”只是参数吗?如果是这样,如何将可以指定的内容限制为特定值?我不确定这是否是使用组、命令等的情况,如果是,如何?
我试图弄清楚如何对 Click 中的命令进行分类,以类似于kubectl其分隔命令的方式所使用的结构。
例如,在普通的 Click 帮助输出中,我们有:
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
A CLI tool
Options:
-h, --help Show this message and exit.
Commands:
command1 This is command1
command2 This is command2
command3 This is command3
command4 This is command4
Run Code Online (Sandbox Code Playgroud)
相反,对我的使用来说最理想的是进行分离以更好地对命令结构进行分类。
例如:
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
A CLI tool
Options:
-h, --help Show this message and exit.
Specific Commands for X:
command1 This is command1
command2 This is command2
Specific Commands for Y:
command3 This is command3
command4 …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 pytest 测试基于点击的线程应用程序。该应用程序将永远运行并等待键盘事件。
#!/usr/bin/python
import threading
import time
import typing
import logging
import click
def test_func(sample_var:str):
print("Sample is: " + sample_var)
@click.option("--sample", required=True, help="Sample String", default="sample", type=str)
@click.command()
def main(sample: str):
print("Starting App r")
interrupt = False
while not interrupt:
try:
print("Start threading ..")
my_thread = threading.Thread(
target=test_func,
kwargs=dict(sample_var=sample),
daemon=True)
my_thread.start()
my_thread.join(120)
if not interrupt:
print("Resting for 60 seconds")
time.sleep(60)
except(KeyboardInterrupt, SystemExit):
print("Received Keyboard Interrupt or system exisying, cleaning all the threads")
interrupt=True
if __name__ == "__main__":
main(auto_envvar_prefix="MYAPP")
Run Code Online (Sandbox Code Playgroud)
问题是,在测试时我不知道如何发送 …
我正在尝试学习如何使用 Python-click。我无法在我的选项之一中使用帮助参数,所以我最终放弃并更改了代码以不包含该选项的帮助。然而,尽管关闭并重新启动 Python,现在重新启动我的计算机,与尝试使用 help 参数相关的错误消息仍然出现。
import click
def something():
pass
@click.command()
@click.argument('dest_dir',type=click.Path(exists=True, readable=True,
resolve_path=True, dir_okay=True),
help='Location of directory where results will be saved')
@click.option('--use_terms', is_flag=True,
help='Process strings based on terms or phrases')
@click.option('--use_query', is_flag=True, help='Process string based on
search query')
@click.option('--search_phrase', '-s', multiple=True)
def do_process(dest_dir,use_terms,use_query,*search_phrase):
""" testing setting parameters for snip tables"""
outref = open('e:\\myTemp\\testq.txt')
ms = dest_dir + '\n'
if use_terms:
ms += use_term + '\n'
else:
ms += use_query + '\n'
for each in search_phrase:
x = …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用单击库向命令行应用程序添加帮助。正如官方文档中提到的,
对于命令,会生成一个简短的帮助片段。默认情况下,它是命令帮助消息的第一句话,除非它太长。这也可以被覆盖
使用简单的 @click.command 一切正常:
import click
@click.command()
def cli():
"""This is sample description of script."""
if __name__ == '__main__':
cli()
Run Code Online (Sandbox Code Playgroud)
运行它会从方法的 doscstring 显示脚本的描述:
Usage: example.py [OPTIONS]
This is sample description of script.
Options:
--help Show this message and exit.
Run Code Online (Sandbox Code Playgroud)
但是我需要使用 CommandCollection,因为我正在创建一个由多个命令组成的脚本。以下是官方帮助的示例:
import click
@click.group()
def cli1():
pass
@cli1.command()
def cmd1():
"""Command on cli1"""
@click.group()
def cli2():
pass
@cli2.command()
def cmd2():
"""Command on cli2"""
cli = click.CommandCollection(sources=[cli1, cli2])
if __name__ == '__main__':
cli()
Run Code Online (Sandbox Code Playgroud)
而且我不知道如何向整个命令集合添加描述。到目前为止我尝试过的:
这是我的代码:
@click.group()
@click.pass_context
@click.argument('CHALLENGE', type=int)
def challenge(ctx, challenge):
ctx.obj = Challenge(challenge=challenge)
@click.group(invoke_without_command=True, cls=PhaseGroup)
@click.pass_obj
@click.argument('PHASE', type=int)
def phase(ctx, phase):
# Something
challenge.add_command(phase)
Run Code Online (Sandbox Code Playgroud)
这些命令一起工作应该是这样的。
cli challenge 1 phase 1
Run Code Online (Sandbox Code Playgroud)
通过正确执行,它可以按预期工作。
但是当我使用 --help 或在阶段上定义任何其他标志时,它会抛出
cli challenge 1 phase 1 --help
It throws Error: Missing argument "PHASE".
Run Code Online (Sandbox Code Playgroud)
我搜索了 SOF,发现python click app 失败,并显示“缺少参数”,但无法找到问题这是一个有同样问题的用户,但我不太明白答案。
我不能将参数设置为可选,因为它是 CLI 工作的关键部分。
我是第一次尝试 Click,但我遇到了绊脚石。
我希望我的(两个)子命令要么采用文件路径名选项,要么接受来自 STDIN 的文件内容。
允许:使用 --compose-file 的路径
./docker-secret-helper.py secret-hash-ini --compose-file docker-compose-test.yml
Run Code Online (Sandbox Code Playgroud)允许:使用文件内容作为标准输入
cat docker-compose-test.yml | ./docker-secret-helper.py secret-hash-ini
Run Code Online (Sandbox Code Playgroud)
(是否应该有一个选项来指示标准输入,例如-i,,或其他什么?)
不允许: --compose-file 和 stdin 都没有通过
./docker-secret-helper.py secret-hash-ini
Run Code Online (Sandbox Code Playgroud)
应该返回如下内容: You must either pass --compose-file or pipe in stdin.
当前脚本
我当前的脚本接受(仅)文件路径名(通过--compose-file):
#!/usr/bin/env python
import click
from DockerSecretHelper import DockerSecretHelper
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=CONTEXT_SETTINGS)
def cli():
pass
@cli.command(help="retrieves an ini-style file of variables to be used as env vars for docker-compose commmand")
@click.option('--compose-file', help='compose file to work …Run Code Online (Sandbox Code Playgroud) 默认情况下,click 添加了一个--help选项,根据单击命令的结构输出标准化的用法文本:
Usage: ...
Options: ...
Commands:
...
...
Run Code Online (Sandbox Code Playgroud)
如何覆盖此行为以获得自定义帮助输出?我想要做的是使用丰富的库输出自定义消息。