I made a command line in Python. Before I go on and add more commands, is my program made well?
I don't like the huge amount of "if" statements in it. But I don't know a better way to do it. (JSON may be used later this is why I have it included)
Here's the code:
import time
import json
print("Welcome to pyCMD, user\n")
time.sleep(0.2)
input("Press enter to start\n")
time.sleep(0.2)
def SavetoDisk(data, file):
with open(file, 'w') as outfile:
json.dump(data, outfile)
def ReadfromDisk(file):
with open(file) as json_file:
data = json.load(json_file)
return data
print('Starting command line, use "help . ." for help')
running = True
commandList = "add | sub | mult | div | exp | tetrate | python"
while running:
try:
userInput = input(': ')
tokens = userInput.split()
command = tokens[0]
args = [(token) for token in tokens[1:]]
except: print("unknown input error")
try:
arg1, arg2 = args
except ValueError:
print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')
if command == "add":
print(float(arg1) + float(arg2))
if command == "sub":
print(float(arg1) - float(arg2))
if command == "mult":
print(float(arg1) * float(arg2)) #math commands
if command == "div":
print(float(arg1) / float(arg2))
if command == "exp":
print(float(arg1) ** float(arg2))
if command == "tetrate":
for x in range(int(arg2)):
arg1 = float(arg1) * float(arg1)
print(arg1)
if command == "python":
exec(open(arg1).read())
if command == "help":
if arg1 == '.':
if arg2 == '.':
print('To see help about a command, type: "help [command] ." for list of commands type: "help command list"')
if arg1 == 'command':
if arg2 == 'list':
print(commandList)
if arg1 == 'add':
print("Add: \n Description: Adds 2 numbers \n Syntax: add [num1] [num2]")
if arg1 == 'sub':
print("Sub: \nDescription: Subtracts 2 numbers \n Syntax : sub [num1] [num2]")
if arg1 == 'mult':
print("Mult: \nDescription: Multiplies 2 numbers \n Syntax : mult [num1] [num2]")
if arg1 == 'div':
print("Div: \nDescription: Divides 2 numbers \n Syntax : div [num1] [num2]")
if arg1 == 'exp':
print("Exp: \nDescription: Raises 1 number by another \n Syntax : exp [num1] [num2]")
if arg1 == 'tetrate':
print("Tetrate: \nDescription: Tetration \n Syntax : tetrate [num1] [num2]")
if arg1 == 'python':
print("Python: \nDescription: Runs a python script \n Syntax : python [path/to/program.py] .")
.) a feature you desire? Or just a just side effect of original implementation with all commands going through same path? \$\endgroup\$