简体   繁体   中英

Python Always Returning False

I have a script that gets the md5 value for a given file and another script that checks another file for an md5 I precalculated. Calculator:

import sys
import hashlib

BUF_SIZE = 65536

md5 = hashlib.md5()
sha1 = hashlib.sha1()

with open(sys.argv[1], 'rb') as f:
    while True:
        data = f.read(BUF_SIZE)
        if not data:
            break
        md5.update(data)
        sha1.update(data)

print("{0}".format(md5.hexdigest()))

Comparer:

import os
if os.system("python /home/jamesestes/Desktop/hash.py /home/jamesestes/Desktop/Untitled-1.py") == "85e1a2bfe4347c7e380059cc15591164":
    print("OK")
else:
    print("FAILED")

The comparer script always returns False even when the values match.

os.system() does not return the output from the executed command. The return value is the exit code.

If you want to capture the output, then you'd be better off using the subprocess module . (And when you do, make sure that you account for trailing whitespace or newlines in the output.)

(Of course, in this case, since you're executing one Python script from another, you could re-work your code so that you don't need to use os.system() or anything from subprocess at all. If you changed your calculator script to move the code into a function and to return the hash string instead of printing it, then your comparer script should simply import that code and execute that function directly.)

Use os.popen("cmd").read() instead of os.system

import os
if os.popen("python /home/jamesestes/Desktop/hash.py /home/jamesestes/Desktop/Untitled-1.py").read() == "85e1a2bfe4347c7e380059cc15591164":
    print("OK")
else:
    print("FAILED")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM