0

Hi: I'm new to click and here is a example of how I failed to test my sub-command: for some reasons I need to keep my python environment clean and I created a virtual environment to install click in "venv/lib/"

main.py
import click


@click.group()
def cli():
    """This is group command."""
    pass


@click.command()
@click.option('--user', required=True, prompt='your name', help='input your name')
def user(user):
    """This is sub-group command."""
    print(f'Do something here.{user}!')

cli.add_command(user)

if __name__ == '__main__':
    cli()

 

I also created a shell script to activate virtual env.

run_tool.sh
        
# export PYTHONPATH=$PYTHONPATH:'/Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test/venv/lib'
source /Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test/venv/bin/activate
# I tried both activate virtual env and export PYTHONPATH. none of them worked.
cd /Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test
# python3 main.py

then I created an alias in ~/.zshrc in order to create a shortcut to activate my virtual env.

nano ~/.zshrc
alias aa=/Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test/run_tool.sh
source ~/.zshrc

here was the result:

> aa                                                                                 at 11:59:04
Usage: main.py [OPTIONS] COMMAND [ARGS]...

  This is group command.

Options:
  --help  Show this message and exit.

Commands:
  user  This is sub-group command.

when I tested the sub-command I was stuck in the group-command

> aa user                                                                            at 11:59:06
Usage: main.py [OPTIONS] COMMAND [ARGS]...

  This is group command.

Options:
  --help  Show this message and exit.

Commands:
  user  This is sub-group command.
xwei
  • 9
  • 1

1 Answers1

0

Your bash script isn't passing the "user" argument to the python script.

# Get the first argument after the script name, and use it as command
command="$1"
PYTHONPATH=$PYTHONPATH:'/Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test/venv/lib'
source /Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test/venv/bin/activate
cd /Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test
python3 main.py $command
aclowkay
  • 3,577
  • 5
  • 35
  • 66
  • Thanks! it sort of worked. I could enter my sub-command using "aa user". However when I use "aa user --help" the output was the same as using "aa user". Do you know why? – xwei Aug 24 '22 at 06:17
  • PS: after I added another argument it worked fine now. Many thanks! `command="$1" option="$2" source /Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test/venv/bin/activate cd /Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test python3 main.py $command $option` – xwei Aug 24 '22 at 09:52
  • You could use some more bash tricks here to just append everything. https://stackoverflow.com/questions/43413203/how-to-pass-all-but-the-first-argument-to-a-second-bash-script – aclowkay Aug 25 '22 at 08:13