嗨:我是新来单击的,这是我如何未能测试子命令的示例: 由于某些原因,我需要保持 python 环境干净,我创建了一个虚拟环境来安装单击“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()
我还创建了一个 shell 脚本来激活虚拟环境。
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
然后我在 ~/.zshrc 中创建了一个别名,以便创建激活我的虚拟环境的快捷方式。
nano ~/.zshrc
alias aa=/Volumes/di/Temp/weixintong/wxt_DI_Learn/click_test/run_tool.sh
source ~/.zshrc
结果如下:
> 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.
当我测试子命令时,我被困在组命令中
> 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.
您的 bash 脚本没有将“user”参数传递给 python 脚本。
# 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