KcFnMi KcFnMi - 7 days ago 5
Python Question

Pipe git commit hash to file in Python

I'm trying to write to file the commit hash via Python. So I did:

f = open('git.txt', 'w')
f.write(str(subprocess.check_output(['C:/Program Files/Git/bin/git', 'rev-parse', 'HEAD'])))
f.close()


But this wrote the following to file:

b'714548ca074bd6e7c40973375e32413e63a67027\n'


I would like just:

714548ca074bd6e7c40973375e32413e63a67027


How may I do that?

Answer

That's just a byte string. All you need to do is decode it before writing it:

r = subprocess.check_output(['C:/Program Files/Git/bin/git', 'rev-parse', 'HEAD'])
f.write(r.strip().decode())

r.strip() was called to remove the trailing '\n', you can alternatively do r[:-1].decode() if you prefer that.

Also, as @torek notes, it is best to open files using the with statement which automatically closes it for you.

So:

# add .strip().decode() at the end if you want a single line statement.
res = subprocess.check_output(['C:/Program Files/Git/bin/git', 'rev-parse', 'HEAD'])  
with open('git.txt', 'w') as f:
    f.write(res.strip().decode())
Comments