获取脚本终结点

2024-04-25 03:50:35 发布

您现在位置:Python中文网/ 问答频道 /正文

Poetry有一种很好的方法,可以使用poetry run <entrypoint>运行Python入口点。使用Python或Bash从pyproject.toml中以编程方式获取<entrypoints>列表的最佳方法是什么

例如pyproject.toml

[tool.poetry]
name = "random-tool"
version = "1.0"

[tool.poetry.scripts]
tool = "tool.function:main"
other_tool = "other_tool.function:main"
all_the_tools = "other_tool.function:all"

输出为:

entrypoint = [ "tool", "other_tool", "all_the_tools" ]

Tags: the方法runbashpoetrymainfunctiontool
2条回答

使用python,这非常容易,因为您可以使用tomlpyproject.toml文件解析到字典中:

import toml

pyproject = toml.load("pyproject.toml")
print(pyproject["tool"]["poetry"]["scripts"].keys())

OP在一篇评论中表示希望将端点收集到一个可以在以后迭代的结构中

对于这个答案,我将集中讨论一个bash/array想法

第一个问题是解析来自pyproject.toml文件的所需数据;我的示例文件:

$ cat poetry.toml
[tool.poetry]
name = "random-tool"
version = "1.0"

[tool.poetry.scripts]
tool = "tool.function:main"
other_tool = "other_tool.function:main"
all_the_tools = "other_tool.function:all"

[tool.poetry.other_stuff]         # add some gibberish to demonstrate extracting data from middle of file
a = "a"
b = "b"
c = "c"

解析出所需数据的一个sed想法:

$ sed -En '1,/\[tool.poetry.scripts\]/d;/^$/,$d;s/^([^ ]+) .*$/\1/p' poetry.toml
tool
other_tool
all_the_tools

其中:

  • -En-启用E扩展的正则表达式支持并禁止打印模式空间(n
  • 1,/\[tool.poetry.scripts\]/d-删除从第1行到包含字符串的行[tool.poetry.scripts\]范围内的所有内容
  • /^$/,$d-删除从第一个空行(^$)到文件结尾($)范围内的所有内容
  • s/^([^ ]+) .*$)/\1/p-将第一个捕获组定义为第一个空格(([^ ]+))的起始行,但不包括该空格,然后打印第一个捕获组(\1/p

使用awk的一个想法:

$ awk '
/\[tool.poetry.scripts\]/ { extract=1        # set "extract" flag
                            next             # go to next record
                          }

# when "extract" flag = 1:

extract                   { if ( NF == 0)    # if no fields (ie, blank line) then
                               exit          # exit processing
                            print $1         # else print first field
                          }
' poetry.toml
tool
other_tool
all_the_tools

或作为一个班轮:

$ awk '/\[tool.poetry.scripts\]/ { extract=1 ; next } extract { if ( NF == 0) { exit } ; print $1}' poetry.toml
tool
other_tool
all_the_tools


从这里有几种方法可以将这些数据加载到bash数组结构中;使用mapfile的一个想法是:

# load sed output into array endpoints[]

$ mapfile -t endpoints < <(sed -En '1,/\[tool.poetry.scripts\]/d;/^$/,$d;s/^([^ ]+) .*$/\1/p' poetry.toml)

# display contents of the endpoints[] array

$ typeset -p endpoints
declare -a endpoints=([0]="tool" [1]="other_tool" [2]="all_the_tools")


此时,数据已加载到endpoints[]数组中,并可在稍后的时间进行迭代,例如:

for i in "${!endpoints[@]}"
do
    echo "endpoints[${i}] = ${endpoints[${i}]}"
done

由此产生:

endpoints[0] = tool
endpoints[1] = other_tool
endpoints[2] = all_the_tools

相关问题 更多 >