0

I was trying to write a small program to get the checksums of some files. Using the code mentioned over here, I made this:

import hashlib
import sys
from functools import partial

def md5sum(filename):
    with open(filename, mode='rb') as f:
        d = hashlib.md5()
        for buf in iter(partial(f.read, 128), b''):
            d.update(buf)
    return d.hexdigest()

print(md5sum(sys.argv[0]))

That code works fine. However, when I try adding SHA1 support like so:

import hashlib
import sys
from functools import partial

def md5sum(filename):
    with open(filename, mode='rb') as f:
        d = hashlib.md5()
        for buf in iter(partial(f.read, 128), b''):
            d.update(buf)
    return d.hexdigest()

def sha1sum(filename):
    with open(filename, mode='rb') as f:
        d = hashlib.sha1()
        for buf in iter(partial(f.read, 128), b''):
            d.update(buf)
    return d.hexdigest()

if sys.argv[0] == 'md5':
    print(md5sum(sys.argv[1]))
elif sys.argv[0] == 'sha1':
    print(sha1sum(sys.argv[1]))

it stops printing the output (for both MD5 and SHA1). What am I doing wrong here?

Community
  • 1
  • 1
Nathan2055
  • 2,143
  • 8
  • 24
  • 48
  • Try putting `print(sys.argv[0])` just before the `if` test at the end; you may not be getting the system argument you think you are (or maybe you should be using `sys.argv[1]` instead). – Hugh Bothwell Mar 18 '14 at 19:06
  • I've always preferred to use `optparse` for command line arguments, just my opinion. That way you don't have to bother with all the indexing. – anon582847382 Mar 18 '14 at 19:11

1 Answers1

3

sys.argv[0] is the name of the script; command line arguments are stored in sys.argv[1:]. You probably wanted to test sys.argv[1] instead:

if sys.argv[1] == 'md5':
    print(md5sum(sys.argv[2]))
elif sys.argv[1] == 'sha1':
    print(sha1sum(sys.argv[2]))

Note that your original 'working' version only ever calculated the MD5 hash of the script itself.

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997