Coder Social home page Coder Social logo

docopt.jl's Introduction

docopt creates beautiful command-line interfaces

https://travis-ci.org/docopt/docopt.svg?branch=master

Video introduction to docopt: PyCon UK 2012: Create *beautiful* command-line interfaces with Python

New in version 0.6.1:

  • Fix issue #85 which caused improper handling of [options] shortcut if it was present several times.

New in version 0.6.0:

  • New argument options_first, disallows interspersing options and arguments. If you supply options_first=True to docopt, it will interpret all arguments as positional arguments after first positional argument.
  • If option with argument could be repeated, its default value will be interpreted as space-separated list. E.g. with [default: ./here ./there] will be interpreted as ['./here', './there'].

Breaking changes:

  • Meaning of [options] shortcut slightly changed. Previously it meant "any known option". Now it means "any option not in usage-pattern". This avoids the situation when an option is allowed to be repeated unintentionally.
  • argv is None by default, not sys.argv[1:]. This allows docopt to always use the latest sys.argv, not sys.argv during import time.

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.

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)

Beat that! The option parser is generated based on the docstring above that is passed to docopt function. docopt parses the usage pattern ("Usage: ...") and option descriptions (lines starting with dash "-") and ensures that the program invocation matches the usage pattern; it parses options, arguments and commands based on that. The basic idea is that a good help message has all necessary information in it to make a parser.

Also, PEP 257 recommends putting help message in the module docstrings.

Installation

Use pip or easy_install:

pip install docopt==0.6.2

Alternatively, you can just drop docopt.py file into your project--it is self-contained.

docopt is tested with Python 2.7, 3.4, 3.5, and 3.6.

Testing

You can run unit tests using the command:

python setup.py test

API

from docopt import docopt
docopt(doc, argv=None, help=True, version=None, options_first=False)

docopt takes 1 required and 4 optional arguments:

  • 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

"""
  • argv is an optional argument vector; by default docopt uses the argument vector passed to your program (sys.argv[1:]). Alternatively you can supply a list of strings like ['--verbose', '-o', 'hai.txt'].

  • help, by default True, specifies whether the parser should automatically print the help message (supplied as doc) and terminate, in case -h or --help option is encountered (options should exist in usage pattern, more on that below). If you want to handle -h or --help options manually (as other options), set help=False.

  • version, by default None, is an optional argument that specifies the version of your program. If supplied, then, (assuming --version option is mentioned in usage pattern) when parser encounters the --version option, it will print the supplied version and terminate. version could be any printable object, but most likely a string, e.g. "2.1.0rc1".

    Note, when docopt is set to automatically handle -h, --help and --version options, you still need to mention them in usage pattern for this to work. Also, for your users to know about them.

  • options_first, by default False. If set to True will disallow mixing options and positional argument. I.e. after first positional argument, all arguments will be interpreted as positional even if the look like options. This can be used for strict compatibility with POSIX, or if you want to dispatch your arguments to other programs.

The return value is a simple dictionary with options, arguments and commands as keys, spelled exactly like in your help message. Long versions of options are given priority. For example, if you invoke the top example as:

naval_fate.py ship Guardian move 100 150 --speed=15

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'}

Help message format

Help message consists of 2 parts:

  • 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
    

Their format is described below; other text is ignored.

Usage pattern format

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

"""

Each pattern can consist of the following elements:

  • <arguments>, ARGUMENTS. Arguments are specified as either upper-case words, e.g. my_program.py CONTENT-PATH or words surrounded by angular brackets: my_program.py <content-path>.
  • --options. Options are words started with dash (-), e.g. --output, -o. You can "stack" several of one-letter options, e.g. -oiv which will be the same as -o -i -v. The options can have arguments, e.g. --input=FILE or -i FILE or even -iFILE. However it is important that you specify option descriptions if you want your option to have an argument, a default value, or specify synonymous short/long versions of the option (see next section on option descriptions).
  • commands are words that do not follow the described above conventions of --options or <arguments> or ARGUMENTS, plus two special commands: dash "-" and double dash "--" (see below).

