chdir
到达其他目录不会影响后续的单独子shell或子进程命令,而调用os.chdir
直接会影响your
本质上,我试图使用子流程调用在特定的sha哈希处检出git commit。
但是,我一直收到错误subprocess.CalledProcessError: Command '['git', 'checkout', '62bbce43e']' returned non-zero exit status 128.
这是我下面的代码:
with open(filename) as inputfile:
reader = csv.reader(inputfile, delimiter=",")
linecount = 0
for row in reader:
if linecount == 0:
linecount += 1
else:
repo = str(row[0])
sha = str(row[2])
specificfile = str(row[3])
linenum = int(row[4])
cl("cd", repo)
subprocess.check_output(['git', 'checkout', sha])
print("checkout done")
git("checkout", "-")
A subprocess.check_output()
调用实际上返回输出(并且您还可以通过传递stderr
参数来获取错误输出)。您可能想看看它是否使您错误解释发生了什么。
由于您收到异常(意味着调用未完成,因此可能不会返回输出),您应该能够从其中一个异常成员获取输出:
try:
output = subprocess.check_output(['git', 'checkout', sha], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print("Exception on process, rc=", e.returncode, "output=", e.output)
我要做知道的一件事是,如果您实际上不是Git存储库中的某些git
命令往往会返回128。因此,我将用[来查看cl("cd", repo)
行之后的路径:os.system("pwd") # use "cd" for Windows.
如果您的影响当前过程,因此您可能不一定完全在Git存储库中。这肯定可以解释cd
在子过程中]中运行,这将不是
128
返回代码。通过示例,下面的记录显示了当我尝试在存储库之外运行git
命令时发生的情况:>>> try:
... output = subprocess.check_output(['git', 'checkout', '12345'])
... except subprocess.CalledProcessError as e:
... print(e.returncode, e.output)
...
128 b'fatal: not a git repository (or any of the parent directories): .git\n'
如果结果证明您:are
在错误的目录中(即,cl("cd", repo)
语句正在运行子进程来更改目录),则应使用受Python祝福的方法来更改目录( )
import os
os.chdir(path)
这实际上会更改immediate
进程(Python解释器)的目录,而不是临时子进程。
((a)
实际上,这通常是个好建议-尽可能使用特定于Python的东西(因为它大多是跨平台的),而不是生成子shell(固有地是特定于平台的)。chdir
到达其他目录不会影响后续的单独子shell或子进程命令,而调用os.chdir
直接会影响your
subprocess
函数都接受关键字cwd
参数,其默认值为cwd=None
。在此处提供字符串会导致Python仅针对该子进程调用将os.chdir
进入指定目录。查看详细信息here。
-C
,它告诉Git尽早进行自己的chdir
。要像调用git checkout
一样调用cd path/to/repo; git checkout
,请使用git -C path/to/repo checkout
。此标志是Git 1.8.5版中的新功能,因此,如果您的Git早于该版本,您将没有git -C
(但如果您的Git早于2.x,则升级时间已经很长了:-) )。
chdir
到达其他目录不会影响后续的单独子shell或子进程命令,而调用os.chdir
直接会影响your