具有退出状态128的子流程调用

问题描述 投票:0回答:2

本质上,我试图使用子流程调用在特定的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", "-")
python git subprocess
2个回答
1
投票

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.

如果您的cd

子过程中]中运行,这将不是

影响当前过程,因此您可能不一定完全在Git存储库中。这肯定可以解释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(固有地是特定于平台的)。
[另一点—使一个子shell命令chdir到达其他目录不会影响后续的单独子shell或子进程命令,而调用os.chdir直接会影响

your

进程和因此会影响其子流程-请注意,这里还有两个附加选项:
  • subprocess函数都接受关键字cwd参数,其默认值为cwd=None。在此处提供字符串会导致Python仅针对该子进程调用将os.chdir进入指定目录。

查看详细信息here

  • Git本身提供了一个标志-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,则升级时间已经很长了:-) )。


  • 0
    投票
    [另一点—使一个子shell命令chdir到达其他目录不会影响后续的单独子shell或子进程命令,而调用os.chdir直接会影响

    your

    © www.soinside.com 2019 - 2024. All rights reserved.