Use the following constructs to specify patterns:

  • [ ] (brackets) optional elements. e.g.: my_program.py [-hvqo FILE]
  • ( ) (parens) required elements. All elements that are not put in [ ] are also required, e.g.: my_program.py --path=<path> <file>... is the same as my_program.py (--path=<path> <file>...). (Note, "required options" might be not a good idea for your users).
  • | (pipe) mutually exclusive elements. Group them using ( ) if one of the mutually exclusive elements is required: my_program.py (--clockwise | --counter-clockwise) TIME. Group them using [ ] if none of the mutually-exclusive elements are required: my_program.py [--left | --right].
  • ... (ellipsis) one or more elements. To specify that arbitrary number of repeating elements could be accepted, use ellipsis (...), e.g. my_program.py FILE ... means one or more FILE-s are accepted. If you want to accept zero or more elements, use brackets, e.g.: my_program.py [FILE ...]. Ellipsis works as a unary operator on the expression to the left.
  • [options] (case sensitive) shortcut for any options. You can use it if you want to specify that the usage pattern could be provided with any options defined below in the option-descriptions and do not want to enumerate them all in usage-pattern.
  • "[--]". Double dash "--" is used by convention to separate positional arguments that can be mistaken for options. In order to support this convention add "[--]" to your usage patterns.
  • "[-]". Single dash "-" is used by convention to signify that stdin is used instead of a file. To support this add "[-]" to your usage patterns. "-" acts as a normal command.

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

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

then number of occurrences of the option will be counted. I.e. args['-v'] will be 2 if program was invoked as my_program -vv. Same works for commands.

If your usage patterns allows to match same-named option with argument or positional argument several times, the matched arguments will be collected into a list:

Usage: my_program.py <file> <file> --path=<path>...

I.e. invoked with my_program.py file1 file2 --path=./here --path=./there the returned dict will contain args['<file>'] == ['file1', 'file2'] and args['--path'] == ['./here', './there'].

Option descriptions format

Option descriptions consist of a list of options that you put below your usage patterns.

It is necessary to list option descriptions in order to specify:

  • synonymous short and long options,
  • if an option has an argument,
  • if option's argument has a default value.

The rules are as follows:

  • Every line in doc that starts with - or -- (not counting spaces) is treated as an option description, e.g.:

    Options:
      --verbose   # GOOD
      -o FILE     # GOOD
    Other: --bad  # BAD, line does not start with dash "-"
    
  • To specify that option has an argument, put a word describing that argument after space (or equals "=" sign) as shown below. Follow either <angular-brackets> or UPPER-CASE convention for options' arguments. You can use comma if you want to separate options. In the example below, both lines are valid, however you are recommended to stick to a single style.:

    -o FILE --output=FILE       # without comma, with "=" sign
    -i <file>, --input <file>   # with comma, without "=" sign
    
  • Use two spaces to separate options with their informal description:

    --verbose More text.   # BAD, will be treated as if verbose option had
                           # an argument "More", so use 2 spaces instead
    -q        Quit.        # GOOD
    -o FILE   Output file. # GOOD
    --stdout  Use stdout.  # GOOD, 2 spaces
    
  • If you want to set a default value for an option with an argument, put it into the option-description, in form [default: <my-default-value>]:

    --coefficient=K  The K coefficient [default: 2.95]
    --output=FILE    Output file [default: test.txt]
    --directory=DIR  Some directory [default: ./]
    
  • If the option is not repeatable, the value inside [default: ...] will be interpreted as string. If it is repeatable, it will be splited into a list on whitespace:

    Usage: my_program.py [--repeatable=<arg> --repeatable=<arg>]
                         [--another-repeatable=<arg>]...
                         [--not-repeatable=<arg>]
    
    # will be ['./here', './there']
    --repeatable=<arg>          [default: ./here ./there]
    
    # will be ['./here']
    --another-repeatable=<arg>  [default: ./here]
    
    # will be './here ./there', because it is not repeatable
    --not-repeatable=<arg>      [default: ./here ./there]
    

Examples

We have an extensive list of examples which cover every aspect of functionality of docopt. Try them out, read the source if in doubt.

Subparsers, multi-level help and huge applications (like git)

If you want to split your usage-pattern into several, implement multi-level help (with separate help-screen for each subcommand), want to interface with existing scripts that don't use docopt, or you're building the next "git", you will need the new options_first parameter (described in API section above). To get you started quickly we implemented a subset of git command-line interface as an example: examples/git

Data validation

docopt does one thing and does it well: it implements your command-line interface. However it does not validate the input data. On the other hand there are libraries like python schema which make validating data a breeze. Take a look at validation_example.py which uses schema to validate data and report an error to the user.

Using docopt with config-files

Often configuration files are used to provide default values which could be overriden by command-line arguments. Since docopt returns a simple dictionary it is very easy to integrate with config-files written in JSON, YAML or INI formats. config_file_example.py provides and example of how to use docopt with JSON or INI config-file.

Development

We would love to hear what you think about docopt on our issues page

Make pull requests, report bugs, suggest ideas and discuss docopt. You can also drop a line directly to <[email protected]>.

Porting docopt to other languages

We think docopt is so good, we want to share it beyond the Python community! All official docopt ports to other languages can be found under the docopt organization page on GitHub.

If your favourite language isn't among then, you can always create a port for it! You are encouraged to use the Python version as a reference implementation. A Language-agnostic test suite is bundled with Python implementation.

Porting discussion is on issues page.

Changelog

docopt follows semantic versioning. The first release with stable API will be 1.0.0 (soon). Until then, you are encouraged to specify explicitly the version in your dependency tools, e.g.:

pip install docopt==0.6.2
  • 0.6.2 Bugfix release.
  • 0.6.1 Bugfix release.
  • 0.6.0 options_first parameter. Breaking changes: Corrected [options] meaning. argv defaults to None.
  • 0.5.0 Repeated options/commands are counted or accumulated into a list.
  • 0.4.2 Bugfix release.
  • 0.4.0 Option descriptions become optional, support for "--" and "-" commands.
  • 0.3.0 Support for (sub)commands like git remote add. Introduce [options] shortcut for any options. Breaking changes: docopt returns dictionary.
  • 0.2.0 Usage pattern matching. Positional arguments parsing based on usage patterns. Breaking changes: docopt returns namespace (for arguments), not list. Usage pattern is formalized.
  • 0.1.0 Initial release. Options-parsing only (based on options description).

docopt.jl's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docopt.jl's Issues

Incorrect parsing symbols [ and ] which are mark optional part of argument.

If there is [ and ] in arguments then DocOpt.jl insert extra spaces around it.

using DocOpt
const doc = """Usage:
  test.jl <filename.dat[.gz]>
"""
arguments = docopt(doc)
println(arguments)

and running it with julia test.jl 1.dat yields

Dict{AbstractString,Any}(Pair{AbstractString,Any}("<filename.dat [ .gz ] >","1.dat"))

Not precompiling?

My first call to docopt takes about 4000 times longer than my second call to it. (4 seconds vs 0.001 second.) What's happening? Is Julia compiling the function during the first call, rather than pre-compiling the library? (I'm using both Julia 0.4 and Julia 0.5.)

julia> using DocOpt

julia> DOC = "Usage: my_program"
"Usage: my_program"

julia> @time     args = docopt(DOC)
  4.113140 seconds (1.88 M allocations: 80.758 MB, 12.67% gc time)
Dict{AbstractString,Any} with 0 entries

julia> @time     args = docopt(DOC)
  0.001893 seconds (400 allocations: 18.016 KB)
Dict{AbstractString,Any} with 0 entries

julia> isdefined(Base, :__precompile__)
true

[PkgEval] DocOpt may have a testing issue on Julia 0.4 (2014-08-29)

PackageEvaluator.jl is a script that runs nightly. It attempts to load all Julia packages and run their tests (if available) on both the stable version of Julia (0.3) and the nightly build of the unstable version (0.4). The results of this script are used to generate a package listing enhanced with testing results.

On Julia 0.4

  • On 2014-08-27 the testing status was Tests pass.
  • On 2014-08-29 the testing status changed to Tests fail, but package loads.

Tests pass. means that PackageEvaluator found the tests for your package, executed them, and they all passed.

Tests fail, but package loads. means that PackageEvaluator found the tests for your package, executed them, and they didn't pass. However, trying to load your package with using worked.

This issue was filed because your testing status became worse. No additional issues will be filed if your package remains in this state, and no issue will be filed if it improves. If you'd like to opt-out of these status-change messages, reply to this message saying you'd like to and @IainNZ will add an exception. If you'd like to discuss PackageEvaluator.jl please file an issue at the repository. For example, your package may be untestable on the test machine due to a dependency - an exception can be added.

Test log:

>>> 'Pkg.add("DocOpt")' log
INFO: Installing DocOpt v0.0.1
INFO: Package database updated

>>> 'using DocOpt' log
Julia Version 0.4.0-dev+417
Commit eb487b1 (2014-08-29 00:43 UTC)
Platform Info:
  System: Linux (x86_64-unknown-linux-gnu)
  CPU: Intel(R) Xeon(R) CPU E5-2650 0 @ 2.00GHz
  WORD_SIZE: 64
  BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Sandybridge)
  LAPACK: libopenblas
  LIBM: libopenlibm
  LLVM: libLLVM-3.3

