【问题标题】:Is there a way to handle ignorefiles (like .gitignore) in python?有没有办法在 python 中处理忽略文件(如 .gitignore)?
【发布时间】:2020-06-30 18:20:29
【问题描述】:

我想编写一个忽略文件和目录的应用程序,例如 git 正在使用其 .gitignore 文件执行此操作。目标是以下。我的应用程序称为“MyFancyApp”。如果我像这样运行 cli:“MyFancyApp build”,应用程序会在当前目录上运行并收集所有文件并将其放入 Zip 文件中。但我想排除我在 .MyFancyAppIgnore 文件中引用的文件和目录。代码是用 Python 编写的

【问题讨论】:

  • 到目前为止你尝试过什么?请参阅how to ask,了解如何编写一个您可能会得到帮助的好问题。
  • 您必须自己构建它。您可以从文件中读取文件列表,将它们存储在列表中,当您到达要排除的部分时,检查文件名是否在列表中。 .gitignore 的存在是为了在推送到源存储库时忽略文件。
  • 注意这个应用已经存在:tar -zxvf my_archive.tgz --exclude-from=my_ignore_file.txt the_directory
  • ...或git-archive

标签: python git ignore


【解决方案1】:

你可以使用python库GitPython来检查git是否会通过ignored方法忽略文件​​。这给定一个文件路径列表将检查 git 是否会忽略它们返回那些将是的。可以使用python -mpip install GitPython 安装它,然后在您的代码中:

import git

flist = [ # list of the files given by glob.glob or otherwise
]
repo = git.Repo(start_dir, search_parent_directories=True)
ignored = repo.ignored(flist)
flist = [f for f in flist if not f in ignored] # Filter the flist
repo.close()
# In your zipping function use the modified flist

注意

我发现在调用repo.ignored 时必须使用绝对路径,因此您可能需要使用pathlib

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2020-05-03
    • 2020-07-02
    • 2016-12-27
    相关资源
    最近更新 更多