Home > Software engineering >  How to invoke @Click (Python) but also pass in other parameters that aren't from Click?
How to invoke @Click (Python) but also pass in other parameters that aren't from Click?

Time:11-09

I have a python script that I am trying to invoke from bash/shell/cli. I have used a module called 'Click' before; however, I don't think it's possible to both pass in parameters using 'Click' AND passing in non-click parameters (such as a dictionary or list). Is there a way I can still pass in the non-click parameter? (Below is my attempt at trying to accomplish this:)

response_dict = json.loads(response.text)

@click.command()
@click.argument("md5hash_passed")

def find_pr_id (response, md5hash_passed):
   values = response["values"]
   for item in values:
      item_id = item["id"]
      fromref = item["fromRef"]
      md5_hash = fromref["latestCommit"]
      branch_name = fromref["displayId"]
      if md5_hash == md5hash_passed:
         return item_id

find_pr_id(response_dict)

Thanks in advance.

CodePudding user response:

You don't run find_pr_id directly, try this:

import click

@click.group()
@click.pass_context
def cli(ctx):
    ctx.obj = json.loads(response.text)

@cli.command()
@click.pass_obj
@click.argument("md5hash_passed")
def find_pr_id (request, md5hash_passed):
    values = request["values"]
    for item in values:
        item_id = item["id"]
        fromref = item["fromRef"]
        md5_hash = fromref["latestCommit"]
        branch_name = fromref["displayId"]
        if md5_hash == md5hash_passed:
            return item_id

if __name__ == "__main__":
    cli()

run with :

python test.py find-pr-id 123
  • Related