Search code examples
pythongitsubprocessgitpython

getting last git commit date via passing git command to subprocess in python


I have a script in which I just need to retrieve the date in the format 2015-07-28 of the last git commit.

but using git log -1 --pretty=format:"%ci" in terminal if I get Tue Jul 28 16:23:24 2015 +0530 then if I am trying to

pass this as string to subprocess.Popen like

subprocess.Popen('git log -1 --pretty=format:"%cd"' shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE))

but this throws me error TypeError: %c requires int or char which I guess python things we are passing a char to %c while that was for getting date using git command.

I need this date to be concatenated to a string a my python script.


Solution

  • The error message does not correspond to your code: the code in question would produce SyntaxError, not TypeError.

    You don't need shell=True. To get git's output, you could use subprocess.check_output() function:

    from subprocess import check_output
    
    date_string = check_output('git log -1 --pretty=format:"%ci"'.split()).decode()