首先是一个小项目设置:
从一个带有poetry new example_script 的新诗歌项目开始(并在example_script 目录中创建一个main.py 文件),其结构如下:
├── example_script
│ ├── __init__.py
│ ├── main.py
├── pyproject.toml
├── README.rst
└── tests
├── __init__.py
└── test_poetry_example.py
并在pyproject.toml 中添加我们要安装的脚本的配置(在[tool.poetry.scripts] 部分):
# pyproject.toml
[tool.poetry]
name = "example_script"
# some lines excluded
[tool.poetry.scripts]
my-script = "example_script.main:start"
# some lines excluded
最后是main.py 文件,其中必须有一个start 函数(正如我们在toml 中传递的那样)。参数解析器进入这个函数,因为这个函数是我们运行脚本时最终会执行的函数:
import argparse
def some_function(target, end="!"):
"""Some example funcion"""
msg = "hi " + target + end
print(msg)
def start():
# All the logic of argparse goes in this function
parser = argparse.ArgumentParser(description='Say hi.')
parser.add_argument('target', type=str, help='the name of the target')
parser.add_argument('--end', dest='end', default="!",
help='sum the integers (default: find the max)')
args = parser.parse_args()
some_function(args.target, end=args.end)
我们可以用诗歌运行脚本,也可以直接安装运行:
# run with poetry
$ poetry run my-script
# install the proyect (this will create a virtualenv if you didn't have it created)
$ poetry install
# activate the virtualenv
$ poetry shell
# run the script
$ my-script --help
usage: my-script [-h] [--end END] target
Say hi.
positional arguments:
target the name of the target
optional arguments:
-h, --help show this help message and exit
--end END sum the integers (default: find the max)
$ my-script "spanish inquisition" --end "?"
hi spanish inquisition?