有没有办法将命令行解析到python-click中,然后单击手动执行回到我的代码?

发布于 2025-02-07 10:59:01 字数 706 浏览 0 评论 0 原文

当我在下面运行代码时,处理域()调用下方都没有处理任何内容。 Gibberish甚至没有异常。似乎要使用单击,您必须执行 everyathy 单击方式,我能说的最好是将所有代码移动到装饰器函数中?

是否有一种方法可以将命令行解析以单击,然后单击手动执行回到我的代码?

import click
my_cfg = { 'domains': [], 'def_domains': ['stackoverflow.com', 'google.com'] } 

@click.command()
@click.option('--domain', '-d', multiple=True, type=str, nargs=1, default=my_cfg['def_domains'])
def domains(domain):
    click.echo('\n'.join(domain))
    my_cfg['domains'].append(domain)
domains()

fgddtruhygtuit5r # No exception thrown!! Once domains() is called my code never runs

### Bunch of code here that I cannot easily move into domains() ###

从Pycharm内部的Windows运行Python 3.10.x。

When I run the code below, nothing below the domains() call is processed. The gibberish doesn't even throw an exception. It seems like to use click you have to do everything the click way, which as best I can tell is to move all of my code into the decorator functions?

Is there a way to hand the command line parsing to click but then have click hand execution back over to my code?

import click
my_cfg = { 'domains': [], 'def_domains': ['stackoverflow.com', 'google.com'] } 

@click.command()
@click.option('--domain', '-d', multiple=True, type=str, nargs=1, default=my_cfg['def_domains'])
def domains(domain):
    click.echo('\n'.join(domain))
    my_cfg['domains'].append(domain)
domains()

fgddtruhygtuit5r # No exception thrown!! Once domains() is called my code never runs

### Bunch of code here that I cannot easily move into domains() ###

Running python 3.10.x on Windows from within PyCharm.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷乱花海 2025-02-14 10:59:01

简短版本在standalone_mode = false时传递时,调用单击命令时。

使用python'click'库的解析器作为简单函数

以下是一个示例:

import click
my_cfg = {
    'domains':     [],
    'def_domains': ['stackoverflow.com', 'google.com'],
    }

@click.command()
@click.option('--domain', '-d', multiple=True, type=str, nargs=1, default=my_cfg['def_domains'])
def domains(domain):
    my_cfg['domains'].append(domain)

domains(standalone_mode=False)

print(f"my_cfg: {my_cfg}")

for_testing.py

my_cfg: {'domains': [('stackoverflow.com', 'google.com')], 'def_domains': ['stackoverflow.com', 'google.com']}

for_testing.py -d duckduckgo.com

my_cfg: {'domains': [('duckduckgo.com',)], 'def_domains': ['stackoverflow.com', 'google.com']}

for_testing.py -d duckduckgo.com -d google.com -d google.com -d bing.com

my_cfg: {'domains': [('duckduckgo.com', 'google.com', 'bing.com')], 'def_domains': ['stackoverflow.com', 'google.com']}

编辑:您需要处理异常,甚至退出 - version,for -version, -h和-help自己。这是我在一起的一些代码:

def process_cli_using_click(my_cli):
    #param my_cli: The function you defined via click to process the command line arguments
    click_invoke_rc = None

    try:
        click_invoke_rc = my_cli(standalone_mode=False)
    except click.exceptions.NoSuchOption as err:
        print(f"{err}")
        print(f"Try running the program with -h or --help.")
        exit(3)
    except click.exceptions.UsageError as err:
        print(f"{err}")
        print(f"Try running the program with -h or --help.")
        exit(5)
    except:
        err = sys.exc_info()[0]
        print(f"An unexpected command line processing error occurred:")
        print(f"{err}")
        print(f"Try running the program with -h or --help.")
        exit(10)

    if click_invoke_rc == 0:  # Catch if -h, --help, --version, or something unknown was specified
        exit(1)

Short version is pass in standalone_mode=False when calling your click commands.

Found the answer in Program stops when running @click.command. And I learned about it in Using the Python 'click' library's parser as a simple function.

Here's an example:

import click
my_cfg = {
    'domains':     [],
    'def_domains': ['stackoverflow.com', 'google.com'],
    }

@click.command()
@click.option('--domain', '-d', multiple=True, type=str, nargs=1, default=my_cfg['def_domains'])
def domains(domain):
    my_cfg['domains'].append(domain)

domains(standalone_mode=False)

print(f"my_cfg: {my_cfg}")

for_testing.py

my_cfg: {'domains': [('stackoverflow.com', 'google.com')], 'def_domains': ['stackoverflow.com', 'google.com']}

for_testing.py -d duckduckgo.com

my_cfg: {'domains': [('duckduckgo.com',)], 'def_domains': ['stackoverflow.com', 'google.com']}

for_testing.py -d duckduckgo.com -d google.com -d bing.com

my_cfg: {'domains': [('duckduckgo.com', 'google.com', 'bing.com')], 'def_domains': ['stackoverflow.com', 'google.com']}

Edit: You'll need to handle exceptions and even exiting for --version, -h, and -help yourself. Here's some code I kludged together:

def process_cli_using_click(my_cli):
    #param my_cli: The function you defined via click to process the command line arguments
    click_invoke_rc = None

    try:
        click_invoke_rc = my_cli(standalone_mode=False)
    except click.exceptions.NoSuchOption as err:
        print(f"{err}")
        print(f"Try running the program with -h or --help.")
        exit(3)
    except click.exceptions.UsageError as err:
        print(f"{err}")
        print(f"Try running the program with -h or --help.")
        exit(5)
    except:
        err = sys.exc_info()[0]
        print(f"An unexpected command line processing error occurred:")
        print(f"{err}")
        print(f"Try running the program with -h or --help.")
        exit(10)

    if click_invoke_rc == 0:  # Catch if -h, --help, --version, or something unknown was specified
        exit(1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文