I have a project I'm working on and I wanted to pass possible flags from user input (example "-s") into a boolean list from where I can find specific options the user has requested for.
My code currently:
def run():
running = True
while running:
user_input = input()
dir_path = find_file_name(user_input[2:])
flags = get_action(dir_path[1])
file_dump = []
options = [False] * 6
if user_input[0] == "Q":
running = False
break
elif user_input[0] == "L":
options[0] = "-r" in flags
options[1] = "-f" in flags
options[2] = "-s" in flags
options[3] = "-e" in flags
While this technique works, I was hoping that there would be a better way to do the last part with the options being set based on the flags contained in the input. I'm also not 100% sure this is a good way to use a run()
method. Any suggestions would be helpful! Thanks!
CodePudding user response:
Take a look at standard library argparse
module. It does what you need and a lot more.
CodePudding user response:
As jetpack_guy said, argparse
is the best way to do something like this. This library has a lot of features, but here's how to create booleans from arguments like you need.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-r', action='store_true')
parser.add_argument('-f', action='store_true')
parser.add_argument('-s', action='store_true')
parser.add_argument('-e', action='store_true')
args = parser.parse_args()
print(args.r)
print(args.f)
print(args.s)
print(args.e)
python test.py -r
would produce r: True, f: False, s: False, e: False
python test.py -r -f -s
would produce r: True, f: True, s: True, e: False
python test.py -rsf
would produce r: True, f: True, s: True, e: False