0

I'm trying to assign the md5 sum of a file (in ubuntu) to a variable(any) in python script as below

aList=subprocess.check_output(["md5sum",filename])

i want to assign only sum to the variable for that i used below code but it's not working

aList=subprocess.check_output(["md5sum",filename," | awk '{print $1}'"])

please help me to find out solution

thanks in advance

Sanjeev Kumar
  • 13
  • 1
  • 4
  • Doesn't `aList = subprocess.check_output(['md5sum', filename]).decode().partition(' ')[0]` work? – Jon Clements Aug 20 '17 at 12:33
  • Consider https://stackoverflow.com/questions/13332268/python-subprocess-command-with-pipe, which discusses pipes in calls to `subprocess` methods, and also consider using the Python [hashlib](https://docs.python.org/2/library/hashlib.html) library instead of using the `md5sum` command. – larsks Aug 20 '17 at 12:35
  • Thanks Jon Clements, its working. – Sanjeev Kumar Aug 21 '17 at 05:06

1 Answers1

1

Rather than shelling out to perform the md5sum, use Python's inbuilt hashlib.md5 implementation:

import hashlib

with open(filename, 'rb') as f:
    hexdigest = hashlib.md5(f.read()).hexdigest()
    print(hexdigest)
mhawke
  • 84,695
  • 9
  • 117
  • 138