【问题标题】:Pass commandline arguments to a Python script installed with Poetry将命令行参数传递给安装了 Poetry 的 Python 脚本
【发布时间】:2021-08-01 04:40:03
【问题描述】:

documentation 说脚本部分可以在安装包的时候用来安装脚本或者可执行文件。但它没有显示如何将参数传递给脚本的任何示例。

如何使用argparse 接收函数中的参数?

【问题讨论】:

  • 你知道commandline arguments是什么意思吗?或者如何从 shell(linux 或 windows)运行脚本?如果使用 IDE(例如 sypder)或 jupyter-notebook,请务必设置该上下文。

标签: python argparse python-poetry


【解决方案1】:

首先是一个小项目设置:

从一个带有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?

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2014-03-08
    • 2013-10-22
    • 2016-12-19
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 2011-05-20
    • 2018-12-04
    相关资源
    最近更新 更多