如何通过GitPython获取推送到GitLab后的远程反馈信息
I've run into this exact issue before—GitPython's high-level push() method gives you push status info, but it doesn't capture those handy remote: lines GitLab sends back (like the MR URL). Here's how to fix it:
The Problem
When you use origin.push() (the Remote object's push method), it returns a list of PushInfo objects that tell you things like if the push succeeded or what refs were updated. But those remote: messages from GitLab are part of the underlying git push command's output—specifically, they get sent to stderr (not stdout), and the high-level method doesn't capture that by default.
The Solution
Instead of using the Remote object's push() method, call the raw git push command via GitPython and capture both stdout and stderr. Then you can parse the stderr output to grab those remote messages.
Here's how to adjust your code:
import git from subprocess import PIPE # Assume `repo` is your initialized GitPython Repo object if repo.is_dirty(): repo.git.add(all=True) repo.git.commit(m="my commit") # Execute git push directly and capture output stdout, stderr = repo.git.push( "origin", branch, o="merge_request.create", stdout=PIPE, stderr=PIPE ) # Decode and parse the stderr output (where GitLab's remote messages live) remote_feedback = stderr.decode("utf-8") # Extract and print all remote: lines print("GitLab Remote Feedback:") for line in remote_feedback.split("\n"): if line.startswith("remote:"): print(line.strip()) # Bonus: Extract the Merge Request URL specifically mr_url = None for line in remote_feedback.split("\n"): stripped_line = line.strip() if stripped_line.startswith("remote: https://") and "merge_requests" in stripped_line: mr_url = stripped_line.replace("remote: ", "") break if mr_url: print(f"\nCreated Merge Request: {mr_url}")
Why This Works
GitLab sends those remote: messages as part of the push response, and the git push command outputs them to stderr. By using stdout=PIPE and stderr=PIPE, we tell GitPython to capture both streams instead of letting them print to the console. We then decode the stderr content and parse it to find the lines we care about.
If you were set on using the high-level Remote.push() method, you'd have to mess with GitPython's logging or hooks, but that's far less straightforward than just capturing the raw command output.
内容的提问来源于stack exchange,提问作者user2854921

