подпрограммы

This commit is contained in:
badkaktus 2019-10-12 21:08:18 +03:00
parent e62cee4774
commit 89b09c204a
3 changed files with 23 additions and 23 deletions

View File

@ -64,7 +64,7 @@ Epoch
Тестирование (Testing) Тестирование (Testing)
Аргументы командной строки (Command-Line Arguments) Аргументы командной строки (Command-Line Arguments)
Флаги командной строки (Command-Line Flags) Флаги командной строки (Command-Line Flags)
Command-Line Subcommands Подкоманды командной строки (Command-Line Subcommands)
Environment Variables Environment Variables
HTTP Clients HTTP Clients
HTTP Servers HTTP Servers

View File

@ -1,9 +1,9 @@
// Some command-line tools, like the `go` tool or `git` // Некоторые инструменты командной строки, такие как `go`
// have many *subcommands*, each with its own set of // или `git`, имеют много *подкоманд*, каждая со своим
// flags. For example, `go build` and `go get` are two // собственным набором флагов. Например, `go build` и
// different subcommands of the `go` tool. // `go get` - это две разные подкоманды инструмента `go`.
// The `flag` package lets us easily define simple // Пакет `flag` позволяет нам легко определять простые
// subcommands that have their own flags. // подкоманды, которые имеют свои собственные флаги.
package main package main
@ -15,30 +15,30 @@ import (
func main() { func main() {
// We declare a subcommand using the `NewFlagSet` // Мы объявляем подкоманду, используя функцию `NewFlagSet`,
// function, and proceed to define new flags specific // и приступаем к определению новых флагов, специфичных
// for this subcommand. // для этой подкоманды.
fooCmd := flag.NewFlagSet("foo", flag.ExitOnError) fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
fooEnable := fooCmd.Bool("enable", false, "enable") fooEnable := fooCmd.Bool("enable", false, "enable")
fooName := fooCmd.String("name", "", "name") fooName := fooCmd.String("name", "", "name")
// For a different subcommand we can define different // Для другой подкоманды мы можем определить другие
// supported flags. // флаги.
barCmd := flag.NewFlagSet("bar", flag.ExitOnError) barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
barLevel := barCmd.Int("level", 0, "level") barLevel := barCmd.Int("level", 0, "level")
// The subcommand is expected as the first argument // Подкоманда ожидается в качестве первого аргумента
// to the program. // программы.
if len(os.Args) < 2 { if len(os.Args) < 2 {
fmt.Println("expected 'foo' or 'bar' subcommands") fmt.Println("expected 'foo' or 'bar' subcommands")
os.Exit(1) os.Exit(1)
} }
// Check which subcommand is invoked. // Проверяем, какая подкоманда вызвана.
switch os.Args[1] { switch os.Args[1] {
// For every subcommand, we parse its own flags and // Для каждой подкоманды мы анализируем ее собственные
// have access to trailing positional arguments. // флаги и имеем доступ к аргументам.
case "foo": case "foo":
fooCmd.Parse(os.Args[2:]) fooCmd.Parse(os.Args[2:])
fmt.Println("subcommand 'foo'") fmt.Println("subcommand 'foo'")

View File

@ -1,24 +1,24 @@
$ go build command-line-subcommands.go $ go build command-line-subcommands.go
# First invoke the foo subcommand. # Первый вызов подкоманды foo.
$ ./command-line-subcommands foo -enable -name=joe a1 a2 $ ./command-line-subcommands foo -enable -name=joe a1 a2
subcommand 'foo' subcommand 'foo'
enable: true enable: true
name: joe name: joe
tail: [a1 a2] tail: [a1 a2]
# Now try bar. # Теперь пробуем bar.
$ ./command-line-subcommands bar -level 8 a1 $ ./command-line-subcommands bar -level 8 a1
subcommand 'bar' subcommand 'bar'
level: 8 level: 8
tail: [a1] tail: [a1]
# But bar won't accept foo's flags. # Но bar не может принимать флаги определенные для foo.
$ ./command-line-subcommands bar -enable a1 $ ./command-line-subcommands bar -enable a1
flag provided but not defined: -enable flag provided but not defined: -enable
Usage of bar: Usage of bar:
-level int -level int
level level
# Next we'll look at environment variables, another common # Далее мы рассмотрим переменные окружения, еще один
# way to parameterize programs. # распространенный способ параметризации программ.