[每个功能的python单击模块输入

问题描述 投票:0回答:1

我是适用于Click模块的python新手。因此,在这里我有一个疑问,即仅为主要cli功能提供输入。但是我想一一提供所有功能的输入。可以点击吗?感谢您的进步。

@click.option('--create', default='sub', help='Create')
@click.command()
def create(create):
    click.echo('create called')
    os.system('curl http://127.0.0.1:5000/create')   
@click.option('--conn', default='in', help='connect to server')
@click.command()
def conn(conn):
    click.echo('conn called')
    os.system('curl http://127.0.0.1:5000/')

和我的setup.py

from setuptools import setup
setup(
     name="hello",
     version='0.1',
     py_modules=['hello'],
     install_requires=[
                    'Click',
     ],
     entry_points='''
     [console_scripts]
     hello=hello:cli
''',
)

我的输出期望

$ hello --conn in
  success
  hello --create sub
  success
python python-3.x command-line-interface argparse python-click
1个回答
0
投票

对我来说听起来像您想要基于提供给hello cli的输入的不同命令。因此,Click具有有用的组概念,即可以调用的命令集合。

您可以按照以下方式重新组织代码:


@click.group()
def cli():
    pass

@cli.command()
def create():
    click.echo('create called')
    os.system('curl http://127.0.0.1:5000/create')

@cli.command()
def conn():
    click.echo('conn called')
    os.system('curl http://127.0.0.1:5000/')

def main():
    value = click.prompt('Select a command to run', type=click.Choice(list(cli.commands.keys()) + ['exit']))
    while value != 'exit':
        cli.commands[value]()

if __name__ == "__main__":
    main()

呼叫将是:

$ hello con
$ hello create

似乎您不需要这些选项,因为您不会根据传入或不传入的选项来更改每个命令的行为。有关更多信息,请参考commands and groups Click documentation

© www.soinside.com 2019 - 2024. All rights reserved.