Search code examples
pythonfunctionsys

How to use optional command line arguments in a python function?


I want a more compact and scalable way to use command line args to feed a python function, here is what i have:

def getRelevant (number = 5, sortBy = "Change"):
    number, sortBy = int(number), sortBy
    relevant = ...
    return relevant

if __name__ == "__main__":
    if len(sys.argv) == 3:
        print(getRelevant(sys.argv[1], sys.argv[2]))
    elif len(sys.argv) == 2:
        print(getRelevant(sys.argv[1]))
    else:
        print(getRelevant())

It works. But I'm not happy with this conditionals, is there a way to make it simpler?


Solution

  • Argparse should do this. It is feature rich and flexible. For your case, the below does the job:

    import argparse
    parser = argparse.ArgumentParser(description='Description of your app here.')
    parser.add_argument('-N', '--integers', default=5,  help='your help text here')
    parser.add_argument('-S', '--sortby', default='Change', choices=['Change', 'SomeOtherOption'], help='some help text here ')
    
    if __name__ == "__main__":
      args = parser.parse_args()
      print(args.integers) # prints 5 if nothing provided
      print(args.sortby)  # prints 'Change' if nothing provided