简体   繁体   English

将命令行 arguments 传递给安装了 Poetry 的 Python 脚本

[英]Pass commandline arguments to a Python script installed with Poetry

The poetry documentation says that the script section can be used to install scripts or executable when the package is installed.诗歌文档说脚本部分可用于安装 package 时安装脚本或可执行文件。 But it does not show any example of how to pass arguments to the script.但它没有显示如何将 arguments 传递给脚本的任何示例。

How can you do to receive with argparse the arguments in the function?如何使用argparse接收 function 中的 arguments?

First a little project setup:首先是一个小项目设置:

Starting from a new poetry project with poetry new example_script (and creating a main.py file inside example_script dir) with a structure like this:从一个带有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

And adding in the pyproject.toml the config (in the section [tool.poetry.scripts] ) of the script that we are going to install:并在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

And finally the main.py file, which has to have a start function inside (as we passed it in the toml).最后是main.py文件,它必须有一个start function 内部(我们在 toml 中传递它)。 The arguments parser goes inside this function, since this function is the one that will end up executing when we run the script: arguments 解析器进入这个 function,因为这个 function 是我们运行脚本时最终会执行的那个:

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)

We can run the script with poetry, or install and run it directly:我们可以用诗歌运行脚本,也可以直接安装运行:

# 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?

This question is really two separate questions:这个问题实际上是两个独立的问题:

  1. How do I pass arguments into a script that is run using Poetry如何将 arguments 传递到使用 Poetry 运行的脚本中
  2. How do I access and parse those arguments, in particular, using argparse如何访问和解析那些 arguments,特别是使用 argparse

The initial answer (by Lucas), addresses parts of each, especially about argparse, but I'm answering to fill in some additional details and explain how to directly access the args.最初的答案(由卢卡斯)解决了每个部分的问题,尤其是关于 argparse,但我回答是为了填写一些额外的细节并解释如何直接访问 args。

Access arguments directly in any function or script直接在任意 function 或脚本中访问 arguments

As an alternative to argparse, arguments can be directly accessed in Python at any time using sys.argv , which is a list of strings, each one is one of the arguments.作为 argparse 的替代方案,arguments 可以随时使用sys.argv在 Python 中直接访问,这是一个字符串列表,每个字符串都是 arguments 之一。 Python splits up the arguments based on spaces, unless the spaces are enclosed in quotes (either single or double quotes). Python 根据空格拆分 arguments,除非空格用引号引起来(单引号或双引号)。

This method is more direct and lightweight than argparse, with a lot less functionality.这种方法比 argparse 更直接、更轻量级,功能也少了很多。

args.py setup as a main script file with a start() function: args.py设置为带有start() function 的主脚本文件:

import sys

def start(args=sys.argv):
  for i, arg in enumerate(args):
    print(f'Arg #{i}: {arg}')

if __name__ == '__main__':
  start()

Run it at the command-line with a variety of argument types:使用各种参数类型在命令行运行它:

$ py 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

The first argument is always the script that was called, in exactly the way it was called (ie relative or absolute path to the script file or other reference).第一个参数始终是被调用的脚本,完全按照它被调用的方式(即脚本文件或其他引用的相对或绝对路径)。

Adding arguments when calling with poetry run使用poetry run调用时添加 arguments

While you can run scripts with Poetry by activating the virtual environment with poetry shell and then running the script as normal with python script.py arg1 arg2 arg3 , you can also add arguments directly to the poetry run command:虽然您可以通过使用poetry shell激活虚拟环境,然后使用python script.py arg1 arg2 arg3正常运行脚本来使用poetry run运行脚本,但您也可以直接将 ZDBC11CAA5BDA99F77E6FB4 runDABD88 命令添加到 ZDBC11CAA5BDA99F77E6FB4 runDABD88

At the command-line, directly running the script:在命令行,直接运行脚本:

$ poetry run python args.py arg1 arg2 arg3
Arg #0: <some_path>/args.py
Arg #1: arg1
Arg #2: arg2
Arg #3: arg3

Or, run it as a script, installed by Poetry.或者,将其作为脚本运行,由 Poetry 安装。 In this case the script name we assign is arg_script , and you just run it directly (not by invoking with python):在这种情况下,我们分配的脚本名称是arg_script ,您只需直接运行它(而不是通过 python 调用):

In pyproject.toml :pyproject.toml

[tool.poetry.scripts]
arg_script = 'args:start' # run start() function from ./args.py

At a command-line, using poetry run :在命令行,使用poetry run

$ poetry run arg_script arg1 arg2 arg3
Arg #0: arg_script
Arg #1: arg1
Arg #2: arg2
Arg #3: arg3

With poetry run , following arguments act just like you were typing them into a command prompt for a terminal with the virtual environment activated.使用poetry run ,跟随 arguments 就像您在激活虚拟环境的终端的命令提示符中键入它们一样。 ie The equivalent is:即等价于:

$ poetry shell
$ args_script arg1 arg2 arg3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM