Search code examples
pythoncommand-lineposixgnu

Standard cmd line separation for option-arguments


Is there a standard for how command-line arguments are passed, or does this differ from program to program? For example, here are a few examples:

  1. $ script.py -a 2
  2. $ script.py -a=2
  3. $ script.py a=2
  4. $ script.py --all 2
  5. $ script.py --all=2

Solution

  • If you use argparse, you will find support for most of the above options. For example:

    # test.py
    import argparse
    parser = argparse.ArgumentParser(description='Dedupe library.')
    parser.add_argument( '-a', '--all', nargs='+', type = int, help='(Optional) Enter one or more Master IDs.')
    

    To run:

    df$ python test.py -a 2
    # {'all': [2]}
    df$ python test.py -a=2
    # {'all': [2]}
    df$ python test.py a=2
    # test.py: error: unrecognized arguments: a=2
    $ python test.py --all 2
    # {'all': [2]}
    $ python test.py --all=2
    # {'all': [2]}
    

    As you can see, all are supported except the form of script.py a=2