Python中如何快速获取.gitignore模板


Python中如何快速获取.gitignore模板
17 回复

你需要 pycharm。。


直接上代码,用 requests 库从 GitHub 的 gitignore 仓库拉取就行,这是最全最新的。先装个库:pip install requests

import requests
import json

def fetch_gitignore_templates():
    """
    获取所有可用的 .gitignore 模板列表
    """
    url = "https://api.github.com/repos/github/gitignore/contents"
    try:
        response = requests.get(url)
        response.raise_for_status()
        files = response.json()
        # 过滤出 .gitignore 文件,它们通常以特定语言或环境命名
        templates = [file['name'].replace('.gitignore', '') for file in files if file['name'].endswith('.gitignore')]
        return templates
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return []

def get_gitignore_template(template_name):
    """
    根据模板名称获取具体的 .gitignore 内容
    """
    url = f"https://raw.githubusercontent.com/github/gitignore/main/{template_name}.gitignore"
    try:
        response = requests.get(url)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        print(f"获取模板失败: {e}")
        return None

# 使用示例
if __name__ == "__main__":
    # 1. 查看所有模板
    all_templates = fetch_gitignore_templates()
    print("可用的模板:", all_templates[:10], "...")  # 打印前10个看看

    # 2. 获取 Python 的 .gitignore
    python_template = get_gitignore_template("Python")
    if python_template:
        print("\n--- Python .gitignore 内容 ---")
        print(python_template)
        # 可以保存到文件
        with open('.gitignore', 'w', encoding='utf-8') as f:
            f.write(python_template)

原理:GitHub 官方维护了一个 gitignore 仓库,里面各种语言和环境的模板都有。上面的代码直接调它的 API 和原始文件地址。

更懒的方法:如果你装了 git,其实可以直接用命令行搞定,但既然问 Python,上面这个最直接。

一句话建议:直接用 requests 抓 GitHub 官方仓库,省事又全。

安装失败
win7 py3

readme = f.read()
UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa4 in position 464: illegal multibyte sequence

不限于 python

离线环境也可以使用

windows 平台我还没测试, 能帮忙 fix 一下吗?

个人认为不会有太多离线环境下生成新 gitignore 的需求吧

哈哈, 其实我是懒, 这种固定数据,没必要每次去打开网址获取; 就像翻译, 我也直接用 https://github.com/soimort/translate-shell, 懒得去打开其他工具.

其实吧,gitignore 也不是个经常要获取的东西。

不过这个项目不错,star 了

你需要这个

https://www.gitignore.io/

还带有 Command Line

idea 自动生成.gitignore 模板

还是喜欢自己写,遇到需要 ignore 的内容再加进去

毕竟模板可以让我们少干活

gitlab 等自建平台; 引入.gitignore 模板的目的是规范项目

不喜欢额外加一些用不着的东西。。。保持代码的纯净。。

回到顶部