首先是一些项目设置:
从一个新的诗歌项目开始poetry new example_script
(并创建一个main.py
里面的文件example_script
dir) 的结构如下:
├── 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?