File tree Expand file tree Collapse file tree 3 files changed +61
-0
lines changed
Expand file tree Collapse file tree 3 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 1010| withcontext.go| cmdexec\_ withcontext| コマンドを context.Context 付きで実行するサンプルです|
1111| pipe.go| cmdexec\_ pipe| (* Cmd).StdinPipe,StdoutPipe,StderrPipeのサンプルです|
1212| multi\_ command\_ with\_ pipe.go| cmdexec\_ multi\_ command\_ with\_ pipe| 複数の (* exec.Cmd) をパイプストリームで繋いで実行するサンプルです|
13+ | withenv.go| cmdexec\_ env| * exec.Cmd 実行時に追加の環境変数を指定するサンプルです|
Original file line number Diff line number Diff line change @@ -19,4 +19,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
1919 m ["cmdexec_withcontext" ] = WithContext
2020 m ["cmdexec_pipe" ] = Pipe
2121 m ["cmdexec_multi_command_with_pipe" ] = MultiCommandWithPipe
22+ m ["cmdexec_env" ] = WithEnv
2223}
Original file line number Diff line number Diff line change 1+ package cmdexec
2+
3+ import (
4+ "errors"
5+ "os"
6+ "os/exec"
7+ "runtime"
8+
9+ "github.com/devlights/gomy/output"
10+ )
11+
12+ // WithEnv -- *exec.Cmd 実行時に追加の環境変数を指定するサンプルです.
13+ //
14+ // REFERENCES
15+ // - https://dev.to/tobychui/quick-notes-for-go-os-exec-3ejg
16+ func WithEnv () error {
17+ if runtime .GOOS == "windows" {
18+ return errors .New ("this example cannot run on Windows, sorry" )
19+ }
20+
21+ const (
22+ Shell = "/bin/bash"
23+ )
24+
25+ var (
26+ cmd * exec.Cmd
27+ out []byte
28+ err error
29+ )
30+
31+ //
32+ // 環境変数の追加なし
33+ //
34+ cmd = exec .Command (Shell , "-c" , "env | grep LANG" )
35+
36+ out , err = cmd .Output ()
37+ if err != nil {
38+ return err
39+ }
40+
41+ output .Stdoutf ("[no append]" , "\n %s\n " , out )
42+ output .StdoutHr ()
43+
44+ //
45+ // 環境変数の追加あり
46+ //
47+ cmd = exec .Command (Shell , "-c" , "env | grep LANG" )
48+ cmd .Env = append (os .Environ (), "LANG2=Japanese" )
49+
50+ out , err = cmd .Output ()
51+ if err != nil {
52+ return err
53+ }
54+
55+ output .Stdoutf ("[append ]" , "\n %s\n " , out )
56+ output .StdoutHr ()
57+
58+ return nil
59+ }
You can’t perform that action at this time.
0 commit comments