首页 > 解决方案 > Git checkout to a commit id 使用 python 子进程时将输出重定向到 stderr

问题描述

subprocess在 python 中使用模块来签出特定的提交。下面是示例代码。

commit_id = '305efe41dc9e9bfa375781fa2b69dd979dcaa7f1'
process = subprocess.Popen(["git", "checkout", commit_id], stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
out, err = process.communicate()

当我打印out时没有输出,而当我打印时err我看到以下消息 -

b"Note: switching to '305efe41dc9e9bfa375781fa2b69dd979dcaa7f1'.\n\nYou are in 'detached HEAD' state. You can look around, make experimental\nchanges and commit them, and you can discard any commits you make in this\nstate without impacting any branches by switching back to a branch.\n\nIf you want to create a new branch to retain commits you create, you may\ndo so (now or later) by using -c with the switch command. Example:\n\n  git switch -c <new-branch-name>\n\nOr undo this operation with:\n\n  git switch -\n\nTurn off this advice by setting config variable advice.detachedHead to false\n\nHEAD is now at 305efe41 checking out back to current branch after operation complete\n"

而当我执行 a 时,git branch我看到我的 HEAD 已更改为305efe41dc9e9bfa375781fa2b69dd979dcaa7f1.

如果我从这个当前分离的头进一步签出其他提交 ID,它仍然可以工作,但消息是在err而不是out像以前一样。

为什么我在 stderr 而不是 stdout 中收到消息?难道我做错了什么?

我的目标是编写一些干净的代码并避免可能的黑客攻击——

if not err:
    // do something

INSTEAD OF 

if err:
   // do something as the checkout is working but for some reason the out is in err

注意:我知道有一些 git 库可以直接使用,而不是使用 subprocess 手动操作,但由于某种原因我不能使用它们。

标签: pythonpython-3.xgitsubprocess

解决方案


推荐阅读