Pranasas
Pranasas

Reputation: 596

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?

Upvotes: 3

Views: 1718

Answers (2)

anothernode
anothernode

Reputation: 5397

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]

Upvotes: 2

torek
torek

Reputation: 489688

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.

Upvotes: 3

Related Questions