假设我在本地文件系统中有一个 git 存储库的路径:path_to_my_repository
,以及存储库中一个文件的路径path_to_file
。
对于给定的日期列表,如何从 Python获取特定分支上文件的相应版本(即将文件加载到内存中)。
这个 shell 命令应该做你想做的事:
git show "<branch>@{<timestamp>}:<path/to/file>"
例如:
git show "master@{yesterday}:some/file/in/repo"
git show "master@{2014-01-01 00:00:00}:another/file"
这打印到STDOUT
.
要从任意目录运行它,您可以使用该-C
选项指向您的存储库根目录:
git -C path_to_my_repository show "master@{2014-05-05 12:00:00}:path_to_file"
您可以使用这样的subprocess
模块 或类似的模块从 Python 运行它:
from subprocess import Popen, PIPE
p = Popen(['git', '-C', path_to_my_repository, 'show',
'master@{' + date_string + '}:' + path_to_file],
stdin=PIPE, stdout=PIPE, stderr=PIPE)
# Content will be in `output`
output, err = p.communicate()
或使用任何其他方法调用 shell 命令。您还应该能够使用 libgit2或许多其他工具。