{"id":13410251,"url":"https://github.com/akamensky/argparse","last_synced_at":"2026-02-08T21:17:59.340Z","repository":{"id":38984033,"uuid":"111885079","full_name":"akamensky/argparse","owner":"akamensky","description":"Argparse for golang. Just because `flag` sucks","archived":false,"fork":false,"pushed_at":"2022-10-31T14:00:31.000Z","size":229,"stargazers_count":600,"open_issues_count":6,"forks_count":62,"subscribers_count":12,"default_branch":"v1","last_synced_at":"2024-07-31T20:41:25.803Z","etag":null,"topics":["argparse","argument-parser","awesome-go","cli","cli-app","command-line-parser","go","golang"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/akamensky.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":"akamensky"}},"created_at":"2017-11-24T06:42:20.000Z","updated_at":"2024-07-30T08:57:42.000Z","dependencies_parsed_at":"2022-07-13T06:50:39.150Z","dependency_job_id":null,"html_url":"https://github.com/akamensky/argparse","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akamensky%2Fargparse","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akamensky%2Fargparse/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akamensky%2Fargparse/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akamensky%2Fargparse/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/akamensky","download_url":"https://codeload.github.com/akamensky/argparse/tar.gz/refs/heads/v1","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221481998,"owners_count":16829979,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["argparse","argument-parser","awesome-go","cli","cli-app","command-line-parser","go","golang"],"created_at":"2024-07-30T20:01:05.814Z","updated_at":"2026-02-08T21:17:59.331Z","avatar_url":"https://github.com/akamensky.png","language":"Go","readme":"# Golang argparse\n\n[![](https://img.shields.io/static/v1?label=Sponsor\u0026message=%E2%9D%A4\u0026logo=GitHub\u0026color=%23fe8e86)](https://github.com/sponsors/akamensky) [![Go Reference](https://pkg.go.dev/badge/github.com/akamensky/argparse.svg)](https://pkg.go.dev/github.com/akamensky/argparse) [![Go Report Card](https://goreportcard.com/badge/github.com/akamensky/argparse)](https://goreportcard.com/report/github.com/akamensky/argparse) [![Coverage Status](https://coveralls.io/repos/github/akamensky/argparse/badge.svg?branch=master)](https://coveralls.io/github/akamensky/argparse?branch=master) [![Build Status](https://travis-ci.org/akamensky/argparse.svg?branch=master)](https://travis-ci.org/akamensky/argparse)\n\nLet's be honest -- Go's standard command line arguments parser `flag` terribly sucks. \nIt cannot come anywhere close to the Python's `argparse` module. This is why this project exists.\n\nThe goal of this project is to bring ease of use and flexibility of `argparse` to Go. \nWhich is where the name of this package comes from.\n\n#### Installation\n\nTo install and start using argparse simply do:\n\n```\n$ go get -u -v github.com/akamensky/argparse\n```\n\nYou are good to go to write your first command line tool!\nSee Usage and Examples sections for information how you can use it\n\n#### Usage\n\nTo start using argparse in Go see above instructions on how to install.\nFrom here on you can start writing your first program.\nPlease check out examples from `examples/` directory to see how to use it in various ways.\n\nHere is basic example of print command (from `examples/print/` directory):\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com/akamensky/argparse\"\n\t\"os\"\n)\n\nfunc main() {\n\t// Create new parser object\n\tparser := argparse.NewParser(\"print\", \"Prints provided string to stdout\")\n\t// Create string flag\n\ts := parser.String(\"s\", \"string\", \u0026argparse.Options{Required: true, Help: \"String to print\"})\n\t// Parse input\n\terr := parser.Parse(os.Args)\n\tif err != nil {\n\t\t// In case of error print error and print usage\n\t\t// This can also be done by passing -h or --help flags\n\t\tfmt.Print(parser.Usage(err))\n\t}\n\t// Finally print the collected string\n\tfmt.Println(*s)\n}\n```\n\n#### Basic options\n\nCreate your parser instance and pass it program name and program description.\nProgram name if empty will be taken from `os.Args[0]` (which is okay in most cases).\nDescription can be as long as you wish and will be used in `--help` output\n```go\nparser := argparse.NewParser(\"progname\", \"Description of my awesome program. It can be as long as I wish it to be\")\n```\n\nString will allow you to get a string from arguments, such as `$ progname --string \"String content\"`\n```go\nvar myString *string = parser.String(\"s\", \"string\", ...)\n```\n\nPositional arguments can be used like this `$ progname value1`.\nSee [Basic Option Structure](#basic-option-structure) and [Positionals](#positionals).\n```go\nvar myString *string = parser.StringPositional(nil)\nvar myString *string = parser.FilePositional(nil)\nvar myString *string = parser.FloatPositional(nil)\nvar myString *string = parser.IntPositional(nil)\nvar myString *string = parser.SelectorPositional([]string{\"a\", \"b\"}, nil)\nvar myString1 *string = parser.StringPositional(Options{Default: \"beep\"})\n```\n\nSelector works same as a string, except that it will only allow specific values.\nFor example like this `$ progname --debug-level WARN`\n```go\nvar mySelector *string = parser.Selector(\"d\", \"debug-level\", []string{\"INFO\", \"DEBUG\", \"WARN\"}, ...)\n```\n\nStringList allows to collect multiple string values into the slice of strings by repeating same flag multiple times.\nSuch as `$ progname --string hostname1 --string hostname2 -s hostname3`\n```go\nvar myStringList *[]string = parser.StringList(\"s\", \"string\", ...)\n```\n\nList allows to collect multiple values into the slice of strings by repeating same flag multiple times \n(at fact - it is an Alias of StringList).\nSuch as `$ progname --host hostname1 --host hostname2 -H hostname3`\n```go\nvar myList *[]string = parser.List(\"H\", \"hostname\", ...)\n```\n\nFlag will tell you if a simple flag was set on command line (true is set, false is not).\nFor example `$ progname --force`\n```go\nvar myFlag *bool = parser.Flag(\"f\", \"force\", ...)\n```\n\nFlagCounter will tell you the number of times that  simple flag  was set on command line \n(integer greater than or equal to 1 or 0 if not set).\nFor example `$ progname -vv --verbose`\n```go\nvar myFlagCounter *int = parser.FlagCounter(\"v\", \"verbose\", ...)\n```\n\nInt will allow you to get a decimal integer from arguments, such as `$ progname --integer \"42\"`\n```go\nvar myInteger *int = parser.Int(\"i\", \"integer\", ...)\n```\n\nIntList allows to collect multiple decimal integer values into the slice of integers by repeating same flag multiple times.\nSuch as `$ progname --integer 42 --integer +51 -i -1`\n```go\nvar myIntegerList *[]int = parser.IntList(\"i\", \"integer\", ...)\n```\n\nFloat will allow you to get a floating point number from arguments, such as `$ progname --float \"37.2\"`\n```go\nvar myFloat *float64 = parser.Float(\"f\", \"float\", ...)\n```\n\nFloatList allows to collect multiple floating point number values into the slice of floats by repeating same flag multiple times.\nSuch as `$ progname --float 42 --float +37.2 -f -1.0`\n```go\nvar myFloatList *[]float64 = parser.FloatList(\"f\", \"float\", ...)\n```\n\nFile will validate that file exists and will attempt to open it with provided privileges.\nTo be used like this `$ progname --log-file /path/to/file.log`\n```go\nvar myLogFile *os.File = parser.File(\"l\", \"log-file\", os.O_RDWR, 0600, ...)\n```\n\nFileList allows to collect files into the slice of files by repeating same flag multiple times.\nFileList will validate that files exists and will attempt to open them with provided privileges.\nTo be used like this `$ progname --log-file /path/to/file.log --log-file /path/to/file_cpy.log -l /another/path/to/file.log`\n```go\nvar myLogFiles *[]os.File = parser.FileList(\"l\", \"log-file\", os.O_RDWR, 0600, ...)\n```\n\nYou can implement sub-commands in your CLI using `parser.NewCommand()` or go even deeper with `command.NewCommand()`.\nAddition of a sub-command implies that a subcommand is required.\nSub-commands are always parsed before arguments.\nIf a command has `Positional` arguments and sub-commands then sub-commands take precedence.\nSince parser inherits from command, every command supports exactly same options as parser itself,\nthus allowing to add arguments specific to that command or more global arguments added on parser itself!\n\nYou can also dynamically retrieve argument values and if they were parsed:\n```\nvar myInteger *int = parser.Int(\"i\", \"integer\", ...)\nparser.Parse()\nfmt.Printf(\"%d\", *parser.GetArgs()[0].GetResult().(*int))\nfmt.Printf(\"%v\", *parser.GetArgs()[0].GetParsed())\n```\n\n#### Basic Option Structure\n\nThe `Option` structure is declared at `argparse.go`:\n```go\ntype Options struct {\n\tRequired bool\n\tValidate func(args []string) error\n\tHelp     string\n\tDefault  interface{}\n}\n```\n\nYou can set `Required` to let it know if it should ask for arguments.\nOr you can set `Validate` as a lambda function to make it know while value is valid.\nOr you can set `Help` for your beautiful help document.\nOr you can set `Default` will set the default value if user does not provide a value.\n\nExample:\n```\ndirpath := parser.String(\"d\", \"dirpath\",\n\t\t\t \u0026argparse.Options{\n\t\t\t \tRequired: false,\n\t\t\t\tHelp: \"the input files' folder path\",\n\t\t\t\tDefault: \"input\",\n\t\t\t})\n```\n\n#### Caveats\n\nThere are a few caveats (or more like design choices) to know about:\n* Shorthand arguments MUST be a single character. Shorthand arguments are prepended with single dash `\"-\"`\n* If not convenient shorthand argument can be completely skipped by passing empty string `\"\"` as first argument\n* Shorthand arguments ONLY for `parser.Flag()` and  `parser.FlagCounter()` can be combined into single argument same as `ps -aux`, `rm -rf` or `lspci -vvk` \n* Long arguments must be specified and cannot be empty. They are prepended with double dash `\"--\"`\n* You cannot define two same arguments. Only first one will be used. For example doing `parser.Flag(\"t\", \"test\", nil)` followed by `parser.String(\"t\", \"test2\", nil)` will not work as second `String` argument will be ignored (note that both have `\"t\"` as shorthand argument). However since it is case-sensitive library, you can work arounf it by capitalizing one of the arguments\n* There is a pre-defined argument for `-h|--help`, so from above attempting to define any argument using `h` as shorthand will fail\n* `parser.Parse()` returns error in case of something going wrong, but it is not expected to cover ALL cases\n* Any arguments that left un-parsed will be regarded as error\n\n##### Positionals\n* `Positional` args have a set of effects and conditions:\n  * Always parsed after subcommands and non-positional args\n  * Always set Required=False\n  * Default is only used if the command or subcommand owning the arg `Happened`\n  * Parsed in Command root-\u003eleaf left-\u003eright order (breadth-first)\n\t* Top level cmd consumes as many positionals as it can, from left to right\n\t* Then in a descendeding loop for any command which `Happened` it repeats\n\t* Positionals which are not satisfied (due to lack of input args) are not errors\n\n#### Contributing\n\nCan you write in Go? Then this projects needs your help!\n\nTake a look at open issues, specially the ones tagged as `help-wanted`.\nIf you have any improvements to offer, please open an issue first to ensure this improvement is discussed.\n\nThere are following tasks to be done:\n* Add more examples\n* Improve code quality (it is messy right now and could use a major revamp to improve gocyclo report)\n* Add more argument options (such as numbers parsing)\n* Improve test coverage\n* Write a wiki for this project\n\nHowever note that the logic outlined in method comments must be preserved \nas the the library must stick with backward compatibility promise!\n\n#### Acknowledgments\n\nThanks to Python developers for making a great `argparse` which inspired this package to match for greatness of Go\n","funding_links":["https://github.com/sponsors/akamensky"],"categories":["Command Line","CLI frameworks","命令行","Go","命令行工具### 标准 CLI`用于创建一个标准命令行应用程序的库`","Build Automation","cli","命令行工具","[Go](https://go.dev/)"],"sub_categories":["Standard CLI","标准CLI","标准 CLI","Useful awesome list for Dotnet cli"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakamensky%2Fargparse","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fakamensky%2Fargparse","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakamensky%2Fargparse/lists"}