>>> test log

ERROR: test error in expression: docopt("Usage: prog add","add") == $(Expr(:typed_dict, :(top(Any)=>top(Any)), :("add"=>true)))
`beginswith` has no method matching beginswith(::Nothing, ::ASCIIString)
 in parse_atom at /home/idunning/pkgtest/.julia/v0.4/DocOpt/src/DocOpt.jl:568
 in parse_seq at /home/idunning/pkgtest/.julia/v0.4/DocOpt/src/DocOpt.jl:534
 in parse_expr at /home/idunning/pkgtest/.julia/v0.4/DocOpt/src/DocOpt.jl:512
 in parse_pattern at /home/idunning/pkgtest/.julia/v0.4/DocOpt/src/DocOpt.jl:601
 in docopt at /home/idunning/pkgtest/.julia/v0.4/DocOpt/src/DocOpt.jl:665
 in anonymous at test.jl:81
 in do_test at test.jl:47
 in test_commands at /home/idunning/pkgtest/.julia/v0.4/DocOpt/test/runtests.jl:68
 in include at ./boot.jl:245
 in include_from_node1 at loading.jl:128
 in process_options at ./client.jl:285
 in _start at ./client.jl:354
 in _start_3B_3599 at /home/idunning/julia04/usr/bin/../lib/julia/sys.so
while loading /home/idunning/pkgtest/.julia/v0.4/DocOpt/test/runtests.jl, in expression starting on line 563
INFO: Testing DocOpt
===============================[ ERROR: DocOpt ]================================

failed process: Process(`/home/idunning/julia04/usr/bin/julia /home/idunning/pkgtest/.julia/v0.4/DocOpt/test/runtests.jl`, ProcessExited(1)) [1]

================================================================================
INFO: No packages to install, update or remove
ERROR: DocOpt had test errors
 in error at error.jl:21
 in test at pkg/entry.jl:715
 in anonymous at pkg/dir.jl:28
 in cd at ./file.jl:20
 in cd at pkg/dir.jl:28
 in test at pkg.jl:68
 in process_options at ./client.jl:213
 in _start at ./client.jl:354
 in _start_3B_3599 at /home/idunning/julia04/usr/bin/../lib/julia/sys.so


>>> end of log

MethodError: no method matching length(::DocOpt.Tokens)

Some of the recent change to Julia 0.5 may have been breaking...I see 5 months ago DocOpt passed on travis-ci with nightly, but it looks like it hasn't been run lately. I'm getting the follow error now, with the latest version of Julia 0.5:

julia> Pkg.test("DocOpt")
INFO: Testing DocOpt
Error During Test
  Test threw an exception of type MethodError
  Expression: parse_argv(ts("-h arg -- -v"),o) == [Option("-h",nothing,0,true),Argument(nothing,"arg"),Argument(nothing,"--"),Argument(nothing,"-v")]
  MethodError: no method matching length(::DocOpt.Tokens)
  Closest candidates are:
    length(::SimpleVector)
    length(::Base.MethodList)
    length(::MethodTable)
    ...
   in _array_for at ./array.jl:255 [inlined]
   in collect(::Base.Generator{DocOpt.Tokens,DocOpt.##25#27}) at ./array.jl:269
   in parse_argv(::DocOpt.Tokens, ::Array{DocOpt.Option,1}, ::Bool) at /global/homes/j/jregier/.julia/v0.5/DocOpt/src/DocOpt.jl:492
   in test_parse_argv() at /global/u2/j/jregier/.julia/v0.5/DocOpt/test/runtests.jl:112
   in include_from_node1(::String) at ./loading.jl:426
   in process_options(::Base.JLOptions) at ./client.jl:262
   in _start() at ./client.jl:318
ERROR: LoadError: There was an error during testing
 in record(::Base.Test.FallbackTestSet, ::Base.Test.Error) at ./test.jl:397
 in do_test(::Base.Test.Threw, ::Expr) at ./test.jl:281
 in test_parse_argv() at /global/u2/j/jregier/.julia/v0.5/DocOpt/test/runtests.jl:112
 in include_from_node1(::String) at ./loading.jl:426
 in process_options(::Base.JLOptions) at ./client.jl:262
 in _start() at ./client.jl:318
while loading /global/u2/j/jregier/.julia/v0.5/DocOpt/test/runtests.jl, in expression starting on line 567
===========================================================[ ERROR: DocOpt ]============================================================

failed process: Process(`/global/u2/j/jregier/julia/bin/julia -Cx86-64 -J/global/u2/j/jregier/julia/lib/julia/sys.so --compile=yes --depwarn=yes --check-bounds=yes --code-coverage=none --color=yes --compilecache=yes /global/u2/j/jregier/.julia/v0.5/DocOpt/test/runtests.jl`, ProcessExited(1)) [1]

========================================================================================================================================
ERROR: DocOpt had test errors
 in #test#61(::Bool, ::Function, ::Array{AbstractString,1}) at ./pkg/entry.jl:736
 in (::Base.Pkg.Entry.#kw##test)(::Array{Any,1}, ::Base.Pkg.Entry.#test, ::Array{AbstractString,1}) at ./<missing>:0
 in (::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#test,Tuple{Array{AbstractString,1}}})() at ./pkg/dir.jl:31
 in cd(::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#test,Tuple{Array{AbstractString,1}}}, ::String) at ./file.jl:59
 in #cd#1(::Array{Any,1}, ::Function, ::Function, ::Array{AbstractString,1}, ::Vararg{Array{AbstractString,1},N}) at ./pkg/dir.jl:31
 in (::Base.Pkg.Dir.#kw##cd)(::Array{Any,1}, ::Base.Pkg.Dir.#cd, ::Function, ::Array{AbstractString,1}, ::Vararg{Array{AbstractString,1},N}) at ./<missing>:0
 in #test#3(::Bool, ::Function, ::String, ::Vararg{String,N}) at ./pkg/pkg.jl:258
 in test(::String, ::Vararg{String,N}) at ./pkg/pkg.jl:258
 in eval(::Module, ::Any) at ./boot.jl:234
 in macro expansion at ./REPL.jl:92 [inlined]
 in (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at ./event.jl:46

Chaging no-positional arguments order doesn't work

Assume the very simple example:

import DocOpt
doc = """
Usage:
  test_docopt_order.jl -a <arg_a> -b <arg_b>

Options:

    -a <arg_a>  Argument A.
    -b <arg_b>  Argument B.
"""
args = DocOpt.docopt(doc)
@show args

Calling the script with the proposed order works fine:

$ julia docopt_test.jl -a aaaa -b bbbb
args = Dict{String,Any}("-a" => true,"<arg_a>" => "aaaa","-b" => true,"<arg_b>" => "bbbb")

i.e., -a gives us "<arg_a>" => "aaaa" and -b gives us "<arg_b>" => "bbbb".

Now, if we invert the order, things get messy:

$ julia docopt_test.jl -b bbbb -a aaaa
args = Dict{String,Any}("-a" => true,"<arg_a>" => "bbbb","-b" => true,"<arg_b>" => "aaaa")

Note that docopt parse <arg_a> as "bbbb" and <arg_b> as "aaaa".

In other words, it looks like docopt only consider positional arguments.

Julia Version 1.4.0 (2020-03-21)
"DocOpt" => v"0.4.0"

Cannot put mandatory argument after optional ones?

Consider the following usage description:

Usage:
  qaf_demux.jl [-i <input_fastq> | --input_fastq <input_fastq>] (-o <output_dir> | --output_dir <output_dir>) -b <barcode> -s <barcode_start> [-m <max_diff>]

-h --help                                 Show this help message and exit.
-i --input_fastq <input_fastq>            Fastq file to demultiplex. Default is to read from stdin.
-o --output_dir <output_dir>              Directory in which to put demultiplexed fastq files.
-b --barcode <barcode>                    Barcodes to which the reads should be attributed.
-s --barcode_start <barcode_start>        Position at which the barcode starts (1-based).
-m --max_diff <max_diff>                  Only assign a record to one of the barcodes if it has no more than *max_diff* differences in its barcode portion. [default: 3]

My script is complaining if I specify the mandatory option -o after the optional argument -m on my command-line:

ERROR: LoadError: ArgumentError: invalid base 10 digit '/' in "/tmp/test_qaf_demux"

If I put the -o earlier, it is fine.

(The script is also complaining if I do not provide option -m, because it doesn't populate the args with the desired default value "-m"=>false,"<max_diff>"=>nothing, but I should probably report this as a separate issue.)

Should we use `Nullable` for optional arguments?

The current implementation returns nothing for optional arguments if they are not provided by users. Julia v0.4 started to support the Nulalble type, which enables to indicate a value is null or not. This type seems to be a reasonable way to return an optional argument, but breaks the backward compatibility.
In the next release, I'd like to provide optional values as nullable because it will be a standard way in the Julia community in the long run.

DocOpt exits in interactive mode

Running the example in an interactive Julia REPL causes the REPL to exist immediately after running docopt. This is not ideal since it would cause possible data loss for users not expecting such behavior, and furthermore would crash REPLs in more complex environments like IJulia.

I would recommend changing the behavior of docopt to not terminate the current process if run within a REPL. You can check this at runtime using the isinteractive() function.

(Also: import DocOpt: docopt is not very idiomatic. The preferred usage would be to simply write using DocOpt and have the package automatically export just docopt.)

return dict should be of type Dict{String,Any}

The dict returned by docopt is of type Dict{AbstractString,Any}. I think it should be of type Dict{String,Any}, as there is no chance of accidentially putting in a type other than String.

Changing this line seems to be sufficient, and passes tests on my computer.

Tag a new release?

The current tagged version does not contain the startswith change from a few months ago.

(It's not necessary for v0.3, but it will still work since you're using Compat, and v0.4 should (finally) be released soon.)

Does not correctly handle multi-line option descriptions

If I have a multi-line option description, DocOpt.jl does not correctly group all lines together, it merely grabs the first line, discarding the rest due to this filter!() call removing all lines that do not start with - after strip()'ing. This stops option descriptions such as the following from working properly:

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
                Has a default value [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

This is identical to the canonical docopt example except that the --speed option spans multiple lines. When trying it out on try.docopt.org, you can see that --speed is correctly defaulted to 10. However, when running with Julia using this file:

doc = """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
                Has a default value [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
"""
using DocOpt

arguments = docopt(doc)
for key in keys(arguments)
    println("* $(key): $(arguments[key])")
end

It does not print out the default value properly:

$ julia docopt_test.jl ship Guardian move 10 50
* remove: false
* --help: false
* <name>: String["Guardian"]
* --drifting: false
* mine: false
* move: true
* --version: false
* --moored: false
* <x>: 10
* ship: true
* new: false
* shoot: false
* set: false
* <y>: 50
* --speed: nothing

Not working with Julia 1.0

This library doesn't seem to work with Julia 1.0:

julia> using DocOpt
[ Info: Precompiling DocOpt [968ba79b-81e4-546f-ab3a-2eecfa62a9db]
ERROR: LoadError: UndefVarError: iteratorsize not defined
Stacktrace:
 [1] getproperty(::Module, ::Symbol) at ./sysimg.jl:13
 [2] top-level scope at none:0
 [3] include at ./boot.jl:317 [inlined]
 [4] include_relative(::Module, ::String) at ./loading.jl:1038
 [5] include(::Module, ::String) at ./sysimg.jl:29
 [6] top-level scope at none:2
 [7] eval at ./boot.jl:319 [inlined]
 [8] eval(::Expr) at ./client.jl:389
 [9] top-level scope at ./none:3
in expression starting at /home/barry/.julia/packages/DocOpt/QelWY/src/DocOpt.jl:117
ERROR: Failed to precompile DocOpt [968ba79b-81e4-546f-ab3a-2eecfa62a9db] to /home/barry/.julia/compiled/v1.0/DocOpt/ZSrJU.ji.
Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] macro expansion at ./logging.jl:313 [inlined]
 [3] compilecache(::Base.PkgId, ::String) at ./loading.jl:1184
 [4] _require(::Base.PkgId) at ./logging.jl:311
 [5] require(::Base.PkgId) at ./loading.jl:852
 [6] macro expansion at ./logging.jl:311 [inlined]
 [7] require(::Module, ::Symbol) at ./loading.jl:834

I'm very new to Julia, so I might be doing something wrong. If so, please point me in the right direction.

List of arguments followed by another list

Tthe following usage is not parsed correctly:

Usage:
  main.jl --files <fnames>... --outputdir <outdir>

I had to flip the order to make it work:

Usage:
  main.jl --outputdir <outdir> --files <fnames>...

Not detecting special argument "--"

For me with Julia 1.5.0 and DocOpt 0.4.0 the special argument -- is not detected and always false.
A workaround is to pass options_first=true but is not always practical.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.