cli flags

This commit is contained in:
badkaktus 2019-10-12 20:58:18 +03:00
parent 7d9228f759
commit e62cee4774
4 changed files with 53 additions and 47 deletions

View File

@ -63,7 +63,7 @@ Epoch
Временные файлы и директории (Temporary Files and Directories)
Тестирование (Testing)
Аргументы командной строки (Command-Line Arguments)
Command-Line Flags
Флаги командной строки (Command-Line Flags)
Command-Line Subcommands
Environment Variables
HTTP Clients

View File

@ -1,10 +1,11 @@
# To experiment with command-line arguments it's best to
# build a binary with `go build` first.
# Чтобы поэкспериментировать с аргументами командной
# строки, лучше сначала создать двоичный файл с
# помощью `go build`.
$ go build command-line-arguments.go
$ ./command-line-arguments a b c d
[./command-line-arguments a b c d]
[a b c d]
c
# Next we'll look at more advanced command-line processing
# with flags.
# Далее мы рассмотрим более сложную обработку командной
# строки с флагами.

View File

@ -1,13 +1,14 @@
// [_Command-line flags_](http://en.wikipedia.org/wiki/Command-line_interface#Command-line_option)
// are a common way to specify options for command-line
// programs. For example, in `wc -l` the `-l` is a
// command-line flag.
// [_Флаги командной строки_](http://en.wikipedia.org/wiki/Command-line_interface#Command-line_option)
// являются распространенным способом задания параметров
// для программ командной строки. Например, в `wc -l` - `-l`
// является флагом командной строки.
package main
// Go provides a `flag` package supporting basic
// command-line flag parsing. We'll use this package to
// implement our example command-line program.
// Go предоставляет пакет `flag`, поддерживающий базовый
// парсинг флагов командной строки. Мы будем использовать
// этот пакет для реализации нашего примера программы
// командной строки.
import (
"flag"
"fmt"
@ -15,34 +16,36 @@ import (
func main() {
// Basic flag declarations are available for string,
// integer, and boolean options. Here we declare a
// string flag `word` with a default value `"foo"`
// and a short description. This `flag.String` function
// returns a string pointer (not a string value);
// we'll see how to use this pointer below.
// Основные объявления флагов доступны для строковых,
// целочисленных и логических параметров. Здесь мы
// объявляем строковой флаг `word` со значением по
// умолчанию `"foo"` и кратким описанием. Функция
// `flag.String` возвращает строковый указатель (не
// строковое значение); мы увидим, как использовать
// этот указатель ниже.
wordPtr := flag.String("word", "foo", "a string")
// This declares `numb` and `fork` flags, using a
// similar approach to the `word` flag.
// Объявляем флаги `numb` и `fork`, используя тот же
// подход, что и выше.
numbPtr := flag.Int("numb", 42, "an int")
boolPtr := flag.Bool("fork", false, "a bool")
// It's also possible to declare an option that uses an
// existing var declared elsewhere in the program.
// Note that we need to pass in a pointer to the flag
// declaration function.
// Также возможно вызвать метод, который использует
// существующую переменную, объявленную в другом месте
// программы. Обратите внимание, что в данном случае
// необходимо передать указатель.
var svar string
flag.StringVar(&svar, "svar", "bar", "a string var")
// Once all flags are declared, call `flag.Parse()`
// to execute the command-line parsing.
// Как только все флаги объявлены, вызовите `flag.Parse()`,
// чтобы выполнить парсинг командной строки.
flag.Parse()
// Here we'll just dump out the parsed options and
// any trailing positional arguments. Note that we
// need to dereference the pointers with e.g. `*wordPtr`
// to get the actual option values.
// Здесь мы просто выведем результат парсинга и все
// введеные аргументы. Обратите внимание, что нам
// нужно разыменовать указатели, например, с
// помощью `*wordPtr`, чтобы получить фактические
// значения.
fmt.Println("word:", *wordPtr)
fmt.Println("numb:", *numbPtr)
fmt.Println("fork:", *boolPtr)

View File

@ -1,10 +1,10 @@
# To experiment with the command-line flags program it's
# best to first compile it and then run the resulting
# binary directly.
# Чтобы поэкспериментировать с программой флагов командной
# строки, лучше сначала скомпилировать ее, а затем
# напрямую запустить полученный бинарный файл.
$ go build command-line-flags.go
# Try out the built program by first giving it values for
# all flags.
# Попробуйте встроенную программу, сначала задав ей
# значения для всех флагов.
$ ./command-line-flags -word=opt -numb=7 -fork -svar=flag
word: opt
numb: 7
@ -12,8 +12,8 @@ fork: true
svar: flag
tail: []
# Note that if you omit flags they automatically take
# their default values.
# Обратите внимание, что если вы опустите флаги, они
# автоматически примут свои значения по умолчанию.
$ ./command-line-flags -word=opt
word: opt
numb: 42
@ -21,16 +21,17 @@ fork: false
svar: bar
tail: []
# Trailing positional arguments can be provided after
# any flags.
# Конечные позиционные аргументы могут быть
# предоставлены после любых флагов.
$ ./command-line-flags -word=opt a1 a2 a3
word: opt
...
tail: [a1 a2 a3]
# Note that the `flag` package requires all flags to
# appear before positional arguments (otherwise the flags
# will be interpreted as positional arguments).
# Обратите внимание, что пакет `flag` требует, чтобы все
# флаги отображались перед позиционными аргументами
# (в противном случае флаги будут интерпретироваться
# как позиционные аргументы).
$ ./command-line-flags -word=opt a1 a2 a3 -numb=7
word: opt
numb: 42
@ -38,8 +39,9 @@ fork: false
svar: bar
tail: [a1 a2 a3 -numb=7]
# Use `-h` or `--help` flags to get automatically
# generated help text for the command-line program.
# Используйте флаги `-h` или `--help`, чтобы получить
# автоматически сгенерированный текст справки для
# программы командной строки.
$ ./command-line-flags -h
Usage of ./command-line-flags:
-fork=false: a bool
@ -47,9 +49,9 @@ Usage of ./command-line-flags:
-svar="bar": a string var
-word="foo": a string
# If you provide a flag that wasn't specified to the
# `flag` package, the program will print an error message
# and show the help text again.
# Если вы укажете флаг, который не был указан для пакета
# флагов, программа напечатает сообщение об ошибке
# и снова покажет текст справки.
$ ./command-line-flags -wat
flag provided but not defined: -wat
Usage of ./command-line-flags: