获取命令行参数

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

我正在尝试通过单击获取命令行参数,然后再对其进行处理:

print(click.get_current_context().find_root().params)

尽管我给了script cmd1 cmd2 --arg1 --arg2 3,但这只是打印空白。我正在尝试获取显示脚本,cmd1等的字符串或列表。

更新:看来我能够访问sys.argv,我想单击它即可“使用”它,但看起来还可以。但是我不知道那有多可靠,如果某些代码修改了它会怎样?我将其作为元数据传递,但找不到调用get-current-context的好地方。

python python-click
1个回答
0
投票

我可以得到

  • 脚本名称:使用get_current_context().info_name
  • 使用以下参数作为字典传递的参数:get_current_context().params

我正在Click==7.0环境中使用Python 3.6.8

代码:

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    print(click.get_current_context().info_name)
    print(click.get_current_context().params)

if __name__ == '__main__':
    hello()

程序输出:

python sample.py --count 2 --name "shovon"
sample.py
{'count': 2, 'name': 'shovon'}

我使用了Click official documentation中的示例程序。

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