Search code examples
pythonstringreplacesysdocopt

Replacing sys.argv with docopt


I'm working on incorporating some string replacements and currently arguments are passed to my script using sys.argv[i]. I'd like to replace sys with docopt, but I've found the documentation relatively unclear so far.

The way my code currently works is

filename.py -param_to_replace new_param_value

(I can also include multiple params to replace)

This then gets processed by

if len(sys.argv) > 1:
    for i in range((len(sys.argv)-1) / 2):
        params[sys.argv[1+2*i].split('-')[1]] = float(sys.argv[1+2*i+1])

where params is the name of a set of defined parameters.

I think I should be able to get this to work with docopt, but so far what I have is more like

"""Docopt test
Usage:
  filename.py --param_name1 <val> --param_name2 <val>

  filename -h | --help
  filename --version

Options:
  -h --help     Show this screen.
  --param_name1 Change some param we call param_name1, all other params changed in similar way


"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='filename 1.0')
    print(arguments)

But this doesn't pass anything and seems to be the end of the details provided in the official documentation. Does anyone with more familiarity with docopt know how to more effectively pass the command line arguments? Or should I replace sys.argv with "arguments" after this?

Thanks!


Solution

  • So I thought I would return to this since I realized I never closed the topic and post an answer. The proper way to pass the arguments is as below:

    """Usage: filename.py [--arg1=N] [--arg2=N] 
    
    Options:
        --arg1=N passes arg1
        --arg2=N passes arg2
    """
    
     from docopt import docopt 
     arguments = docopt(__doc__,version='')
     print arguments[--arg1] #This is to print any argument or pass it through
    

    It seems there was just some problem with usage, which is cleared up in the code here.