def test_inputCustom(self): # Test validation function arg: def isEven(value): if float(value) % 2 != 0: raise Exception('This is not an even value.') pauseThenType('4.1\n2\n') self.assertEqual(pyip.inputCustom(isEven), '2') pauseThenType('hello\n2\n') self.assertEqual(pyip.inputCustom(isEven), '2') pauseThenType('4\n') self.assertEqual(pyip.inputCustom(isEven), '4') pauseThenType('4.0\n') self.assertEqual(pyip.inputCustom(isEven), '4.0')
def pawnTransform(nb_, nc_): new_figure = pyip.inputCustom( whatFigure, 'New figure:\n- queen = WQ\n- bishop = WB\n- knight = WKN\n- rook = WR' ) nb_[nc_[0]][nc_[1]] = new_figure return nb_
def getInputStr(prompt: str, maxlength: int = None, regex: list = None) -> str: def validateInput(text): if len(text) > maxlength: raise Exception(f"Max {maxlength} character is allowed") if regex != None and re.match(regex, text) == None: raise Exception(f"Invalid input pattern") if maxlength != None or regex != None: text = pyip.inputCustom(customValidationFunc=validateInput, prompt=prompt) else: text = pyip.inputStr(prompt=prompt) return text
def open_account(): """This account collect user inputs for opening new account. Collect User inputs, store that in a list and pass it to the backend open account. if the result from the backend is true it restart the program again and if the result if false it call the open_account() method again to collect user information again. Return: None """ print("\n") print(messages.open_account) u_id = pyip.inputInt("Id: ", greaterThan=0) name = pyip.inputCustom(raiseNameError, prompt="Name: ") address = pyip.inputCustom(raiseAddressError, prompt="Address: ") email = pyip.inputEmail("Email: ") balance = pyip.inputInt("Balance: ", min=0) password = pyip.inputPassword("Password: ") user_data = [u_id, name, address, balance, email, password] result = BankOperationsBackend.open_account(user_data) start_again() if result else BankOperationsUi.open_account()
import pyinputplus as pyip def addsUptoTen(numbers): numList = list(numbers) for i,num in enumerate(numList): numList[i] = int(num) if sum(numList) != 10: raise Exception ('The digit must add up to 10, not %s.'%(sum(numList))) return int(numbers) response = pyip.inputCustom(addsUptoTen,'Enter:\t') print('=>',response)
response = pyip.inputNum('>', min=4, lessThan=6) # The blank Keyword Argument response = pyip.inputNum(blank=True) # The limit, timeout, and default Keyword Arguments response = pyip.inputNum(limit=2) # two attempts response = pyip.inputNum(timeout=10) # will wait for 10 seconds for input response = pyip.inputNum(limit=2, default='N/A') # The allowRegexes and blockRegexes Keyword Arguments response = pyip.inputNum(allowRegexes=[r'(I|X|L|C|D|M)+', r'zero']) response = pyip.inputNum(allowRegexes=[r'(i|x|l|c|d|m)+', r'zero']) response = pyip.inputStr(allowRegexes=[r'caterpillar', 'category'], blockRegexes=[r'cat']) # Passing a Custom Validation Function to inputCustom() def addsUpToTen(numbers): numbersList = list(numbers) for i, digit in enumerate(numbersList): numbersList[i] = int(digit) if sum(numbersList) != 10: raise Exception('the digits must add up to 10 , not %s' % (sum(numbersList))) return int(numbers) res = pyip.inputCustom(addsUpToTen) print(res)
This response is invalid. category >>> response 'category' ''' # %% Passing a Custom Validation fn to inputCustom() import pyinputplus as pyip def addsUpToTen(nums): numsList = list(nums) for i, digit in enumerate(numsList): numsList[i] = int(digit) if sum(numsList) != 10: raise Exception(f'The digits must add up to 10, not {sum(numsList)}') return int(nums) # returns an int form of numbers response = pyip.inputCustom(addsUpToTen) # no parentheses after addsUpToTen ''' 123 The digits must add up to 10, not 6 1235 The digits must add up to 10, not 11 1234 >>> response 1234 >>> response = pyip.inputCustom(addsUpToTen) hello invalid literal for int() with base 10: 'h' 55 >>> response 55 '''
for link in soup.findAll('a'): links.append(link.get('href')) #print(link.get('href')) # Iterate through list and return validity for each link for link in links: try: validity = requests.get(link) validity.raise_for_status() print('\nLink:\n', link, '\nStatus: Valid') except Exception as e: print('\nLink:\n', link, '\nStatus: ERROR! 404 - ' 'Link is not a valid website.') print('Exception: {}'.format(e)) # Running the program print('Welcome to LinkVerification. This app will crawl a website of your' 'choice and check all links for validity. An error will be presented' 'if a link is not valid.') print('\nPlease enter a website URL: ') base_page = pyip.inputCustom(validate_url) page_validity = get_website(base_page) if page_validity: # Find every link on website check_links(base_page) else: print('Terminating program.')
age = pip.inputNum(prompt='What is your age? ', greaterThan=1) #Alow blank age = pip.inputNum(prompt='What is your age? ', greaterThan=1, blank=True) #Limit retries on wrong answers age = pip.inputNum(prompt='What is your age? ', greaterThan=1, limit=2) #Timeout after 30 seconds if no input given age = pip.inputNum(prompt='What is your age? ', greaterThan=1, timeout=30) #Define a defaul value so retrylimitexception or timeoutexception aren't thrown age = pip.inputNum(prompt='What is your age? ', greaterThan=1, limit=2, default=18) #Only accept roman numerals via a regex age = pip.inputNum(allowRegexes=[r'(i|v|x|l|c|d|m)+']) #Don't accept numbers ending in 00 age = pip.inputNum(blockRegexes=[r'00$']) #Custom input example def addsUpToTen(numbers): l = list(numbers) for i, digit in enumberate(l): l[i] = int(digit) if sum(l) != 10: raise Exception('The digits must add up to 10.') else: return int(numbers) age = pip.inputCustom(addsUpToTen)
import pyinputplus as pyip def adds_up_to_ten(numbers): numberList = [] for element in numbers: numberList.append(int(numbers)) for i, digit in enumerate(numberList): numberList[i] = int(digit) if sum(numberList) != 10: raise Exception("The digits must add up to 10") return int(numbers) response = pyip.inputCustom(adds_up_to_ten)
import pyinputplus #x = pyinputplus.inputNum("Input a Number: ", limit=3) #print(x) #y = pyinputplus.inputNum("Input a number, this is a timeout: ", timeout=10, default="Timeout") #print(y) #r = pyinputplus.inputNum("Input Your Roman Numeral or Integers in 10 seconds: ", allowRegexes=[r"(I|V|W|L|C|D|M|X)+", r"zero"]) #print(r) def addsuptoten(numbers): numberList = list(numbers) for i, integer in enumerate(numberList): numberList[i] = int(integer) if sum(numberList) != 10: raise Exception("the numbers must add upto to 10, not %s." % (sum(numberList))) return int(numbers) response = pyinputplus.inputCustom(addsuptoten) print(response)
print("Passing a custom validation function to inputCustom()".center(99,'=')) print("You can write a function that performs some custom validation logic not provided by the functions in PyInputPlus by passing the function to inputCustom()") print("Your function should:") print("1. Accept a string argument of what your user entered") print("2. Raise an exception if the string fails validation") print("3. Returns None (or has no return statement) if inputCustom should return the string unchanged") print("4. Returns a non-None value if inputCustom() should return a different string from the one the user entered") print("5. Be passed as the first argument to inputCustom()") print("Note that the function call looks like inputCustom(name_of_custom_function) and not inputCustom(name_of_custom_function()) because you are passing the function itself to inputCustom() and not calling the custom function and passing the return value to inputCustom()") print('#' * 99) # custom validation function def add_up_to_ten(numbers): numbers_list = list(numbers) for i, digit in enumerate(numbers_list): numbers_list[i] = int(digit) if sum(numbers_list) != 10: raise Exception("The sum of the numbers should be equal to {} not {}".format(10, sum(numbers_list))) return(int(numbers)) response = pyip.inputCustom(add_up_to_ten, prompt="Enter numbers adding up to ten\n") print(response) print('#' * 99) print("Writing your own custom validation function is useful when it is otherwise impossible to write a regex for valid input") print('#' * 99)
# ensure user enters a yes or no response # response = pyip.inputYesNo('please enter yes/no: ') # takes True or False # response = pyip.inputBool('please enter T/F: ') # ensures inputs email # response = pyip.inputEmail('please enter a valid email: ') # ensure filepath, plus checks a file actually exists # response = pyip.inputFilepath('please enter a filepath: ', mustExist=True) # allows the user to enter password, showing * as they type # response = pyip.inputPassword('please enter your password: '******'the digits must add to 10, not %s' % sum(L)) print('good job. adds up to 10') return sum(L) response = pyip.inputCustom( MustAddToTen, prompt='please enter numbers that add up to 10, no spaces: ') print(response)
import pyinputplus as pyip def addsUpToTen(numbers): numbersList = list(numbers) for i, digit in enumerate(numbersList): numbersList[i] = int(digit) if sum(numbersList) != 10: raise Exception('The digits must add up to 10, not %s.' % (sum(numbersList))) return int(numbers) # Return an int form of numbers. response = pyip.inputCustom(addsUpToTen)
fmlist_.append(fm_pb3) fm_pb4 = 0 fmlist_.append(fm_pb4) fm_pb5 = 0 fmlist_.append(fm_pb5) fm_pb6 = 0 fmlist_.append(fm_pb6) fm_pb7 = 0 fmlist_.append(fm_pb7) nb_ = b.table() nbinfo_ = b.startBoard() while True: print(tabulate(nb_, tablefmt="grid")) figure = pyip.inputCustom(isChessFigure, "Figure: ") coor = pyip.inputCustom(isCoordinates, "Coordinates: ") nc_ = list(newCoor(coor)) new_fmlist_ = [] #king if figure == 'WK' or figure == 'BK': dict_, nb_, mate, draw, pat, check, mate = k.king( figure, fmlist_, mvcounts, nc_, nbinfo_, nb_) fmk += 1 new_fmlist_.append(fmk) if mate: print(f'End of game, {f.whoseMove(mvcounts)} is the winner.') break
import pyinputplus as pyip # response = pyip.inputNum('Enter number: ', min=4, lessThan=6, blank=True) # response = pyip.inputYesNo('Answer "yes" or "no".', limit=2, default='No') # # print(f'The response is {response}.') def adds_up_to_ten(numbers): print("Enter a string of numbers that adds up to ten. IF YOU DARE.") numbers_list = list(numbers) for i, digit in enumerate(numbers_list): numbers_list[i] = int(digit) if sum(numbers_list) != 10: raise Exception("The digits must add up to 10, not %s." % (sum(numbers_list))) return int(numbers) # Return an int form of numbers. response = pyip.inputCustom("Enter a string of numbers that adds up to ten. IF YOU DARE.", adds_up_to_ten)
import pyinputplus as pyip foodTypes = { 'breadType': ['wheat', 'white', 'sourdough'], 'proteinType': ['chicken', 'turkey', 'ham', 'tofu'], 'chessType': ['cheddar', 'Swiss', 'mozzarella'] } def inputMenu(food): for key in foodTypes: if food in foodTypes[key]: return food raise Exception("It's not a food") response = pyip.inputCustom(inputMenu, 'Please, enter food')
def create_custom_validator(my_number: int): def compare_against_number(my_str): try: selected_number = int(my_str) if selected_number != my_number: raise Exception(f"{selected_number} is not the right answer") except ValueError: raise Exception(f"{my_str} must be a integer") return compare_against_number results = [] for m in multipliers: try: multiplier01, multiplier02 = m prompt = f"{multiplier01} x {multiplier02} = " result = multiplier01 * multiplier02 pyip.inputCustom(create_custom_validator(result), prompt=prompt, timeout=8, limit=3) print("Correct\n") results.append(True) time.sleep(1) except pyip.TimeoutException: results.append(False) print("Out of time!") except pyip.RetryLimitException: results.append(False) print("Out of tries!") print(f"Total: {['Right' if b else 'Wrong' for b in results]}")
# Bypass filters # We're going to be using the subprocess Module # subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, # cwd=None, timeout=None, check=False, # encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs) # Subprocess contains functions that allow us to execute system commands # Commands depend on the OS which executes the script import subprocess, re import pyinputplus as pyip def is_mac(s): mac_regex = re.compile(r'(([A-Fa-f]|\d){2}:){5}([A-Fa-f]|\d){2}') mo1 = mac_regex.search(s) if mo1 is None: raise Exception('Not a valid MAC Address.') interface = pyip.inputStr(prompt='What interface would you like to change?\n') new_address = pyip.inputCustom(is_mac, prompt='Enter your new MAC Address:\n', limit=4,) print('Changing MAC address of ' + interface + ' to ' + new_address) subprocess.run('sudo ifconfig' + interface + 'down', shell=True) # disconnect interface subprocess.run(('sudo ifconfig' + interface + 'hw ether ' + new_address), shell=True) # Change the MAC subprocess.run('sudo ifconfig' + interface + 'up', shell=True) # Reconnect' + interface subprocess.run('sudo ifconfig' + interface, shell=True) # Return connection properties
def pawnTransform(nb_, nc_): new_figure = pyip.inputCustom(whatFigure, 'New figure:\n- queen = BQ\n') nb_[nc_[0]][nc_[1]] = new_figure return nb_
# greaterThan/lessThan -> ensures input to be greater or less than a value response1 = pyip.inputNum('Enter num: ', min=4) response2 = pyip.inputNum('Enter num: ', greaterThan=4) # Arguments for any function # limit=int -> limit the number of tries to enter valid input before the default value is returned # timeout=int/float -> limit the number of seconds to enter a valid input # default=str/None -> default value to use should the user time out or exceed the number of tries # blank=True -> allow you to use blank inputs # allowRegexes -> limit input to a list of regular expression strings # blockRegexes -> block a list of regular expression strings to be accepted as an input response3 = pyip.inputNum(limit=2, default='N/A') response4 = pyip.inputNum(timeout=10, default='N/A') response5 = pyip.inputNum(blank=True) response6 = pyip.inputNum(allowRegexes=[r'(I|V|X|L|C|D|M)+', r'zero']) response7 = pyip.inputNum(blockRegexes=[r'[02468]$']) # You can write a function to perform your own custom validation logic by passing the function to inputCustom() def adds_uptoten(numbers): numberslist = list(numbers) for i, digit in enumerate(numberslist): numberslist[i] = int(digit) if sum(numberslist) != 10: raise Exception('The digits must add up to 10, not %s.' % (sum(numberslist))) return int(numbers) # Return an int form of numbers response8 = pyip.inputCustom(adds_uptoten)
numbersList = list( numbers ) # creates a list separating each character, for example 234 --> ['2', '3', '4'] for i, digit in enumerate( numbersList ): # It creates an enumerate object, which is the count number (in this case 0 unless we specify another) and the item in the list numbersList[i] = int( digit ) # takes the index in the 2-tuple and use that to converte the element in the list to an integer ''' Explanation of the above: An enumerate will create something like this (0, '2'), (1, '3'), (2, '4') with this code we make sure that every digit (the second element in the tuple which we call by using the index) will be converted to integer ''' if sum( numbersList ) != 10: # if the sum of the elements in the array is different from 10 raises an exception raise Exception( f'The digits must add up to 10, not {sum(numbersList)}') return int(numbers) test_custom_input = pyip.inputCustom( addsUpToTen ) # the exception created before makes that inputCustom() runs until a valid input gets entered print(test_custom_input)
#!/usr/bin/env python3 ''' Example program where the user enters a series of digits that adds up to 10. This function passes a custom validation function to inputCustom(): - Accepts a single string argument of what the user entered - Raises an exception if the string fails validation - Returns None (or has no return statement) if inputCustom() should return the string unchanged - Returns a non-None value if inputCustom() should return a different string from the one the user entered - Function passes as first argument to inputCustom() ''' import pyinputplus as pyip def addsUpToTen(numbers): numbersList = list(numbers) # Convert string to list of numbers for i, digit in enumerate(numbersList): # Add up each number in string numbersList[i] = int(digit) if sum(numbersList) != 10: # Raise exception if string fails validation raise Exception('The digits must add up to 10, not %s.' % (sum(numbersList))) return int(numbers) # Return an int form of numbers response = pyip.inputCustom(addsUpToTen) # No parenthesis after print(response)