click是一个python包,用于为您的应用程序创建漂亮的命令行界面.我一直在玩点击,今天在github 上推了这个简单的罗马数字转换器.
我现在要做的是测试我的点击应用程序.我正在阅读文档,但不知道如何运行测试.
有没有人有测试点击应用程序的经验?
所以我想要实现的是确保参数是某些预定义集合(这里是tool1,tool2,tool3)的一部分,就像使用@click.option和type=click.Choice(),同时能够传递多个参数,如@click.argumentwith nargs=-1.
import click
@click.command()
@click.option('--tools', type=click.Choice(['tool1', 'tool2', 'tool3']))
@click.argument('programs', nargs=-1)
def chooseTools(programs, tools):
"""Select one or more tools to solve the task"""
# Selection of only one tool, but it is from the predefined set
click.echo("Selected tools with 'tools' are {}".format(tools))
# Selection of multiple tools, but no in-built error handling if not in set
click.echo("Selected tools with 'programs' are {}".format(programs))
Run Code Online (Sandbox Code Playgroud)
这将是这样的例子:
python selectTools.py --tools tool1 tool3 tool2 nonsense
Selected tools with …Run Code Online (Sandbox Code Playgroud) 我有这段代码:
import click
@click.option('--delete_thing', help="Delete some things columns.", default=False)
def cmd_do_this(delete_thing=False):
print "I deleted the thing."
Run Code Online (Sandbox Code Playgroud)
我想重命名 中的选项变量--delete-thing。但是Python不允许变量名中出现破折号。有没有办法编写这种代码?
import click
@click.option('--delete-thing', help="Delete some things columns.", default=False, store_variable=delete_thing)
def cmd_do_this(delete_thing=False):
print "I deleted the thing."
Run Code Online (Sandbox Code Playgroud)
所以delete_thing将被设置为值delete-thing
我写了这个简短的小程序是为了自学 Python 中的面向对象设计。但是我目前遇到了一个非常令人困惑的错误。
Traceback (most recent call last):
File "main.py", line 97, in <module>
cli()
File "C:\Python27\lib\site-packages\click\core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "C:\Python27\lib\site-packages\click\core.py", line 695, in main
with self.make_context(prog_name, args, **extra) as ctx:
File "C:\Python27\lib\site-packages\click\core.py", line 620, in make_context
self.parse_args(ctx, args)
File "C:\Python27\lib\site-packages\click\core.py", line 874, in parse_args
value, args = param.handle_parse_result(ctx, opts, args)
File "C:\Python27\lib\site-packages\click\core.py", line 1390, in handle_parse_result
value = self.full_process_value(ctx, value)
File "C:\Python27\lib\site-packages\click\core.py", line 1675, in full_process_value
return Parameter.full_process_value(self, ctx, value)
File "C:\Python27\lib\site-packages\click\core.py", line 1359, …Run Code Online (Sandbox Code Playgroud) 我有一个使用Python click包的命令行程序.我可以在本地安装和运行它,没问题:
pip install --editable . # (or leave out the editable of course)
Run Code Online (Sandbox Code Playgroud)
现在,我想创建一个可以独立分发和运行的可执行文件.通常情况下,因为我在Windows环境中的时候,我会用一个py2exe,pyinstaller或cx_Freeze.但是,这些包都不起作用.
更具体地说,它们都生成可执行文件,但可执行文件什么都不做.我怀疑这个问题是因为我的main.py脚本没有main功能.任何建议都会非常有用,提前谢谢!
可以使用从此处复制的代码重现问题.
hello.py
import click
@click.command()
def cli():
click.echo("I AM WORKING")
Run Code Online (Sandbox Code Playgroud)
setup.py
from distutils.core import setup
import py2exe
setup(
name="hello",
version="0.1",
py_modules=['hello'],
install_requires=[
'Click'
],
entry_points="""
[console_scripts]
hello=hello:cli
""",
console=['hello.py']
)
Run Code Online (Sandbox Code Playgroud)
如果有人可以提供工作的setup.py文件来创建可执行文件和任何其他所需的文件,那将非常感激.
从控制台:
python setup.py py2exe
# A bunch of info, no errors
cd dist
hello.exe
# no output, should …Run Code Online (Sandbox Code Playgroud) 使用时click我知道如何定义多项选择选项。我也知道如何将选项设置为必需选项。但是,我怎么能表明一个选项B,只需要在设置选项的值A是foo?
下面是一个例子:
import click
@click.command()
@click.option('--output',
type=click.Choice(['stdout', 'file']), default='stdout')
@click.option('--filename', type=click.STRING)
def main(output, filename):
print("output: " + output)
if output == 'file':
if filename is None:
print("filename must be provided!")
else:
print("filename: " + str(filename))
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
如果output选项是stdout,则filename不需要。但是,如果用户选择output是file,则filename必须提供另一个选项。单击是否支持此模式?
在函数的开头,我可以添加如下内容:
if output == 'file' and filename is None:
raise ValueError('When output is "file", a …Run Code Online (Sandbox Code Playgroud) 我正在寻找一些建议,以避免不得不两次实例化一个类;这更多是一个设计模式问题。我正在使用Python Click库创建一个应用程序。
我有一个Settings类,该类首先将所有初始默认设置加载到字典中(硬编码到应用程序中),然后将用户计算机上TOML文件中的所有设置覆盖(如果指定)加载到字典中,然后最后将两者合并并将它们用作类实例(settings.<something>)的属性。
对于大多数这些设置,我还希望能够指定命令行标志。优先级将变为:
为了获得此结果,我发现在使用Click的装饰器时,我必须执行以下操作:
import click
from myapp import Settings
settings = Settings()
pass_settings = click.make_pass_decorator(Settings, ensure=True)
@click.command()
@click.help_option('-h', '--help')
@click.option(
'-s', '--disk-size',
default=settings.instance_disk_size,
help="Disk size",
show_default=True,
type=int
)
@click.option(
'-t', '--disk-type',
default=settings.instance_disk_type,
help="Disk type",
show_default=True,
type=click.Choice(['pd-standard', 'pd-ssd'])
)
@pass_settings
def create(settings, disk_size, disk_type):
print(disk_size)
print(disk_type)
Run Code Online (Sandbox Code Playgroud)
settings = Settings()需要线来提供@click.option与所述装饰default值。该default值可以来自用户替代TOML文件(如果存在),也可以来自应用程序默认值。Settings …我在 Python 3.6.6(在 conda 环境下)上使用 Click 7.0 编写的 CLI 响应缓慢。
使用 pip 安装包(使用 setuptools)后,调用 CLI 时打印帮助消息需要时间:
$ time cli
Usage: cli [OPTIONS] COMMAND [ARGS]...
Welcome in the CLI!
Options:
--version Show the version and exit.
--help Show this message and exit.
real 0m0,523s
user 0m0,482s
sys 0m0,042s
Run Code Online (Sandbox Code Playgroud)
但是,直接从源调用 CLI 时,我没有遇到这种延迟:
$ time python myproject/cli.py
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
Welcome in the CLI!
Options:
--version Show the version and exit.
--help Show this message and exit.
real 0m0,088s
user 0m0,071s …Run Code Online (Sandbox Code Playgroud) 是否可以将选项的默认值定义为单击中的另一个参数?
我想要的是这样的:
@click.command()
@click.argument('project')
@click.option('--version', default=project)
def main(project, version):
...
Run Code Online (Sandbox Code Playgroud)
如果该选项--version为空,它将自动采用project的值。这样的事情可能吗?
我正在使用命令行 shell,并且正在尝试测试一些解析命令参数的函数。
import shlex
import click
def process_cmd(args, called_self=False):
result = args
# Replace aliases
if not called_self:
aliases = click.get_current_context().obj.config['ALIASES']
if result[0] in aliases:
substitution = process_cmd(split_args(aliases[result[0]]), True)
if len(result) == 1:
result = substitution
else:
result = substitution + result[1:]
return result
def split_pipeline(args):
cmd = []
for arg in args:
if arg == '|':
yield process_cmd(cmd)
cmd = []
else:
cmd.append(arg)
# yield the last part of the pipeline
yield process_cmd(cmd)
Run Code Online (Sandbox Code Playgroud)
这是我编写的单元测试split_pipeline:
import parser …Run Code Online (Sandbox Code Playgroud) python ×10
python-click ×10
anaconda ×1
click ×1
conda ×1
cx-freeze ×1
decorator ×1
json ×1
oop ×1
py2exe ×1
pyinstaller ×1
pytest ×1
python-2.7 ×1
setuptools ×1
unit-testing ×1