我是 GitPython 新手,我正在尝试获取提交中文件的内容。我能够从特定提交中获取每个文件,但每次运行该命令时都会收到错误。现在,我知道该文件存在于 GitPython 中,但每次运行程序时,都会收到以下错误:
returned non-zero exit status 1
我在用Python 2.7.6 and Ubuntu Linux 14.04。
我知道该文件存在,因为我也从命令行直接进入 Git,检查相应的提交,搜索该文件并找到它。我也运行cat
命令,然后显示文件内容。很多时候,当错误出现时,它表示有问题的文件不存在。我试图使用 GitPython 来检查每个提交,从每个单独的提交中获取每个 blob 或文件,并对该文件的内容运行外部 Java 程序。 Java 程序旨在将字符串返回给 Python。为了捕获从 Java 代码返回的字符串,我还使用subprocess.check_output
。任何帮助将不胜感激。
我尝试将命令作为列表传递:
cmd = ['java', '-classpath', '/home/rahkeemg/workspace/CSCI499_Java/bin/:/usr/local/lib/*:', 'java_gram.mainJava','absolute/path/to/file']
subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=False)
我还尝试过将命令作为字符串传递:
subprocess.check_output('java -classpath /home/rahkeemg/workspace/CSCI499_Java/bin/:/usr/local/lib/*: java_gram.mainJava {file}'.format(file=entry.abspath.strip()), shell=True)
是否可以从 GitPython 访问文件的内容?
例如,假设有一个提交并且它有一个文件foo.java该文件中有以下代码行:
foo.java
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class foo{
public static void main(String[] args) throws Exception{}
}
我想访问文件中的所有内容并在其上运行外部程序。
任何帮助将不胜感激。下面是我用来执行此操作的一段代码
#! usr/bin/env python
__author__ = 'rahkeemg'
from git import *
import git, json, subprocess, re
git_dir = '/home/rahkeemg/Documents/GitRepositories/WhereHows'
# make an instance of the repository from specified path
repo = Repo(path=git_dir)
heads = repo.heads # obtain the different repositories
master = heads.master # get the master repository
print master
# get all of the commits on the master branch
commits = list(repo.iter_commits(master))
cmd = ['java', '-classpath', '/home/rahkeemg/workspace/CSCI499_Java/bin/:/usr/local/lib/*:', 'java_gram.mainJava']
# start at the very 1st commit, or start at commit 0
for i in range(len(commits) - 1, 0, -1):
commit = commits[i]
commit_num = len(commits) - 1 - i
print commit_num, ": ", commit.hexsha, '\n', commit.message, '\n'
for entry in commit.tree.traverse():
if re.search(r'\.java', entry.path):
current_file = str(entry.abspath.strip())
# add the current file or blob to the list for the command to run
cmd.append(current_file)
print entry.abspath
try:
# This is the scenario where I pass arguments into command as a string
print subprocess.check_output('java -classpath /home/rahkeemg/workspace/CSCI499_Java/bin/:/usr/local/lib/*: java_gram.mainJava {file}'.format(file=entry.abspath.strip()), shell=True)
# scenario where I pass arguments into command as a list
j_response = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=False)
except subprocess.CalledProcessError as e:
print "Error on file: ", current_file
# Use pop on list to remove the last string, which is the selected file at the moment, to make place for the next file.
cmd.pop()