문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top