Is there an elegant way to introduce a pair of floats using argparse?
I know I can use both separately and later process them to convert them into a numpy array of two floats, or even I have been suggested to enter the pair as a string and convert them to numbers but both seem ugly and unnecessary.
Is there a way to introduce a pair of floats so as later have them as a numpy array?
First way
def parse_arguments():
parser = argparse.ArgumentParser(description='Process two float numbers.')
# Define two float arguments
parser.add_argument('--number1', type=float, help='Enter the first float number')
parser.add_argument('--number2', type=float, help='Enter the second float number')
args = parser.parse_args()
# Check if both arguments are provided
if args.number1 is not None and args.number2 is not None:
# Create a numpy array
result_array = np.array([args.number1, args.number2])
return result_array
else:
# Handle the case when one or both arguments are not provided
print("Please provide both float numbers.")
return None
Second way
def parse_arguments():
parser = argparse.ArgumentParser(description='Process two float numbers.')
# Define an argument for two float numbers separated by a comma
parser.add_argument('--float_numbers', type=str, help='Enter two float numbers separated by a comma (e.g., 1.0,2.5)')
args = parser.parse_args()
# Check if the argument is provided
if args.float_numbers is not None:
# Split the string into two floats
numbers = [float(x) for x in args.float_numbers.split(',')]
# Create a numpy array
result_array = np.array(numbers)
return result_array
else:
# Handle the case when the argument is not provided
print("Please provide two float numbers.")
return None