Create simple arg parse in python

argparse is a module to make user-friendly command-line interfaces. It’s probably the one of the most frequently used module when I create a script in python that needs to parse some arguments. Check this out.

$ vim test.py
#!/usr/bin/python
import argparse

def init_args():
  parser = argparse. ArgumentParser(description="This is the description")
  parser.add_argument("--arg1", required=True, type=str, help="This is arg1")
  parser.add_argument("--allow", required=False, action="store_true", help="Allow mode")
  return parser.parse_args()

def main(arg1):
  return "arg1: %s"%(arg1)

if __name__ == "__main__":
  args = init_args()
  main(args.arg1)

See what happens when we run it

$ ./test.py --arg1 "showme"
arg1: showme

Sometimes we want to create an argumen but only store it as a True variable. we can just create simple test like this.

$ vim test.py
#!/usr/bin/python
import argparse

def init_args():
  parser = argparse. ArgumentParser(description="This is the description")
  parser.add_argument("--arg1", required=False, action="store_true", help="Enable arg1")
  return parser.parse_args()

def main():
  return "arg1 is enabled"

if __name__ == "__main__":
  args = init_args()
  if args.arg1:
    main()
  else:
    print "arg1 parse is not enabled"

Try to run it

$ ./test.py --arg1
arg1 is enabled

Leave a Comment