【问题标题】:How to run Python powered CLI like a normal system CLI?如何像普通系统 CLI 一样运行 Python 驱动的 CLI?
【发布时间】:2020-09-27 03:43:11
【问题描述】:

我想像其他 cli 工具一样运行我构建的 CLI,例如,kubectlredis 等。目前,我运行我的 cli:python3 cli.py subarg --args;相反,我想运行:invdb subarg --args 其中 invdb 是 Python 包。

项目仓库的结构是:

.
├── CHALLENGE.md
├── Pipfile
├── Pipfile.lock
├── README.md
├── __pycache__
│   └── config.cpython-38.pyc
├── data_platform_challenge_darwin
├── data_platform_challenge_linux
├── data_platform_challenge_windows
├── discussion_answers_rough_work
├── dist
│   ├── invdb-0.0.1.tar.gz
│   └── invdb-tesla-kebab-mai-haddi-0.0.1.tar.gz
├── example.json
├── invdb
│   ├── __init__.py
│   ├── analysis.py
│   ├── cleanup.py
│   ├── cli.py
│   ├── config.py
│   ├── etl.py
│   ├── groups.py
│   ├── initialize_db.py
│   └── nodes.py
├── invdb.egg-info
│   ├── PKG-INFO
│   ├── SOURCES.txt
│   ├── dependency_links.txt
│   └── top_level.txt
├── setup.py
├── test.db
└── tests

【问题讨论】:

  • Python 是一种解释性语言,你说的是在 PATH 上有一个可执行文件。有很多方法可以做到这一点(主要是通过 setuptools 的入口点垫片)。以the v1 aws cli 为例。
  • >Python 是一种解释性语言,您说的是在 PATH 上有一个可执行文件。即使有办法,我要求拥有的东西是好事还是python3 cli.py ... 是更好的方法?
  • 我写了一个应该有帮助的答案。优点是使用方便。缺点是必须安装。我在我的公司制作了一个复杂的 Python 包供内部使用,它使用了这个 entry_point shim 技术,但是它需要一些基础设施才能变得有用(我们必须建立一个 PyPI 服务器,连接 CI/CD,教所有开发人员机器如何找到内部 PyPI,说服开发人员执行pip install,而不仅仅是从源代码同步和运行等...)。这并不是说这些缺点是必要的,只是它们是可能的。

标签: python python-3.x command-line-interface


【解决方案1】:

setuptools(或者是 distutils?这条线太模糊了)提供了一个 entry_points.console_scripts 选项,可以在安装包时为您执行此操作。我将在摘要的底部提供一个示例存储库。

像这样构造一个项目树:

# /mypackage/mymodule.py
print("We did it!")
# /pyproject.toml
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
# this is required for Python to recognize setuptools as the build backend
[metadata]
name = sample_module
version = 0.0.1
author = Adam Smith
description = console_script example

[bdist_wheel]
universal = true

[options]
packages = my_package
python_requires = >=2.7
entry_points = 
    [console_scripts]
    sample_module = my_package.my_module:main

然后在 shell 中运行以下命令:

$ python3 -mpip install .
(ed. this will install the file locally. To build a wheel (to install elsewhere) try pep517)

如果您收到有关安装脚本不在您的 PATH 上的警告,您应该考虑添加它。否则,只需运行您的新脚本

$ sample_module
We did it!

GitLab:nottheeconomist/console_script_example


由于您已经有了 setup.py,请考虑将以下条目添加到您的 setuptools.setup 调用中:

# ...

setuptools.setup(
    # ...
    entry_points = {
        'console_scripts': ['sample_module=my_package.my_module:main']
    }
)

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 2021-06-27
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    相关资源
    最近更新 更多