You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python CLI应用设置自定义命令别名并适配Windows、Linux系统以发布至PyPI

把Python CLI脚本转为跨平台独立命令并发布到PyPI

好的,我来帮你搞定这个需求——把你的Python CLI脚本变成像git、angular那样的独立命令,还能跨Windows和Linux,顺利发布到PyPI。下面是一步步的具体操作:

步骤1:整理项目结构

首先把你的项目调整成标准Python包结构,方便后续打包发布:

your-project/
├── pyproject.toml  # 现代Python项目的核心配置文件
├── src/
│   └── rexona/
│       ├── __init__.py
│       └── cli.py  # 把原来的test.py代码移到这里

注:把原test.py重命名为cli.py并放到src/rexona目录下,这是Python包的规范结构,能避免命名冲突。

步骤2:配置控制台脚本入口

在pyproject.toml里添加配置,指定你的自定义命令名称(比如rexona)和对应的执行函数:

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "rexona-cli"  # 你的PyPI包名,必须唯一
version = "0.1.0"
authors = [
  { name="Your Name", email="your@email.com" }
]
description = "A CLI tool for processing CSV files"
readme = "README.md"
requires-python = ">=3.7"

[project.scripts]
rexona = "rexona.cli:main"

这里的rexona = "rexona.cli:main"意思是:用户输入rexona命令时,会自动执行rexona.cli模块里的main()函数。

步骤3:调整你的CLI代码

确保cli.py(原test.py)里有一个main()函数作为命令入口,比如用argparse处理参数的示例:

import argparse
import csv

def main():
    parser = argparse.ArgumentParser(description='Process CSV files with custom options.')
    parser.add_argument('filepath', help='Path to the target CSV file')
    parser.add_argument('-v', '--verbose', action='store_true', help='Enable detailed output')
    parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all non-essential output')
    parser.add_argument('-o', '--output', help='Specify output directory or file path')
    
    args = parser.parse_args()
    
    # 你的业务逻辑代码
    if args.verbose:
        print(f"Starting processing for file: {args.filepath}")
    
    # 示例:读取CSV内容
    with open(args.filepath, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        # 这里写你的处理逻辑...
    
    if args.output:
        print(f"Output will be saved to: {args.output}")

if __name__ == '__main__':
    main()

步骤4:本地测试安装

在项目根目录运行以下命令,以开发模式安装你的包(修改代码后即时生效):

pip install -e .

安装完成后,你就能直接在终端/命令提示符里用rexona命令了:

# Linux/macOS
rexona data.csv -o ./output

# Windows
rexona data.csv -o .\output
  • Linux/macOS:rexona会被安装到~/.local/bin(用户级安装)或/usr/local/bin(系统级安装),这些目录默认在PATH里,直接就能用。
  • Windows:会生成rexona.cmd文件,放在Python的Scripts目录(比如C:\Users\你的用户名\AppData\Local\Programs\Python\PythonXX\Scripts),如果这个目录不在系统PATH里,手动添加一下就行。

步骤5:打包并发布到PyPI

  1. 先安装打包和上传工具:
pip install build twine
  1. 生成发布包:
python -m build

这会在dist/目录下生成两个文件:.tar.gz(源码包)和.whl(wheel包,安装更快)。
3. 上传到PyPI:

twine upload dist/*

按照提示输入你的PyPI账号密码,就能完成发布了。

验证发布效果

其他用户安装你的包后,直接就能用rexona命令:

pip install rexona-cli
rexona data.csv -v

内容的提问来源于stack exchange,提问作者Omar Jarkas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:37:29