首先进行一些项目设置:
从一个带有
poetry new example_script
的新诗歌项目开始(并在 main.py
目录中创建一个 example_script
文件),其结构如下:
├── 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)
我们可以用poem来运行脚本,或者直接安装运行:
# 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?
这个问题实际上是两个独立的问题:
最初的答案(由 Lucas 提供)解决了每个问题的部分问题,特别是关于 argparse 的问题,但我回答是为了填写一些额外的详细信息并解释如何直接访问 args。
作为 argparse 的替代方案,可以随时使用
sys.argv
在 Python 中直接访问参数,这是一个字符串列表,每个字符串都是参数之一。 Python 根据空格分割参数,除非空格用引号引起来(单引号或双引号)。
这个方法比argparse更直接、更轻量,但功能少了很多。
args.py
设置为具有 start()
功能的主脚本文件:
import sys
def start(args=sys.argv):
for i, arg in enumerate(args):
print(f'Arg #{i}: {arg}')
if __name__ == '__main__':
start()
在命令行中使用各种参数类型运行它:
$ python args.py "item 1" 'Hello Arguments!!' "i 3" 4 5 6
Arg #0: args.py
Arg #1: item 1
Arg #2: Hello Arguments!!
Arg #3: i 3
Arg #4: 4
Arg #5: 5
Arg #6: 6
第一个参数始终是被调用的脚本,其调用方式完全相同(即脚本文件或其他引用的相对或绝对路径)。
poetry run
注意:在 Poetry 的 v2.X 版本中,参数对于
poetry run
命令的作用可能有所不同
虽然您可以通过使用
poetry shell
激活虚拟环境,然后使用 python script.py arg1 arg2 arg3
正常运行脚本来运行 Poetry 脚本,但您也可以直接向 poetry run
命令添加参数:
在命令行,直接运行脚本:
$ poetry run python args.py arg1 arg2 arg3
Arg #0: <some_path>/args.py
Arg #1: arg1
Arg #2: arg2
Arg #3: arg3
或者,将其作为脚本运行,由 Poetry 安装。在这种情况下,我们分配的脚本名称是
arg_script
,您只需在激活虚拟环境的情况下在终端提示符下直接运行它(即不要使用 python 调用):
在
pyproject.toml
:
[tool.poetry.scripts]
arg_script = 'args:start' # run start() function from ./args.py
更新
pyproject.toml
后,在终端提示符下运行 poetry install
,以在名为 arg_script
的虚拟环境中安装脚本。
使用 Poetry,您可以使用
poetry run
在虚拟环境中运行命令:
$ poetry run arg_script arg1 arg2 arg3
Arg #0: arg_script
Arg #1: arg1
Arg #2: arg2
Arg #3: arg3
在
poetry run
之后添加的任何参数,就像您将它们输入到已激活虚拟环境的终端中一样。即等价的是:
$ poetry shell
$ args_script arg1 arg2 arg3