When I run my code it keeps giving me an error:
File "C:\Users\Joshua Ajogu Alfa\Desktop\merklehashtreebuild1.py", line 36, in inputString = sys.argv[1] IndexError: list index out of range
#!/usr/bin/python
import hashlib,sys
class MerkleTreeNode:
def __init__(self,value):
self.left = None
self.right = None
self.value = value
self.hashValue = hashlib.sha256(value.encode('utf-8')).hexdigest()
def buildTree(leaves,f):
nodes = []
for i in leaves:
nodes.append(MerkleTreeNode(i))
while len(nodes)!=1:
temp = []
for i in range(0,len(nodes),2):
node1 = nodes[i]
if i 1 < len(nodes):
node2 = nodes[i 1]
else:
temp.append(nodes[i])
break
f.write("Left child : " node1.value " | Hash : " node1.hashValue " \n")
f.write("Right child : " node2.value " | Hash : " node2.hashValue " \n")
concatenatedHash = node1.hashValue node2.hashValue
parent = MerkleTreeNode(concatenatedHash)
parent.left = node1
parent.right = node2
f.write("Parent(concatenation of " node1.value " and " node2.value ") : " parent.value " | Hash : " parent.hashValue " \n")
temp.append(parent)
nodes = temp
return nodes[0]
inputString = sys.argv[1]
leavesString = inputString[1:len(inputString)-1]
leaves = leavesString.split(",")
f = open("merkle.tree", "w")
root = buildTree(leaves,f)
f.close()
CodePudding user response:
You can call the program with arguments like this:
python program.py something another
Also I think adding a except block or checking the length of arguments before is better:
try:
inputString = sys.argv[1]
except IndexError:
pass # <- do something if there's no argument
## OR
if len(sys.argv) > 1:
inputString = sys.argv[1]
else:
pass # <- do something
CodePudding user response:
you aren't passing the arguments to the file while starting it, do it in this way:
python C:/path/to/your/python/file.pi arg1 arg2 arg3
to avoid any error consider to do:
try:
inputString = sys.argv[1]
except ValueError:
inputstring = input("please add your input string: ")
# do anything you want if you dislike this
Note: remember that you always have a sys.argv list that contains only the filename [main.py]
CodePudding user response:
sys.argv is set by the command you run (i'll treat windows since it's your situation)
maybe trying to run a small program like this one will help
import sys
print(*sys.argv)
the rule of argv
is that the first argument (sys.arg[0]
) is the name of your program as you writen it in the CLI and the next are strings that contains each arguments you passed so running:
python prog.py 2 arg1 arg2
will set argv at :
["prog.py", "2", "arg1", "arg2"]
normaly a whitespace separate argument but you can use double quote to ignore them.
running:
python prog.py 1 "arg1 arg2"
will set argv at :
["prog.py", "2", "arg1 arg2"]
in your case it look like you are not giving any argument to your program since argv[1]
does not exist.