Bash 脚本从 setup.py 或 PKG-INFO 文件获取版本并导出为环境变量

Bash script get version from setup.py or from PKG-INFO file and export as environment variable

我需要从 setup.py 或使用 bash 从 PKG-INFO 获取版本值,并使用版本值提取环境变量以备后用。 (实际上我需要 GitHub 操作的版本值)

from setuptools import setup, find_packages

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name="helloworld",
    version="0.0.3",
    author="John",
    author_email="john@gmail.com",
    url="https://github.com/google/helloworld",
    description="Hello World!",
    long_description=long_description,
    long_description_content_type="text/markdown",
    packages=find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    install_requires=["click"],
    python_requires='>=3.6',
    py_modules=["helloworld"],
    entry_points={"console_scripts": ["helloworld = src.main:main"]},
)

包装信息:

Metadata-Version: 2.1
Name: helloworld
Version: 0.0.3
Summary: Hello World!
Home-page: https://github.com/google/helloworld
Author: John
Author-email: john@gmail.com
License: UNKNOWN
Platform: UNKNOWN
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.6
Description-Content-Type: text/markdown

# helloworld

Hello World Python
...

I need to get version value from setup.py or from PKG-INFO using bash and extract environment variable with the version value for later use.

PKG-INFO 获取所需数据可能比从 setup.py 更容易。如果只有一个 Version: 条目,你可以用 sed:

the_version=$(sed -n 's/^Version: *//p' PKG-INFO) ||
  echo 'no version found' 1>&2
export the_version

解释:

  • sed-n 选项禁止在每个循环结束时打印当前行的默认行为。
  • s 命令从任何以此开头的行中删除 Version: 标签。 p 后缀导致(仅)打印实际执行替换的那些行的替换结果。
  • 围绕 sed 命令的 $() 构造捕获并扩展为该命令的标准输出,这将是 Version: 行的尾部。然后将其分配给 shell 变量 the_version.
  • sed 以非零退出状态终止的情况下,执行 echo 命令以打印诊断信息,该诊断信息被重定向到标准错误而不是标准输出
  • shell 变量被 export 编辑,以便脚本的后续命令 运行 将在其环境中接收它。
  • 如果命令以非零退出状态退出,则会将诊断打印到标准错误流

比我想象的要容易:

VERSION=$(python setup.py --version)
echo $VERSION

同样的方法也可以得到模块名:

MODULE_NAME=$(python setup.py --name)
echo $MODULE_NAME