порождающие команды
This commit is contained in:
parent
18cd0d0514
commit
f411479c93
@ -68,7 +68,7 @@ Epoch
|
|||||||
Переменные среды (Environment Variables)
|
Переменные среды (Environment Variables)
|
||||||
HTTP клиенты (HTTP Clients)
|
HTTP клиенты (HTTP Clients)
|
||||||
HTTP серверы (HTTP Servers)
|
HTTP серверы (HTTP Servers)
|
||||||
Spawning Processes
|
Порождающие процессы (Spawning Processes)
|
||||||
Exec'ing Processes
|
Exec'ing Processes
|
||||||
Signals
|
Signals
|
||||||
Exit
|
Exit
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
// Sometimes our Go programs need to spawn other, non-Go
|
// Иногда наши программы Go должны порождать другие, не
|
||||||
// processes. For example, the syntax highlighting on this
|
// Go процессы. Например, подсветка синтаксиса на этом
|
||||||
// site is [implemented](https://github.com/mmcgrana/gobyexample/blob/master/tools/generate.go)
|
// сайте [реализуется](https://github.com/mmcgrana/gobyexample/blob/master/tools/generate.go)
|
||||||
// by spawning a [`pygmentize`](http://pygments.org/)
|
// путем запуска [`pygmentize`](http://pygments.org/)
|
||||||
// process from a Go program. Let's look at a few examples
|
// процесса из программы Go. Давайте рассмотрим несколько
|
||||||
// of spawning processes from Go.
|
// примеров порождающих процессов из Go.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
@ -15,16 +15,16 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
// We'll start with a simple command that takes no
|
// Мы начнем с простой команды, которая не принимает
|
||||||
// arguments or input and just prints something to
|
// аргументов или ввода и просто печатает что-то на
|
||||||
// stdout. The `exec.Command` helper creates an object
|
// стандартный вывод. Хелпер `exec.Command` создает
|
||||||
// to represent this external process.
|
// объект для представления этого внешнего процесса.
|
||||||
dateCmd := exec.Command("date")
|
dateCmd := exec.Command("date")
|
||||||
|
|
||||||
// `.Output` is another helper that handles the common
|
// `.Output` - это еще один хелпер, который обрабатывает
|
||||||
// case of running a command, waiting for it to finish,
|
// общий случай запуска команды, ожидаетее завершения
|
||||||
// and collecting its output. If there were no errors,
|
// и сбора выходных данных. Если ошибок не было, `dateOut`
|
||||||
// `dateOut` will hold bytes with the date info.
|
// будет содержать байты с информацией о дате.
|
||||||
dateOut, err := dateCmd.Output()
|
dateOut, err := dateCmd.Output()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
@ -32,15 +32,15 @@ func main() {
|
|||||||
fmt.Println("> date")
|
fmt.Println("> date")
|
||||||
fmt.Println(string(dateOut))
|
fmt.Println(string(dateOut))
|
||||||
|
|
||||||
// Next we'll look at a slightly more involved case
|
// Далее мы рассмотрим несколько более сложный случай,
|
||||||
// where we pipe data to the external process on its
|
// когда мы направляем данные во внешний процесс на
|
||||||
// `stdin` and collect the results from its `stdout`.
|
// его `stdin` и собираем результаты из его `stdout`.
|
||||||
grepCmd := exec.Command("grep", "hello")
|
grepCmd := exec.Command("grep", "hello")
|
||||||
|
|
||||||
// Here we explicitly grab input/output pipes, start
|
// Здесь мы явно получаем каналы ввода-вывода,
|
||||||
// the process, write some input to it, read the
|
// запускаем процесс, записываем в него некоторые
|
||||||
// resulting output, and finally wait for the process
|
// входные данные, читаем полученный результат и,
|
||||||
// to exit.
|
// наконец, ожидаем завершения процесса.
|
||||||
grepIn, _ := grepCmd.StdinPipe()
|
grepIn, _ := grepCmd.StdinPipe()
|
||||||
grepOut, _ := grepCmd.StdoutPipe()
|
grepOut, _ := grepCmd.StdoutPipe()
|
||||||
grepCmd.Start()
|
grepCmd.Start()
|
||||||
@ -49,20 +49,20 @@ func main() {
|
|||||||
grepBytes, _ := ioutil.ReadAll(grepOut)
|
grepBytes, _ := ioutil.ReadAll(grepOut)
|
||||||
grepCmd.Wait()
|
grepCmd.Wait()
|
||||||
|
|
||||||
// We ommited error checks in the above example, but
|
// Мы опускаем проверки ошибок в приведенном выше
|
||||||
// you could use the usual `if err != nil` pattern for
|
// примере, но вы можете использовать обычный шаблон
|
||||||
// all of them. We also only collect the `StdoutPipe`
|
// `if err != nil` для них. Мы также собираем только
|
||||||
// results, but you could collect the `StderrPipe` in
|
// результаты `StdoutPipe`, но вы можете собирать
|
||||||
// exactly the same way.
|
// `StderrPipe` точно таким же образом.
|
||||||
fmt.Println("> grep hello")
|
fmt.Println("> grep hello")
|
||||||
fmt.Println(string(grepBytes))
|
fmt.Println(string(grepBytes))
|
||||||
|
|
||||||
// Note that when spawning commands we need to
|
// Обратите внимание, что при порождении команд нам
|
||||||
// provide an explicitly delineated command and
|
// нужно предоставить явно разграниченный массив
|
||||||
// argument array, vs. being able to just pass in one
|
// команд и аргументов вместо возможности просто
|
||||||
// command-line string. If you want to spawn a full
|
// передать одну строку командной строки.
|
||||||
// command with a string, you can use `bash`'s `-c`
|
// Если вы хотите создать полную команду со строкой,
|
||||||
// option:
|
// вы можете использовать опцию `-c` в `bash`:
|
||||||
lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
|
lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
|
||||||
lsOut, err := lsCmd.Output()
|
lsOut, err := lsCmd.Output()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
# The spawned programs return output that is the same
|
# Порожденные программы возвращают вывод, который
|
||||||
# as if we had run them directly from the command-line.
|
# является таким же, как если бы мы запускали их
|
||||||
|
# непосредственно из командной строки.
|
||||||
$ go run spawning-processes.go
|
$ go run spawning-processes.go
|
||||||
> date
|
> date
|
||||||
Wed Oct 10 09:53:11 PDT 2012
|
Wed Oct 10 09:53:11 PDT 2012
|
||||||
|
Loading…
x
Reference in New Issue
Block a user