KcFnMi KcFnMi - 8 months ago 52
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'])))

But this wrote the following to file:


I would like just:


How may I do that?

Answer Source

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'])

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.


# 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: