Python script: get latest tag info from remote Git repository?

Question:

I have found a way to get the info on the latest Git tag from the remote repository:

git ls-remote --tags --refs --sort="version:refname" git://github.com/git/git.git | awk -F/ 'END{print$NF}'

This works fine from the command line.

How would I get this info from the python script?

I tried os.system(command), but it doesn’t seem like a good choice?

Asked By: Danijel

||

Answers:

You can use subprocess.check_output and do what your awk incantation does in Python (namely print the last line’s last /-separated segment).

Using the list form of arguments for subprocess.check_output ensures you don’t need to think about shell escaping (in fact, the shell isn’t even involved).

import subprocess

repo_url = "https://github.com/git/git.git"
output_lines = subprocess.check_output(
    [
        "git",
        "ls-remote",
        "--tags",
        "--refs",
        "--sort=version:refname",
        repo_url,
    ],
    encoding="utf-8",
).splitlines()
last_line_ref = output_lines[-1].rpartition("/")[-1]
print(last_line_ref)
Answered By: AKX
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.