本文整理汇总了Golang中os.Environ函数的典型用法代码示例。如果您正苦于以下问题:Golang Environ函数的具体用法?Golang Environ怎么用?Golang Environ使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Environ函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: compile
func compile(w *World) *bytes.Buffer {
ioutil.WriteFile(TEMPPATH+".go", []byte(w.source()), 0644)
err := new(bytes.Buffer)
re, e, _ := os.Pipe()
attr := &os.ProcAttr{Env: os.Environ(), Files: []*os.File{nil, e, nil}}
args := []string{bin + "/" + arch + "g", "-o", TEMPPATH + ".6", TEMPPATH + ".go"}
os.StartProcess(bin+"/"+arch+"g", args, attr)
e.Close()
io.Copy(err, re)
if err.Len() > 0 {
return err
}
re, e, _ = os.Pipe()
attr = &os.ProcAttr{Env: os.Environ(), Files: []*os.File{nil, e, nil}}
args = []string{bin + "/" + arch + "l", "-o", TEMPPATH + "", TEMPPATH + ".6"}
os.StartProcess(bin+"/"+arch+"l", args, attr)
e.Close()
io.Copy(err, re)
return err
}
示例2: buildChromium
func buildChromium(chromiumDir, targetPlatform string) error {
if err := os.Chdir(filepath.Join(chromiumDir, "src")); err != nil {
return fmt.Errorf("Could not chdir to %s/src: %s", chromiumDir, err)
}
// Find the build target to use while building chromium.
buildTarget := "chrome"
if targetPlatform == "Android" {
util.LogErr(
ioutil.WriteFile(filepath.Join(chromiumDir, "chromium.gyp_env"), []byte("{ 'GYP_DEFINES': 'OS=android', }\n"), 0777))
buildTarget = "chrome_public_apk"
}
// Restart Goma's compiler proxy right before building the checkout.
err := ExecuteCmd("python", []string{filepath.Join(GomaDir, "goma_ctl.py"), "restart"},
os.Environ(), GOMA_CTL_RESTART_TIMEOUT, nil, nil)
if err != nil {
return fmt.Errorf("Error while restarting goma compiler proxy: %s", err)
}
// Run "GYP_DEFINES='gomadir=/b/build/goma' GYP_GENERATORS='ninja' build/gyp_chromium -Duse_goma=1".
env := []string{fmt.Sprintf("GYP_DEFINES=gomadir=%s", GomaDir), "GYP_GENERATORS=ninja"}
err = ExecuteCmd(filepath.Join("build", "gyp_chromium"), []string{"-Duse_goma=1"}, env,
GYP_CHROMIUM_TIMEOUT, nil, nil)
if err != nil {
return fmt.Errorf("Error while running gyp_chromium: %s", err)
}
// Run "ninja -C out/Release -j100 ${build_target}".
// Use the full system env while building chromium.
args := []string{"-C", "out/Release", "-j100", buildTarget}
return ExecuteCmd("ninja", args, os.Environ(), NINJA_TIMEOUT, nil, nil)
}
示例3: StartProcess
func StartProcess() (*os.Process, error) {
argv0, err := exec.LookPath(os.Args[0])
if err != nil {
return nil, err
}
files := make([]*os.File, 0)
files = append(files, os.Stdin)
files = append(files, os.Stdout)
files = append(files, os.Stderr)
for _, key := range os.Environ() {
if strings.HasPrefix(key, ENV_PREFIX) {
parts := strings.SplitN(key, "=", 2)
if fd, err := strconv.Atoi(parts[1]); err == nil {
if err = noCloseOnExec(uintptr(fd)); err != nil {
files = append(files, os.NewFile(uintptr(fd), key))
}
}
}
}
return os.StartProcess(argv0, os.Args, &os.ProcAttr{
Dir: path.Dir(argv0),
Env: os.Environ(),
Files: files,
Sys: &syscall.SysProcAttr{},
})
}
示例4: Infra
func (f *Foundation) Infra(ctx *foundation.Context) error {
if ctx.Action == "" {
appInfra := ctx.Appfile.ActiveInfrastructure()
lookup := directory.Lookup{Infra: appInfra.Type}
infra, err := ctx.Directory.GetInfra(&directory.Infra{Lookup: lookup})
os.Setenv("DEISCTL_TUNNEL", infra.Outputs["ip"])
fmt.Println("DEISCTL_TUNNEL is " + os.Getenv("DEISCTL_TUNNEL"))
cmd := exec.Command("deisctl", "config", "platform", "set", "version=v1.11.1")
cmd.Env = os.Environ()
err = ottoExec.Run(ctx.Ui, cmd)
cmd = exec.Command("deisctl", "config", "platform", "set", "sshPrivateKey=~/.ssh/deis-test")
cmd.Env = os.Environ()
err = ottoExec.Run(ctx.Ui, cmd)
cmd = exec.Command("deisctl", "config", "platform", "set", "domain=goings.space")
cmd.Env = os.Environ()
err = ottoExec.Run(ctx.Ui, cmd)
cmd = exec.Command("deisctl", "install", "platform")
cmd.Env = os.Environ()
err = ottoExec.Run(ctx.Ui, cmd)
cmd = exec.Command("deisctl", "start", "platform")
cmd.Env = os.Environ()
err = ottoExec.Run(ctx.Ui, cmd)
return err
}
return nil
}
示例5: TestRunHookExceptional
func (s *DebugHooksServerSuite) TestRunHookExceptional(c *C) {
err := ioutil.WriteFile(s.ctx.ClientFileLock(), []byte{}, 0777)
c.Assert(err, IsNil)
session, err := s.ctx.FindSession()
c.Assert(session, NotNil)
c.Assert(err, IsNil)
// Run the hook in debug mode with no exit flock held.
// The exit flock will be acquired immediately, and the
// debug-hooks server process killed.
err = session.RunHook("myhook", s.tmpdir, os.Environ())
c.Assert(err, ErrorMatches, "signal: killed")
// Run the hook in debug mode with the exit flock held.
// This simulates the client process starting but not
// cleanly exiting (normally the .pid file is updated,
// and the server waits on the client process' death).
cmd := exec.Command("flock", s.ctx.ClientExitFileLock(), "-c", "sleep 1s")
c.Assert(cmd.Start(), IsNil)
expected := time.Now().Add(time.Second)
err = session.RunHook("myhook", s.tmpdir, os.Environ())
after := time.Now()
c.Assert(after, checkers.TimeBetween(expected.Add(-100*time.Millisecond), expected.Add(100*time.Millisecond)))
c.Assert(err, ErrorMatches, "signal: killed")
c.Assert(cmd.Wait(), IsNil)
}
示例6: startAttachTag
func startAttachTag(tag string) {
if *dockerFlag == "" {
*dockerFlag, _ = exec.LookPath("docker")
}
var containers []string
img := "gc14:" + tag
foreachDockerPs(func(runningImage, containerID string) {
if runningImage != img {
return
}
containers = append(containers, containerID)
})
switch {
case len(containers) > 1:
for _, container := range containers {
// Best effort:
exec.Command(*dockerFlag, "kill", container).Run()
exec.Command(*dockerFlag, "rm", container).Run()
}
case len(containers) == 1:
if err := syscall.Exec(*dockerFlag,
[]string{*dockerFlag, "attach", containers[0]},
os.Environ()); err != nil {
log.Fatalf("docker attach exec: %v", err)
}
}
if err := syscall.Exec(*dockerFlag,
[]string{*dockerFlag, "run", "-t", "-i", "-h", tag, "-w", "/home/gopher", img, "/bin/bash"},
os.Environ()); err != nil {
log.Fatalf("docker run exec: %v", err)
}
}
示例7: main
func main() {
// 获取系统名字
fmt.Println(os.Hostname())
// 获取系统内存
fmt.Println(os.Getpagesize())
// 获取系统环境变量
for index, env := range os.Environ() {
fmt.Println(index, " : ", env)
}
// 获取指定key的环境变量,环境变量不区分大小写
fmt.Println("当前系统目录为:", os.Getenv("windir"))
// 设置环境变量
fmt.Println("cody的环境变量为:", os.Getenv("cody"))
os.Setenv("Cody", "guo")
fmt.Println("cody的环境变量为:", os.Getenv("cody"))
// 删除所有环境变量
os.Clearenv()
fmt.Println(os.Environ())
// 如果存在os.Exit()就不会执行defer
// defer fmt.Println("我在退出吗?")
// os.Exit(0)
fmt.Println("程序已退出,不打印了...")
fmt.Println(os.Getuid(), os.Getgid())
fmt.Println(os.Getgroups())
fmt.Println(os.Getpid(), os.Getppid())
fmt.Println(os.TempDir())
}
示例8: TestSetNewEval
func TestSetNewEval(t *testing.T) {
arguments := []Argument{
Constant("/bin/bash"),
Constant("-c"),
Constant("echo $setenv"),
}
exec := ExecPromise{ExecTest, arguments}
var sout bytes.Buffer
ctx := NewContext()
ctx.ExecOutput = &sout
name := "setenv"
value := "blafasel"
s := SetEnv{Constant(name), Constant(value), exec}
oldenv := fmt.Sprintf("%v", os.Environ())
s.Eval([]Constant{}, &ctx, "setenv")
newenv := fmt.Sprintf("%v", os.Environ())
if oldenv != newenv {
t.Errorf("(setenv) changed overall environment")
}
if sout.String() != "blafasel\n" {
t.Errorf("env name not present during execution")
}
}
示例9: Mousetrap
func Mousetrap(app *cli.App) {
oldBefore := app.Before
app.Before = func(c *cli.Context) error {
if mousetrap.StartedByExplorer() {
cmd := exec.Command(os.Args[0], os.Args[1:]...)
cmd.Env = append(os.Environ(), "MOUSETRAP=1")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
cmd = exec.Command("cmd.exe", "/K")
cmd.Env = os.Environ()
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
fmt.Println("Failed to execute sub-process. Error:", err)
os.Exit(1)
}
os.Exit(0)
}
if oldBefore == nil {
return nil
}
return oldBefore(c)
}
}
示例10: main
func main() {
m := martini.Classic()
m.Map(SetupDB())
m.Get("/", func() string { return "Welcome to GoSQL database" })
m.Get("/var", func() string {
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
fmt.Println(pair[0])
}
return "hello"
})
m.Get("/show", ShowDB)
m.Get("/print1", func() string { return os.Getenv("POSTGRESDB_SERVICE_HOST") })
m.Get("/print4", func() string { return os.Getenv("OPENSHIFT_POSTGRESQL_PASSWORD") })
m.Get("/print5", func() string { return os.Getenv("OPENSHIFT_POSTGRESQL_USER") })
m.Get("/print6", func() string { return os.Getenv("POSTGRESQL_USER") })
m.Get("/var", func() string {
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
fmt.Println(pair[0])
}
return "yo"
})
m.Post("/add", InsertPur)
m.RunOnAddr(":8080")
}
示例11: compile
func compile(w *World) *bytes.Buffer {
ioutil.WriteFile(TEMPPATH+".go", []byte(w.source()), 0644)
err := new(bytes.Buffer)
re, e, _ := os.Pipe()
os.ForkExec(
bin+"/"+arch+"g",
[]string{bin + "/" + arch + "g", "-o", TEMPPATH + ".6", TEMPPATH + ".go"},
os.Environ(),
"",
[]*os.File{nil, e, nil})
e.Close()
io.Copy(err, re)
if err.Len() > 0 {
return err
}
re, e, _ = os.Pipe()
os.ForkExec(
bin+"/"+arch+"l",
[]string{bin + "/" + arch + "l", "-o", TEMPPATH + "", TEMPPATH + ".6"},
os.Environ(),
"",
[]*os.File{nil, e, nil})
e.Close()
io.Copy(err, re)
return err
}
示例12: build
//to build the project with gobuild or make after generating .go source files
func build(b int, s string) (err os.Error) {
p := strings.Fields(s)
params := make([]string, len(p)+1)
params[0] = ""
for i, param := range p {
params[i+1] = param
}
m := b == MAKE
g := b == GOBUILD
//fd := []*os.File{os.Stdin, os.Stdout, os.Stderr}
if m {
err = os.Exec("/usr/bin/make", params, os.Environ())
if err != nil {
panic("Cannot call make")
}
} else if g {
gobuild := os.Getenv("GOBIN")
if len(gobuild) == 0 {
gobuild = path.Join(os.Getenv("HOME"), "bin", "gobuild")
} else {
gobuild = path.Join(gobuild, "gobuild")
}
err := os.Exec(gobuild, params, os.Environ())
if err != nil {
panic("Cannot call gobuild")
}
}
return
}
示例13: TestRunHookExceptional
func (s *DebugHooksServerSuite) TestRunHookExceptional(c *gc.C) {
err := ioutil.WriteFile(s.ctx.ClientFileLock(), []byte{}, 0777)
c.Assert(err, gc.IsNil)
session, err := s.ctx.FindSession()
c.Assert(session, gc.NotNil)
c.Assert(err, gc.IsNil)
// Run the hook in debug mode with no exit flock held.
// The exit flock will be acquired immediately, and the
// debug-hooks server process killed.
err = session.RunHook("myhook", s.tmpdir, os.Environ())
c.Assert(err, gc.ErrorMatches, "signal: [kK]illed")
// Run the hook in debug mode, simulating the holding
// of the exit flock. This simulates the client process
// starting but not cleanly exiting (normally the .pid
// file is updated, and the server waits on the client
// process' death).
ch := make(chan bool)
var clientExited bool
s.PatchValue(&waitClientExit, func(*ServerSession) {
clientExited = <-ch
})
go func() { ch <- true }()
err = session.RunHook("myhook", s.tmpdir, os.Environ())
c.Assert(clientExited, jc.IsTrue)
c.Assert(err, gc.ErrorMatches, "signal: [kK]illed")
}
示例14: TestIsMaster
func TestIsMaster(t *testing.T) {
origEnv := make([]string, len(os.Environ()))
copy(origEnv, os.Environ())
for _, v := range []struct {
env string
expect bool
}{
{miyabi.FDEnvKey, false},
{"UNKNOWN_KEY", true},
} {
func() {
defer func() {
os.Clearenv()
for _, v := range origEnv {
env := strings.SplitN(v, "=", 2)
os.Setenv(env[0], env[1])
}
}()
if err := os.Setenv(v.env, "1"); err != nil {
t.Error(err)
return
}
actual := miyabi.IsMaster()
expect := v.expect
if !reflect.DeepEqual(actual, expect) {
t.Errorf(`IsMaster() with %v=1 => %#v; want %#v`, v.env, actual, expect)
}
}()
}
}
示例15: emitError
// Emit error.
func emitError(cmd []string, err error, errorHandlers []errorhandlers.Handler) {
// Construct the error.
timestamp := time.Now().UTC()
hostname, _ := os.Hostname()
environ := make(map[string]string, len(os.Environ()))
for _, env := range os.Environ() {
var k, v string
equalPos := strings.IndexByte(env, '=')
if equalPos == -1 {
k = env
} else {
k = env[:equalPos]
v = env[equalPos+1:]
}
environ[k] = v
}
errMsg := &errorhandlers.Error{
Cmd: cmd,
Desc: err.Error(),
Hostname: hostname,
Environ: environ,
Timestamp: timestamp,
}
// Emit the error.
for _, h := range errorHandlers {
if err := h.Handle(errMsg); err != nil {
fmt.Fprintf(os.Stderr, "Failed to send error message: %s\n", err)
}
}
}