Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly parse a Git command (`git log ...`) in Python?

Using a Python script, I'd like to get the email of a person who last committed changes to a specific file /path/to/file.py.

Sounds easy, right? I just need to somehow parse the following

git log -n 1 --pretty=format:%ae -- /path/to/file.py

Package sh is my preferred choice. Unfortunately, in Python

import sh
print(str(sh.git.log('-n 1 --pretty=format:%ae -- /path/to/file.py')))
print(str(sh.git.log('-n', '1', '--pretty=format:%ae', '--', /path/to/file.py')))

both print - (press RETURN). So maybe I'm messing something up with the arguments.

Otherwise, str(sh.git.status()) correctly returns On branch master ..., and some other tested commands work as expected.

How to solve this?

like image 900
Pranasas Avatar asked Jul 03 '26 20:07

Pranasas


2 Answers

The - (press RETURN) output sounds like it's something printed by a pager.

Remember, every Git command may (depending on options, arguments, configuration settings, and other environmental details such as whether stdin is a tty) run its output through a pager. The pager used depends on your personal configuration. How that pager acts depends on the pager used and on the input data.

One simple workaround is to run git --no-pager <git-command> to tell Git not to use a pager, even if the configuration and environment suggest that Git should use a pager.

like image 81
torek Avatar answered Jul 06 '26 17:07

torek


This should work:

print(str(sh.git.log("-n 1", "--pretty=format:%ae", "/path/to/file")))

At least this shows how it works on my machine:

$ git log -n 1 --pretty=format:%ae -- README.md
[email protected]
$ python3
Python 3.6.4 (default, Jan 25 2018, 15:54:40)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sh
>>> print(str(sh.git.log("-n 1", "--pretty=format:%ae", "README.md")))
[email protected]
like image 28
anothernode Avatar answered Jul 06 '26 17:07

anothernode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!