def diff_run(args): if (args == ""): utils.ErrorPrint("diff: No arguments provided\n") return file1, i = PatternGet(args) args = RemovePrecedingSpaces(args[i:]) if (args == ""): utils.ErrorPrint("diff: 2nd argument missing\n") return file2, i = PatternGet(args) if not Path(file1).exists(): utils.ErrorPrint("diff: {0}: no such file or directory\n".format(file1)) return if not Path(file2).exists(): utils.ErrorPrint("diff: {0}: no such file or directory\n".format(file2)) return if (os.path.isdir(file1)): print("{0}: Is a directory\n".format(file1)) return if (os.path.isdir(file2)): print("{0}: Is a directory\n".format(file2)) return with open(file1, 'r') as f1: with open(file2, 'r') as f2: diff = difflib.unified_diff(f1.readlines(), f2.readlines()) for line in diff: print(line, end = "")
def Login(): if (len(Admin.admin_dict) == 0): utils.ErrorPrint( "No record of admins... please register a few!!\n") return id = utils.IntegerInputGet("Enter admin id: ") if id not in Admin.admin_dict: utils.ErrorPrint( "Admin ID: {0} doesn't exist!!... please try again\n".format( id)) return pswd = utils.PasswdInputMatch("Enter password: "******"\n>> {0} <<\n".format(Admin.option_menu[x])) Admin.option_functions[x]()
def DelProducts(): while True: id = utils.IntegerInputGet("Enter product id to be deleted: ") print("") if id not in Products.products_dict: utils.ErrorPrint( "Product ID: {0} doesn't exist!!\n".format(id)) else: Products.HeadingPrint() print(Products.products_dict[id]) print("") r = utils.YesNoGet("Delete this product") if (r == "y"): del Products.products_dict[id] with open("products.file", "wb") as products_file: pickle.dump(Products.products_dict, products_file) utils.SuccessPrint( "Product ID: {0} deleted!!\n".format(id)) else: utils.ErrorPrint( "Product ID: {0} not deleted!!\n".format(id)) r = utils.YesNoGet("\nDelete another product") if r != "y": break
def Login(): if (len(Customer.customer_dict) == 0): utils.ErrorPrint("No record of customers... please register!!\n") return id = utils.IntegerInputGet("Enter customer id: ") if id not in Customer.customer_dict: utils.ErrorPrint( "Customer ID: {0} doesn't exist!!... please try again\n". format(id)) return current_customer = Customer.customer_dict[id] if ((current_customer.passwd != "None") and (False == utils.PasswdInputMatch( "Enter password: "******"\n>> {0} <<\n".format(Customer.option_menu[x])) current_customer.option_functions[x]()
def Register(): admin_num = len(Admin.admin_dict) if (admin_num == MAX_ADMIN_COUNT): utils.ErrorPrint("\nMax number of admins already created!!\n") return while (True): id = utils.IntegerInputGet("Enter Admin id: ") if id in Admin.admin_dict: utils.ErrorPrint( "Admin ID: {0} already exist!!... please try again\n". format(id)) continue name = input("Enter admin name: ") pswd = utils.NewPasswdGet("Enter password: "******"admins.file", "wb") as admins_file: pickle.dump(Admin.admin_dict, admins_file) utils.SuccessPrint( "Admin ID: {0} successfully registered!!\n".format(id)) break
def tail_run(args): if (args == ""): utils.ErrorPrint("Error: No arguments provided!!\n") return lines_reqd = 10 filename = args i = 0 if args[0] == '-': if args[1] != 'n': utils.ErrorPrint("tail: {0}: flag not supported\n".format(args[0:2])) return i = 2 while (args[i] == ' '): i += 1 j = i while ('0' <= args[j] and args[j] <= '9'): j += 1 try: lines_reqd = (int)(args[i:j]) filename = args[j+1:] except Exception as err: utils.ErrorPrint("tail: Invalid args: {0}\n".format(args)) utils.ErrorPrint("tail: {0}\n".format(err)) return try: with open(filename, 'r') as f: BLOCK_SIZE = 4096 f.seek(0, os.SEEK_END) unprocessed_bytes = f.tell() lines_remaining = lines_reqd block_number = -1 blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting # from the end of the file while lines_remaining > 0 and unprocessed_bytes > 0: if (unprocessed_bytes > BLOCK_SIZE): unprocessed_bytes -= BLOCK_SIZE f.seek(unprocessed_bytes) blocks.append(f.read(BLOCK_SIZE)) else: unprocessed_bytes -= BLOCK_SIZE f.seek(0, FILE_BEG) blocks.append(f.read(unprocessed_bytes)) lines_found = blocks[-1].count('\n') lines_remaining -= lines_found unprocessed_bytes -= BLOCK_SIZE block_number -= 1 processed_text = ''.join(reversed(blocks)) print ('\n'.join(processed_text.splitlines()[-lines_reqd:])) except Exception as err: utils.ErrorPrint("tail: {0}: {1}\n".format(filename, err))
def cat_run(args): if (args == ""): utils.ErrorPrint("cat: No arguments provided\n") return i = 0 filename = "" to_stdout = False if (args[i] == '\''): # filename is enclosed in single quotes ('<text>') i += 1 while(args[i] != '\'' or args[i-1] == '\\'): # the text may contain ' in itself if(args[i] != '\\'): filename += str(args[i]) i += 1 i += 1 else: while(i < len(args) and args[i] != ' '): filename += str(args[i]) i += 1 while (i < len(args) and args[i] != '|'): i += 1 if (i == len(args)): to_stdout = True else: i += 1 cmd, args = CommandExtract(args[i:]) if not Path(filename).exists(): utils.ErrorPrint("{0}: no such file or directory\n".format(filename)) return if (os.path.isdir(filename)): print("{0}: Is a directory\n".format(filename)) return try: with open(filename, 'r') as f: for line in f: if(to_stdout): print (line, end="") elif (cmd == "tr"): tr_run(line, args) elif (cmd == "sed"): sed_run_on_line(line, args) else: utils.ErrorPrint("cat: Invalid command\n") break except Exception as err: utils.ErrorPrint("{0}\n".format(err))
def sed_run_on_line(line, args): sed_args = "" i = 0 if (args[i] == '\''): # filename is enclosed in single quotes ('<text>') i += 1 while(i < len(args) and (args[i] != '\'' or args[i-1] == '\\')): # the text may contain ' in itself if(args[i] != '\\'): sed_args += str(args[i]) i += 1 i += 1 args_list = sed_args.split('/'); if (args_list[0] != "s"): utils.ErroPrint("sed: {0}: command not supported\n".format(args_list[0])) return n = len(args_list) if (n == 4 and (args_list[3] == "1" or args_list[3] == "")): line = re.sub(r"{0}".format(args_list[1]), r"{0}".format(args_list[2]), line, 1) elif (n == 4 and args_list[3] == "g"): line = re.sub(r"{0}".format(args_list[1]), r"{0}".format(args_list[2]), line) else: utils.ErrorPrint("sed: command not supported\n") return False print (line, end="") return True
def AddProducts(): while True: id = utils.IntegerInputGet("Enter product id: ") if id in Products.products_dict: utils.ErrorPrint( "Product ID: {0} already exists!!... try again.\n".format( id)) continue new_product = Products(id) Products.HeadingPrint() print(new_product) new_product.Modify() with open("products.file", "wb") as products_file: pickle.dump(Products.products_dict, products_file) utils.SuccessPrint( "Product ID: {0} successfully added!!\n\n".format(id)) r = utils.YesNoGet("Add another product") if r != "y": break
def ViewProducts(): utils.screen_clear() if len(Products.products_dict) == 0: utils.ErrorPrint("No products available... Please add some!!\n") return utils.BoldPrint("\nAvailable Products:\n") Products.HeadingPrint() for p in Products.products_dict: print(Products.products_dict[p])
def DeleteFromCart(self): if self.cart.IsEmpty() == True: utils.ErrorPrint("Cart is Empty!!\n") return while True: id = utils.IntegerInputGet("Enter product id: ") if id not in Products.products_dict: utils.ErrorPrint( "Product ID: {0} doesn't exist!!\n".format(id)) else: if True == self.cart.DeleteProduct(id): with open("customer.file", "wb") as customer_file: pickle.dump(Customer.customer_dict, customer_file) r = utils.YesNoGet("\nDelete another product from cart") if r != "y": break
def echo_run(args): if (args == ""): utils.ErrorPrint("echo: No arguments provided\n") return text = "" i = 0 if (args[i] == '\''): # text is enclosed in single quotes ('<text>') i += 1 while(args[i] != '\'' or args[i-1] == '\\'): # the text may contain ' in itself if(args[i] != '\\'): text += str(args[i]) i += 1 i += 1 else: while(i < len(args) and args[i] != '|'): text += str(args[i]) i += 1 text_list = text.split() text = ' '.join(text_list) while (i < len(args) and args[i] != '|'): i += 1 if (i == len(args)): print (text) else: i += 1 cmd, args = CommandExtract(args[i:]) if (cmd == "tr"): tr_run (text, args) elif (cmd == "sed"): sed_run_on_line (text, args) else: utils.ErrorPrint("echo: invalid command\n") return
def head_run(args): if (args == ""): utils.ErrorPrint("Error: No arguments provided!!\n") return lines_reqd = 10 filename = args i = 0 if args[0] == '-': if args[1] != 'n': utils.ErrorPrint("tail: {0}: flag not supported\n".format(args[0:2])) return i = 2 while (args[i] == ' '): i += 1 j = i while ('0' <= args[j] and args[j] <= '9'): j += 1 try: lines_reqd = (int)(args[i:j]) filename = args[j+1:] except Exception as err: utils.ErrorPrint("tail: Invalid args: {0}\n".format(args)) utils.ErrorPrint("tail: {0}\n".format(err)) return try: with open(filename, 'r') as f: try: while (lines_reqd > 0): line = next(f) print (line, end="") lines_reqd -= 1 except StopIteration: pass except Exception as err: utils.ErrorPrint("tail: {0}: {1}\n".format(filename, err))
def sed_run(args): sed_args_list = args.split('\'') if (len(sed_args_list) < 3): utils.ErrorPrint("sed: invalid command\n") return filename = RemovePrecedingSpaces(sed_args_list[2]) cat_args = "{0} | sed '{1}'".format(filename, sed_args_list[1]) cat_run(cat_args)
def grep_dir_iterative(pattern, dirpath, flag_n): try: dir_content = os.listdir(dirpath) for c in sorted(dir_content): if c[0] != '.': dest_path = "{0}/{1}".format(dirpath, c); if (os.path.isdir(dest_path)): print("grep: {0}: Is a directory".format(dest_path)) else: grep_file(pattern, dest_path, flag_n, True) except Exception as err: utils.ErrorPrint("grep: {0}\n".format(err))
def ProductsBoughtPrint(self): if len(self.products_bought_dict) == 0: utils.ErrorPrint("No Products Bought yet!!\n") return utils.ColorTextPrint(utils.BLUE, "\nProducts Bought:\n") Products.HeadingPrint(True) utils.BoldPrint("{0:^15}|\n".format("Quantity")) for prod_id in sorted(self.products_bought_dict): print(Products.products_dict[prod_id], end="") print("\033[1;{0}m{1:^15}|\033[0m".format( utils.PURPLE, self.products_bought_dict[prod_id]))
def touch_run(args): if (args == ""): utils.ErrorPrint("touch: missing file operand\n") return if (args[0] == '~'): args = TildeToHomeConvert(args) # check whether the parent directories exist or not p = (str)(Path(args).absolute()) basedir, f = os.path.split(p) if not Path(basedir).exists(): utils.ErrorPrint("touch: cannot touch '{0}': no such file or directory!!\n".format(args)) return # check whether the file/directory exists or not if Path(args).exists(): os.utime(args, None) else: with open(args, 'a'): # new file is created os.utime(args, None)
def tr_run(line, args): args_list = args.split() intab = "" # in table outtab = "" # out table if (len(args_list) < 2): utils.ErrorPrint("tr: arguments missing\n") return if (args_list[0][0] == '-'): # a flag if (args_list[0][1] != 'd'): utils.ErrorPrint("tr: {0}: flag not supported".format(args_list[0][0:2])) return intab = char_set_get(args_list[1]) line = line.translate(str.maketrans('', '', intab)) else: intab = char_set_get(args_list[0]) outtab = char_set_get(args_list[1]) line = line.translate(str.maketrans(intab, outtab)) print (line, end="")
def MakePayment(self): if self.cart.IsEmpty() == True: utils.ErrorPrint("Cart is Empty!!\n") return if self.payment.MakePayment() == False: utils.ErrorPrint("Payment Failed... please try again!!\n") else: for p in self.cart.products_quantity_dict: if p in self.products_bought_dict: self.products_bought_dict[ p] += self.cart.products_quantity_dict[p] else: self.products_bought_dict[ p] = self.cart.products_quantity_dict[p] self.cart.Clear() with open("customer.file", "wb") as customer_file: pickle.dump(Customer.customer_dict, customer_file) utils.SuccessPrint( "Payment Confirmation... Thanks for Shopping with us!!\n")
def DeleteProduct(self, prod_id): if prod_id not in self.products_quantity_dict: utils.ErrorPrint( "Product ID {0} doesn't exist in your cart!!\n".format( prod_id)) return False product = Products.products_dict[prod_id] r = utils.YesNoGet("Delete the product completely") if (r != "y"): curr_quantity = self.products_quantity_dict[prod_id] utils.BoldPrint("Current Quantity: {0}\n".format(curr_quantity)) new_quantity = utils.IntegerInputGet("Decrease the Quantity to: ") if (new_quantity > curr_quantity): utils.ErrorPrint( "Use \"Add to Cart\" option to increase the quantity\n") return False if (new_quantity == curr_quantity): return False if (new_quantity != 0): self.products_quantity_dict[prod_id] = new_quantity self.total_price -= curr_quantity * product.price self.total_price += new_quantity * product.price self.Print() return True self.total_price -= self.products_quantity_dict[prod_id] * product.price del self.products_quantity_dict[prod_id] utils.SuccessPrint( "Product ID {0} deleted from your cart!!".format(prod_id)) self.Print() return True
def ls_run(args): if (args == ""): args = os.getcwd() elif (args[0] == '~'): args = TildeToHomeConvert(args) try: if not Path(args).exists(): utils.ErrorPrint("ls: cannot access {0}: no such file or directory".format(args)) return if (os.path.isfile(args)): print (args) return dir_content = os.listdir(args) for c in sorted(dir_content): if c[0] != '.': if (os.path.isdir("{0}/{1}".format(args, c))): utils.ColorTextPrint(utils.BLUE, "{0}\n".format(c), True) else: print (c) except Exception as err: utils.ErrorPrint("ls: {0}\n".format(err))
def MakePayment(self): if self.ViewPaymentOptions() == False: return False index = utils.IntegerInputGet("\nSelect A Card: ") if index == 0: return False while (index < 0 or index > len(self.card_number_list)): utils.ErrorPrint("Invalid Input... please try again!!\n") index = utils.IntegerInputGet("Select A Card: ") if index == 0: return False return True
def AddToCart(self): while True: id = utils.IntegerInputGet("Enter product id: ") if id not in Products.products_dict: utils.ErrorPrint( "Product ID: {0} doesn't exist!!\n".format(id)) else: if True == self.cart.AddProduct(id): with open("customer.file", "wb") as customer_file: pickle.dump(Customer.customer_dict, customer_file) r = utils.YesNoGet("\nAdd another product to cart") if r != "y": break
def Print(self): if len(self.products_quantity_dict) == 0: utils.ErrorPrint("Your Cart is Empty!!\n") return utils.ColorTextPrint(utils.BLUE, "\nYour Cart:\n") Products.HeadingPrint(True) utils.BoldPrint("{0:^15}|\n".format("Quantity")) for prod_id in sorted(self.products_quantity_dict): print(Products.products_dict[prod_id], end="") print("\033[1;{0}m{1:^15}|\033[0m".format( utils.PURPLE, self.products_quantity_dict[prod_id])) utils.BoldPrint("\nTotal Amount: Rs. {0:.2f}\n".format( self.total_price))
def Register(): if Guest.guest_number in Customer.customer_dict: utils.ErrorPrint("Guest ID {0} is already registered!!\n".format( Guest.guest_number)) return new_customer = Customer(Guest.guest_number) print(new_customer) new_customer.Modify() with open("customer.file", "wb") as customer_file: pickle.dump(Customer.customer_dict, customer_file) utils.SuccessPrint("Customer ID: {0} successfully added!!\n\n".format( new_customer.id))
def ViewPaymentOptions(self): if len(self.card_number_list) == 0: utils.ErrorPrint("Please add a Debit/Credit Card!!\n") return False utils.BoldPrint("\n|{0:^15}|{1:^20}|{2:^15}|\n".format( "S. No.", "Card Number", "Card Type")) num_list = self.card_number_list type_list = self.card_type_list for i in range(len(num_list)): utils.ColorTextPrint( utils.PURPLE, "|{0:^15}|{1:^20}|{2:^15}|\n".format(i + 1, num_list[i], type_list[i])) return True
def ModifyProducts(): while True: id = utils.IntegerInputGet("Enter product id to be modified: ") print("") if id not in Products.products_dict: utils.ErrorPrint( "Product ID: {0} doesn't exist!!\n".format(id)) else: Products.HeadingPrint() print(Products.products_dict[id]) Products.products_dict[id].Modify() with open("products.file", "wb") as products_file: pickle.dump(Products.products_dict, products_file) r = utils.YesNoGet("\nModify another product") if r != "y": break
def cd_run(args, prev_dir, curr_dir): if (args == ""): # handling empty argument to "cd" command args = str(Path.home()) elif (args[0] == '~'): # handling "~/" args = TildeToHomeConvert(args) elif (args[0] == '-'): # handling '-' if prev_dir != "": args = prev_dir print (prev_dir) else: args = curr_dir try: os.chdir(args) except Exception as err: utils.ErrorPrint("cd: {0}\n".format(err)) return FAILURE return SUCCESS
def grep_file(pattern, filepath, flag_n, print_path = False): try: with open(filepath, 'r') as search_file: i = 0 for line in search_file: i += 1 match = re.findall(r"{0}".format(pattern), line) if match: if print_path: if flag_n: print ("{0}:{1}:{2}".format(filepath, i, line), end="") else: print ("{0}:{1}".format(filepath, i), end="") else: if flag_n: print ("{0}:{1}".format(i, line), end="") else: print ("{0}".format(line), end="") except Exception as err: utils.ErrorPrint("grep: {0}: {1}\n".format(filepath, err))
def grep_run(args): flag_n = False pattern_found = False pattern = "" search_dest = "" i = 0 while (i < len(args)): if(args[i] == '-'): i += 1 if args[i] != 'n': utils.ErrorPrint("tail: {0}: flag not supported\n".format(args[i:i+2])) return flag_n = True i += 1 # get to next character elif(args[i] == ' '): # ignore spaces i += 1 elif (not pattern_found): pattern_found = True if (args[i] == '\''): # pattern is enclosed in single quotes ('<pattern>') i += 1 while(args[i] != '\'' or args[i-1] == '\\'): # the pattern may contain ' in itself if(args[i] != '\\'): pattern += str(args[i]) i += 1 i += 1 else: while(i < len(args) and args[i] != ' '): pattern += str(args[i]) i += 1 i += 1 else: # search dest is at the of the arguments search_dest = args[i:] i = len(args) if (search_dest[0] == "\""): # remove double quotes search_dest = search_dest[1:] search_dest = search_dest[:len(search_dest) - 1] if (pattern == "" or search_dest == ""): utils.ErrorPrint("Usage: grep [OPTION]... PATTERN [FILE]...\n") return if (search_dest == "*"): grep_dir_iterative(pattern, ".", flag_n) elif (not Path(search_dest).exists()): utils.ErrorPrint("grep: '{0}': no such file or directory\n".format(search_dest)) return else: if(os.path.isdir(search_dest)): utils.ErrorPrint("grep: '{0}': Is a directory\n".format(search_dest)) return elif (os.path.isfile(search_dest)): grep_file(pattern, search_dest, flag_n)