我刚刚偶然发现了一段定义点击选项的代码:
@click.option(
"-s",
"--status",
default=True,
is_flag=True,
help="Show status",
)
Run Code Online (Sandbox Code Playgroud)
这是否意味着状态是True,除非-s提供 ,在这种情况下它将变成False?
我正在尝试创建具有以下行为的应用程序:
myapp- 将启动应用程序并执行操作 A
myapp "some argument"- 会做事情 B。事情 B 受到参数“某些参数”的影响。
myapp command- 将启动具有功能 C 的“命令”(由装饰器表示@cli.command)。这将受到 click 必须提供的所有内容的影响,例如@click.option。
请注意,在我的应用程序中会有更多像 C 这样的命令。
我尝试使用以下代码来实现这一点:
import click
class GroupWithOption(click.Group):
def list_commands(self, ctx):
return ['command']
def get_command(self, ctx, cmd_name):
if cmd_name == 'command':
return command
else:
return do_b
@click.group(cls=GroupWithOption, invoke_without_command=True)
def main():
print("Does A")
@main.command()
def command():
print("Does C")
@main.command()
def do_b():
print("Does B")
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
结果好坏参半。其一,我可以非常轻松地调用 3 种不同的行为(或更多),但我无法弄清楚如何将参数传递给 B 命令。我不喜欢这个解决方案。 …
这个问题是关于点击包的:
/b也尝试过使用,但似乎影响不大。cmdpowershell相同的代码有不同的结果,为什么?import click
def command_required_option_from_option(require_name, require_map):
class CommandOptionRequiredClass(click.Command):
def invoke(self, ctx):
require = ctx.params[require_name]
if require not in require_map:
raise click.ClickException(
"Unexpected value for --'{}': {}".format(
require_name, require))
if ctx.params[require_map[require]] is None:
raise click.ClickException(
"With {}={} must specify option --{}".format(
require_name, require, require_map[require]))
super(CommandOptionRequiredClass, self).invoke(ctx)
return CommandOptionRequiredClass
required_options = {
1: 'gs', # generator_string
2: 'nosp', # number_of_sample_points
3: 'nocp', # number_of_center_points
}
@click.command(context_settings=dict(max_content_width=800), cls=command_required_option_from_option('doe', required_options))
@click.option('--input', required=True, type=click.Path(exists=True), metavar='FILE', …Run Code Online (Sandbox Code Playgroud) I have a CLI application built that uses grouped commands and sub-commands. Everything is working. However, I want to ensure this continues to be the case in the future, so I want to ensure that all of my commands and sub-commands have loaded correctly.
My first thought to do this was to just run
commands = ["config", "othercommand"]
runner = CliRunner()
result = runner.invoke(cli.main)
for command in commands:
assert command in result.output
Run Code Online (Sandbox Code Playgroud)
This has a few pitfalls, from my point …
假设我在文件中定义了一个基本的 click CLI 命令cli.py:
import click
@click.command()
@click.option('--test-option')
def get_inputs(test_option):
return test_option
Run Code Online (Sandbox Code Playgroud)
然后是另一个模块脚本test_cli.py,我想从中使用上面定义的 CLI:
from cli import get_inputs
print('before calling get_inputs')
print(get_inputs())
print('after calling get_inputs')
Run Code Online (Sandbox Code Playgroud)
然后在命令行上:
$ python test_cli.py --test-option test123
before calling get_inputs
Run Code Online (Sandbox Code Playgroud)
因此,运行 Click 命令后,整个 Python 进程就完成了,即使在启动调用的脚本中该 Click 命令之后有要计算的语句和表达式,它们也不会被执行。我将如何实现这一目标?
我有一个带有 Python-click 的命令行脚本,带有参数和选项:
# console.py
import click
@click.command()
@click.version_option()
@click.argument("filepath", type=click.Path(exists=True), default=".")
@click.option(
"-m",
"--max-size",
type=int,
help="Max size in megabytes.",
default=20,
show_default=True,
)
def main(filepath: str, max_size: int) -> None:
max_size_bytes = max_size * 1024 * 1024 # convert to MB
if filepath.endswith(".pdf"):
print("success")
else:
print(max_size_bytes)
Run Code Online (Sandbox Code Playgroud)
参数和选项都有默认值,并且在命令行上工作,并且使用 CLI 时它的行为符合预期。但是当我尝试按照 Click文档测试它并调试它时,它不会进入第一行:
# test_console.py
from unittest.mock import Mock
import click.testing
import pytest
from pytest_mock import MockFixture
from pdf_split_tool import console
@pytest.fixture
def runner() -> click.testing.CliRunner:
"""Fixture for invoking command-line interfaces.""" …Run Code Online (Sandbox Code Playgroud) 我的 Python 脚本有一个名为Command. 我想将我的类的方法作为 CLI 命令调用(类似于python cli-comand.py net get-public-ip)。
我使用了Pythonclick库,但是当我尝试执行它时,它抛出了错误TypeError: get_public_ip() missing 1 required positional argument: 'self'。
果然,我没能通过self。有什么方法可以将参数传递到类方法中,或者任何其他方法吗? click主要与函数一起使用。
我的Python脚本如下:
cli命令.py
import click
import urllib.request
from typing import List, AnyStr
from urllib.error import URLError
from ttn_cli.utils.constants import FETCH_PUBLIC_IP_URL
@click.group()
def cli():
"""
This is the root function of cli module.
"""
pass
@cli.group()
def net():
"""
function act as a group which is linked to root cli function.
""" …Run Code Online (Sandbox Code Playgroud) 是否可以为 a 指定两种输入类型click.option,所提供的值必须位于其中一种类型?
在带有输入的普通 python 函数中,我会像这样声明它:
from typing import Union
def fun(x: Union[int, str]):
if isinstance(x, str):
x = int(x)
return x**2
Run Code Online (Sandbox Code Playgroud)
所以x应该是intor str。
我想click实现同样的目标,只是当输入类型不在定义的类型中时脚本会失败。
我试过了
@click.option('-x', type=(click.INT, click.STRING))
Run Code Online (Sandbox Code Playgroud)
但这似乎只适用于有多个参数的场合。
我正在开发一个使用 Click 的库。它包含在 Docker 映像中。我正在尝试使用 pytest 使用 来测试它click.testing.CliRunner。我用来logging编写日志,并且我已指定这些日志应在pyproject.toml. 当我的代码中引发异常(并且仅在 Docker 内)时,我从 Click 中得到以下异常:
/opt/conda/lib/python3.8/site-packages/click/testing.py:434: ValueError
except Exception as e:
if not catch_exceptions:
raise
exception = e
exit_code = 1
exc_info = sys.exc_info()
finally:
sys.stdout.flush()
> stdout = outstreams[0].getvalue()
E ValueError: I/O operation on closed file.
/opt/conda/lib/python3.8/site-packages/click/testing.py:434: ValueError
Run Code Online (Sandbox Code Playgroud)
我已经设法最小化地重现这个问题。我的代码看起来像这样:
/opt/conda/lib/python3.8/site-packages/click/testing.py:434: ValueError
except Exception as e:
if not catch_exceptions:
raise
exception = e
exit_code = 1
exc_info = sys.exc_info()
finally:
sys.stdout.flush()
> stdout = …Run Code Online (Sandbox Code Playgroud) 你如何让Flask CLI命令接受一个参数?
Flask似乎自定义了Click Group对象,所以这不起作用:
@app.cli.command()
@app.cli.argument('email')
def user_info(email):
...
Run Code Online (Sandbox Code Playgroud) python-click ×10
python ×9
python-3.x ×4
pytest ×2
docker ×1
flask ×1
flask-cli ×1
python-3.7 ×1
testing ×1
unit-testing ×1