docopt on python 3 only prints help screen and does not execute the function

  • Last Update :
  • Techknowledgy :

Here is an example. I have this code in a file.

""
"Usage:  scratch.py [-h] [--boston | --sandiego] [--prostitution |
--drugs][--lim VALUE]
Options:
   -h--help: Show help information
   --boston: work on boston addresses
   --sandiego: work on san diego addresses
   --prostitution: prostitution incidents
   --drugs: drug sale incidents
   --lim: number of addresses to work with ""
"

from docopt
import docopt

def scratch(args):
   print(args['--boston'])
print('hello')

if __name__ == '__main__':

   arg = docopt(__doc__, help = False)
print(arg)
scratch(arg)

So if I make a command line call like:

python scratch.py--boston--drugs--lim 100

All that is returned is the following.

Usage: scratch.py <city> [--boston | --sandiego] <crime> [--prostitution |
      --drugs] --count=N
      Options:
      city : city to geocode
      --boston : work on boston addresses
      --sandiego : work on san diego addresses
      crime : crime to select on
      --prostitution : prostitution incidents
      --drugs : drug sale incidents
      -count : number of addresses to work with

Suggestion : 2

Last Updated : 10 Jul, 2020

You can install docopt module in various ways, pip is one of the best ways to install docopt.

$pip install docopt

–option -o: The element starting with “–” or “-” are called as long or short option. It can either be mentioned as --option or -o.

  -h, --help Display help
     -
     o, --option Display options -
     l, --all List all -
     q, --quit exit
     --version Version 3.6 .1

Suggestion : 3

docopt helps you create most beautiful command-line interfaces easily:,Video introduction to docopt: PyCon UK 2012: Create *beautiful* command-line interfaces with Python,0.5.0 Repeated options/commands are counted or accumulated into a list.,Every line in doc that starts with - or -- (not counting spaces) is treated as an option description, e.g.:

docopt helps you create most beautiful command-line interfaces easily:

"""Naval Fate.

Usage:
naval_fate.py ship new <name>...
   naval_fate.py ship <name> move <x>
         <y> [--speed=<kn>]
               naval_fate.py ship shoot <x>
                  <y>
                     naval_fate.py mine (set|remove) <x>
                        <y> [--moored | --drifting]
                           naval_fate.py (-h | --help)
                           naval_fate.py --version

                           Options:
                           -h --help Show this screen.
                           --version Show version.
                           --speed=<kn> Speed in knots [default: 10].
                              --moored Moored (anchored) mine.
                              --drifting Drifting mine.

                              """
                              from docopt import docopt


                              if __name__ == '__main__':
                              arguments = docopt(__doc__, version='Naval Fate 2.0')
                              print(arguments)

Use pip or easy_install:

pip install docopt == 0.6 .2

API

from docopt
import docopt
from docopt import docopt
docopt(doc, argv = None, help = True, version = None, options_first = False)
  • doc could be a module docstring (__doc__) or some other string that contains a help message that will be parsed to create the option parser. The simple rules of how to write such a help message are given in next sections. Here is a quick example of such a string:

""
"Usage: my_program.py [-hso FILE] [--quiet | --verbose] [INPUT ...]

-
h--help show this
   -
   s--sorted sorted output -
   o FILE specify output file[
      default: . / test.txt]
   --quiet print less text
   --verbose print more text

""
"

the return dictionary will be:

{'--drifting': False,    'mine': False,
 '--help': False,        'move': True,
 '--moored': False,      'new': False,
 '--speed': '15',        'remove': False,
 '--version': False,     'set': False,
 '<name>': ['Guardian'], 'ship': True,
 '<x>': '100',           'shoot': False,
 '<y>': '150'}

Usage pattern, e.g.:

Usage: my_program.py[-hso FILE][--quiet | --verbose][INPUT...]

Option descriptions, e.g.:

-h--help show this
   -
   s--sorted sorted output -
   o FILE specify output file[
      default: . / test.txt]
   --quiet print less text
   --verbose print more text

Usage pattern is a substring of doc that starts with usage: (case insensitive) and ends with a visibly empty line. Minimum example:

""
"Usage: my_program.py

""
"

The first word after usage: is interpreted as your program’s name. You can specify your program’s name several times to signify several exclusive patterns:

""
"Usage: my_program.py FILE
my_program.py COUNT FILE

""
"

If your pattern allows to match argument-less option (a flag) several times:

Usage: my_program.py[-v | -vv | -vvv]

Suggestion : 4

Isn't it awesome how optparse and argparse generate help messages based on your code?!,Hell no! You know what's awesome? It's when the option parser is generated based on the beautiful help message that you write yourself! This way you don't need to write this stupid repeatable parser-code, and instead can write only the help message--the way you want it.,Note, when docopt is set to automatically handle -h, --help and --version options, you still need to mention them in the options description (doc) for your users to know about them.,doc should be a string that describes options in a human-readable format, that will be parsed to create the option parser. The simple rules of how to write such a docstring (in order to generate option parser from it successfully) are given in the next section. Here is a quick example of such a string:

docopt helps you create most beautiful command-line interfaces easily:

require "docopt"
doc = <<DOCOPT
Naval Fate.

Usage:
  #{__FILE__} ship new <name>...
  #{__FILE__} ship <name> move <x> <y> [--speed=<kn>]
  #{__FILE__} ship shoot <x> <y>
  #{__FILE__} mine (set|remove) <x> <y> [--moored|--drifting]
  #{__FILE__} -h | --help
  #{__FILE__} --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

DOCOPT

begin
  require "pp"
  pp Docopt::docopt(doc)
rescue Docopt::Exit => e
  puts e.message
end

Docopt is available via rubygems:

gem install docopt

doc should be a string that describes options in a human-readable format, that will be parsed to create the option parser. The simple rules of how to write such a docstring (in order to generate option parser from it successfully) are given in the next section. Here is a quick example of such a string:

Usage: your_program.rb[options]

   -
   h--help Show this. -
   v--verbose Print more text.
   --quiet Print less text. -
   o FILE Specify output file[
      default: . / test.txt].

the return dictionary will be::

{"ship"=>true,
 "new"=>false,
 "<name>"=>["Guardian"],
 "move"=>true,
 "<x>"=>"100",
 "<y>"=>"150",
 "--speed"=>"15",
 "shoot"=>false,
 "mine"=>false,
 "set"=>false,
 "remove"=>false,
 "--moored"=>false,
 "--drifting"=>false,
 "--help"=>false,
 "--version"=>false}

doc should be a string that describes options in a human-readable format, that will be parsed to create the option parser. The simple rules of how to write such a docstring (in order to generate option parser from it successfully) are given in the next section. Here is a quick example of such a string:

Usage: your_program.rb[options]

   -
   h--help Show this. -
   v--verbose Print more text.
   --quiet Print less text. -
   o FILE Specify output file[
      default: . / test.txt].

Suggestion : 5

It is not just the social value of PEP8 but the actual optimizations in those mature scientific libraries that make Python so important as a reason to choose it over other languages.,In fact it is impossible to declare a language superior except in its use to develop a solution space for a problem space within constraints. Python is paradoxically useful amongst other languages mainly due to the community surrounding it and the social mores that have evolved for its use., continuous-integration scrutinizer code-quality php python ruby Discussing the real benefits of high code quality and a practical example ,All this editorializing aside, Python favors ease of development and maintenance over strict protections and enforcements. It has a set of PEP documents (Python Enhancement Proposals) where arguments are reviewed and decided.

Here are three command-lines showing use of three different tools:

# pep8 Dict.py
# pyflakes Dict.py
# pylint Dict.py | less

(not pep8/pyflakes/pylint/PyChecker checked)

from types
import MethodType
class aClass(object): pass
def aMethod(self): print('A message')
anInstance = aClass()
setattr(anInstance, 'aName', MethodType(aMethod, anInstance, aClass))
anInstance.aName()

The reason pylint raises a warning is the absence of a super-init. This is intentional, since the dictionary will be managed using a different style.

#!/usr/bin/env python

""
"Dict.py
Author: Jonathan D.Lettvin
LinkedIn: jlettvin
Date: 20141020 ""
"

from types import(MethodType)

class Dict(dict):
   ""
"
This derived class adds the ability to view and modify a dictionary
using the simpler lexical naming convention used
for code token names
rather than the more complex braces and quotes dictionary accessors.
""
"

remove = '-<>'
# Add characters to this string to get them removed.

@staticmethod
def _clean(k):
   ""
"
This private method removes non - token characters from strings.
Remove all '-'
characters from hashable key to make it lexically ok,
for instance when converting argv command - line dicts.
https: //docs.python.org/2/library/string.html#string.translate
   ""
"
return k.translate(None, Dict.remove)

def _method(self, value):
   ""
"
This private method converts external functions to internal methods.
https: //docs.python.org/2/library/types.html
   ""
"
assert type(value) == type(Dict._clean)
return MethodType(value, self, Dict)

def __init__(self, ** kw):
   ""
"
__class__ has a __dict__ member.
By replacing this __dict__ member with the parent dict builtin
we may access its members lexically instead of with hashable keys.
""
"
self.__dict__ = self # This is the magic line
self.let( ** kw)

def __call__(self, ** kw):
   'Update the instance dictionary'
self.let( ** kw)
return self

def
let (self, ** kw):
"instance dictionary bulk updater"
self.update({
   Dict._clean(k): v
   for k,
   v in kw.items()
})
return self

def method(self, ** kw):
   "instance dictionary bulk method attacher"
self.update({
   Dict._clean(k): self._method(v) for k,
   v in kw.items()
})
return self