Pages

03/12/2021

[Python] Simple command line options and menu

I recently needed to make a script automatable, meaning I had to provide all inputs to it from the CLI command used to execute it, rather than wait for it to prompt me during execution.

Turns out Python has a nice module dedicated to this: argparse

The usage is very simple and will also create the help menu automatically for us:

 import argparse  
   
 parser = argparse.ArgumentParser("myScript")  
 parser.add_argument("-a_flag_input", help="This is a true/false flag", action='store_true')  
 parser.add_argument("-a_string_input", help="This is a string input", type=str)  
 args = parser.parse_args()  
 options = vars(args)  
 print(args)  
   
 if options["a_flag_input"]:  
  print("a_string_input")  

Basically, we define each input parameter along with its type, if the input is a flag (true/false) we can specify an action on it to determine the value it would receive if set.

The inputs will be collected in a Namespace object, which we can convert to dictionary and get easy access to the inputs from the code.

No comments:

Post a Comment

With great power comes great responsibility