Search code examples
pythonchecksum

Im not sure how to take filename out of sha256 checksum in Python 3


I'm still a Python noob but figured that instead of checking a checksum manually, I would make a quick program so it would take less time whenever I had to do it(also as practice) so I wrote this(excuse the extra useless lines and bad naming in my code, I was trying to pinpoint what I was doing wrong.)

import subprocess

FileLocation = input("Enter File Location: ")

Garbage1 = str(input("Enter First Checksum: "))

Garbage2 = str(subprocess.call(['sha256sum', FileLocation]))

Garbage3 = Garbage2.split(None, 1)

if Garbage1 == Garbage3[0]:
    print("all good")
else:
    print("Still Not Working!!!")

When I run this code it keeps on leaving the filepath at the end of the second checksum because of the Linux command, but I tried getting rid of it various ways with .split() but when I ran the code, it was still there, I also tried to add the file path to the end of the first checksum as a test, but that also won't add the filepath to the end of it. I do know for a fact that the checksums match

Any idea whats wrong any help would be appreciated.


Solution

  • From the docs, subprocess.call does: Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute. You can verify this in the python shell by entering help(subprocess.call) or looking at https://docs.python.org and searching for the subprocess module.

    Your code converts the integer return code to a string, not the checksum. There are other calls in subprocess that capture the process stdout, which is where sha256sum sends its checksum. Stdout is a bytes object that needs to be decoded to a string.

    import subprocess
    
    FileLocation = input("Enter File Location: ")
    
    Garbage1 = str(input("Enter First Checksum: "))
    
    Garbage2 = subprocess.check_output(['sha256sum', FileLocation]).decode()
    
    Garbage3 = Garbage2.split(None, 1)
    
    if Garbage1 == Garbage3[0]:
        print("all good")
    else:
        print("Still Not Working!!!")