Skip to main content
 首页 » 编程设计

Python 子进程 git checkout 返回错误,即使没有错误

2025年05月04日17kenshinobiy

我正在编写一个脚本来自动执行一些 GIT 任务。我知道 GITPython,但我不想使用它。即使艰难,也可能更容易。

我得到了以下代码:

def executeCommand(cmd): 
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) 
    out, error = p.communicate() 
    if not error: 
        return out.strip() 
    else: 
        print repr(out) 
        print repr(error) 
        print "Stopping execution!\r" 
        exit(0) 

给出命令 ['git', 'checkout', 'master'] 的这段代码确实检查了 master。但是它会停止执行,显然是因为错误变量不为空。我尝试打印以下错误输出:

"Your branch is up-to-date with 'origin/master'.\n" 
"Switched to branch 'master'\n" 
Stopping execution! 

正如你所看到的,它成功地 check out 了 master 分支(也通过 git status 验证)。但是为什么第二行填的是error变量呢?如何处理?或者没有办法正确处理这个问题?还是我不应该做任何错误检查?最好的解决方案/解释是什么?

谢谢!

请您参考如下方法:

这不是错误!它是 stderr 上的输出 :)

如果你在 linux 终端上,你可以通过运行以下命令来测试它

git checkout master 2>/dev/null 
 
# You shouldn't see any output.  
# This is because git is writing those messages to stderr. 

根据 subprocess docs

communicate() returns a tuple (stdoutdata, stderrdata)

即stdout 和 stderr 上的输出。

如果要检查错误,应该使用returncode 属性。

你的情况

stdout, stderr = p.communicate() 
if p.returncode == 0: 
    return stdout.strip() 
 
else: 
    # handle error 
    print repr(stdout) 
    print repr(stderr) 
    print "stopping execution!\r" 
    exit(0)