KcFnMi KcFnMi - 1 year ago 75
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:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download