当前位置: 首页>>代码示例>>Golang>>正文


Golang exec.Command函数代码示例

本文整理汇总了Golang中os/exec.Command函数的典型用法代码示例。如果您正苦于以下问题:Golang Command函数的具体用法?Golang Command怎么用?Golang Command使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Command函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestTrustedPushWithExpiredSnapshot

func (s *DockerTrustSuite) TestTrustedPushWithExpiredSnapshot(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := fmt.Sprintf("%v/dockercliexpiredsnapshot/trusted:latest", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	// Push with default passphrases
	pushCmd := exec.Command(dockerBinary, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err := runCommandWithOutput(pushCmd)
	if err != nil {
		c.Fatalf("trusted push failed: %s\n%s", err, out)
	}

	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
		c.Fatalf("Missing expected output on trusted push:\n%s", out)
	}

	// Snapshots last for three years. This should be expired
	fourYearsLater := time.Now().Add(time.Hour * 24 * 365 * 4)

	runAtDifferentDate(fourYearsLater, func() {
		// Push with wrong passphrases
		pushCmd = exec.Command(dockerBinary, "push", repoName)
		s.trustedCmd(pushCmd)
		out, _, err = runCommandWithOutput(pushCmd)
		if err == nil {
			c.Fatalf("Error missing from trusted push with expired snapshot: \n%s", out)
		}

		if !strings.Contains(string(out), "repository out-of-date") {
			c.Fatalf("Missing expected output on trusted push with expired snapshot:\n%s", out)
		}
	})
}
开发者ID:ranid,项目名称:docker,代码行数:35,代码来源:docker_cli_push_test.go

示例2: TestBuildCacheADD

func TestBuildCacheADD(t *testing.T) {
	buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildCacheADD", "1")
	buildCmd := exec.Command(dockerBinary, "build", "-t", "testcacheadd1", ".")
	buildCmd.Dir = buildDirectory
	exitCode, err := runCommand(buildCmd)
	errorOut(err, t, fmt.Sprintf("build failed to complete: %v", err))

	if err != nil || exitCode != 0 {
		t.Fatal("failed to build the image")
	}

	buildDirectory = filepath.Join(workingDirectory, "build_tests", "TestBuildCacheADD", "2")
	buildCmd = exec.Command(dockerBinary, "build", "-t", "testcacheadd2", ".")
	buildCmd.Dir = buildDirectory
	out, exitCode, err := runCommandWithOutput(buildCmd)
	errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))

	if err != nil || exitCode != 0 {
		t.Fatal("failed to build the image")
	}

	if strings.Contains(out, "Using cache") {
		t.Fatal("2nd build used cache on ADD, it shouldn't")
	}

	deleteImages("testcacheadd1")
	deleteImages("testcacheadd2")

	logDone("build - build two images with ADD")
}
开发者ID:GloriaH,项目名称:docker,代码行数:30,代码来源:docker_cli_build_test.go

示例3: ForceUnmount

// ForceUnmount attempts to forcibly unmount a given mount.
// It does so by calling diskutil or fusermount directly.
func ForceUnmount(m Mount) error {
	point := m.MountPoint()
	log.Warningf("Force-Unmounting %s...", point)

	var cmd *exec.Cmd
	switch runtime.GOOS {
	case "darwin":
		cmd = exec.Command("diskutil", "umount", "force", point)
	case "linux":
		cmd = exec.Command("fusermount", "-u", point)
	default:
		return fmt.Errorf("unmount: unimplemented")
	}

	errc := make(chan error, 1)
	go func() {
		defer close(errc)

		// try vanilla unmount first.
		if err := exec.Command("umount", point).Run(); err == nil {
			return
		}

		// retry to unmount with the fallback cmd
		errc <- cmd.Run()
	}()

	select {
	case <-time.After(7 * time.Second):
		return fmt.Errorf("umount timeout")
	case err := <-errc:
		return err
	}
}
开发者ID:rdterner,项目名称:go-ipfs,代码行数:36,代码来源:mount.go

示例4: TestStatStdin

func TestStatStdin(t *testing.T) {
	switch runtime.GOOS {
	case "android", "plan9":
		t.Skipf("%s doesn't have /bin/sh", runtime.GOOS)
	}

	testenv.MustHaveExec(t)

	if Getenv("GO_WANT_HELPER_PROCESS") == "1" {
		st, err := Stdin.Stat()
		if err != nil {
			t.Fatalf("Stat failed: %v", err)
		}
		fmt.Println(st.Mode() & ModeNamedPipe)
		Exit(0)
	}

	var cmd *osexec.Cmd
	if runtime.GOOS == "windows" {
		cmd = osexec.Command("cmd", "/c", "echo output | "+Args[0]+" -test.run=TestStatStdin")
	} else {
		cmd = osexec.Command("/bin/sh", "-c", "echo output | "+Args[0]+" -test.run=TestStatStdin")
	}
	cmd.Env = append(Environ(), "GO_WANT_HELPER_PROCESS=1")

	output, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("Failed to spawn child process: %v %q", err, string(output))
	}

	// result will be like "prw-rw-rw"
	if len(output) < 1 || output[0] != 'p' {
		t.Fatalf("Child process reports stdin is not pipe '%v'", string(output))
	}
}
开发者ID:duhaibo0404,项目名称:go-1,代码行数:35,代码来源:os_test.go

示例5: TestPushRepoWithSingleTag

func TestPushRepoWithSingleTag(t *testing.T) {
	var cmd *exec.Cmd
	var err error
	var out string

	reponame := "busybox"
	repotag := "latest"
	repoBase := reponame + ":" + repotag

	repoDest := Domains + "/" + UserName + "/" + repoBase
	cmd = exec.Command(DockerBinary, "tag", "-f", repoBase, repoDest)
	if out, err = ParseCmdCtx(cmd); err != nil {
		t.Fatalf("Tag %v failed: [Info]%v, [Error]%v", repoBase, out, err)
	}

	//push the same repository with specified tag more than once to cover related code processing branch
	for i := 1; i <= 2; i++ {
		cmd = exec.Command(DockerBinary, "push", repoDest)
		if out, err = ParseCmdCtx(cmd); err != nil {
			t.Fatalf("Push %v failed: [Info]%v, [Error]%v", repoDest, out, err)
		}
	}

	cmd = exec.Command(DockerBinary, "rmi", repoDest)
	out, err = ParseCmdCtx(cmd)
}
开发者ID:CodeJuan,项目名称:dockyard,代码行数:26,代码来源:push_test.go

示例6: verifyCertWithSystem

func verifyCertWithSystem(block *pem.Block, add func(*Certificate)) {
	data := pem.EncodeToMemory(block)
	var cmd *exec.Cmd
	if needsTmpFiles() {
		f, err := ioutil.TempFile("", "cert")
		if err != nil {
			fmt.Fprintf(os.Stderr, "can't create temporary file for cert: %v", err)
			return
		}
		defer os.Remove(f.Name())
		if _, err := f.Write(data); err != nil {
			fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err)
			return
		}
		if err := f.Close(); err != nil {
			fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err)
			return
		}
		cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", f.Name(), "-l")
	} else {
		cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", "/dev/stdin", "-l")
		cmd.Stdin = bytes.NewReader(data)
	}
	if cmd.Run() == nil {
		// Non-zero exit means untrusted
		cert, err := ParseCertificate(block.Bytes)
		if err != nil {
			return
		}

		add(cert)
	}
}
开发者ID:oshimaya,项目名称:go,代码行数:33,代码来源:root_darwin.go

示例7: TestTags

// TestTags verifies that the -tags argument controls which files to check.
func TestTags(t *testing.T) {
	// go build
	cmd := exec.Command("go", "build", "-o", binary)
	run(cmd, t)

	// defer removal of vet
	defer os.Remove(binary)

	args := []string{
		"-tags=testtag",
		"-v", // We're going to look at the files it examines.
		"testdata/tagtest",
	}
	cmd = exec.Command("./"+binary, args...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatal(err)
	}
	// file1 has testtag and file2 has !testtag.
	if !bytes.Contains(output, []byte(filepath.Join("tagtest", "file1.go"))) {
		t.Error("file1 was excluded, should be included")
	}
	if bytes.Contains(output, []byte(filepath.Join("tagtest", "file2.go"))) {
		t.Error("file2 was included, should be excluded")
	}
}
开发者ID:suifengRock,项目名称:golang-tools,代码行数:27,代码来源:vet_test.go

示例8: runInstall

func runInstall(image, installType, cloudConfig, device string, force, reboot bool) error {
	in := bufio.NewReader(os.Stdin)

	fmt.Printf("Installing from %s\n", image)

	if !force {
		if !yes(in, "Continue") {
			os.Exit(1)
		}
	}

	if installType == "generic" {
		cmd := exec.Command("system-docker", "run", "--net=host", "--privileged", "--volumes-from=all-volumes",
			"--entrypoint=/scripts/set-disk-partitions", image, device)
		cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
		if err := cmd.Run(); err != nil {
			return err
		}
	}
	cmd := exec.Command("system-docker", "run", "--net=host", "--privileged", "--volumes-from=user-volumes", image,
		"-d", device, "-t", installType, "-c", cloudConfig)
	cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}

	if reboot && yes(in, "Continue with reboot") {
		log.Info("Rebooting")
		power.Reboot()
	}

	return nil
}
开发者ID:pirater,项目名称:os,代码行数:33,代码来源:install.go

示例9: setupRamDisk

func setupRamDisk(path string) error {
	// err := exec.Command("umount", "-f", path).Run()
	// if err == nil {
	//   log.Printf("Unmounted ramdisk at %s - you may want to eject it!", path)
	// }

	// 1 MB
	diskPath, err := exec.Command("hdiutil", "attach", "-nomount", "ram://2048").Output()
	if err != nil {
		log.Fatal("Creating ramdisk: ", err)
	}
	diskPathStr := strings.TrimSpace(string(diskPath))
	log.Printf("Created ramdisk at %s", diskPathStr)

	err = exec.Command("newfs_hfs", diskPathStr).Run()
	if err != nil {
		log.Fatal("Formatting ramdisk: ", err)
	}
	log.Printf("Formatted ramdisk as HFS.")

	if _, err := os.Stat(path); os.IsNotExist(err) {
		err = os.Mkdir(path, 0700)
		if err != nil {
			log.Fatal("Making dir for ramdisk: ", err)
		}
	}

	err = exec.Command("mount", "-t", "hfs", diskPathStr, path).Run()
	if err != nil {
		log.Fatal("Mounting ramdisk: ", err)
	}
	log.Printf("Ramdisk mounted at %s", path)

	return nil
}
开发者ID:jeisc,项目名称:sneakynote.com,代码行数:35,代码来源:store_darwin.go

示例10: checkPackage

func (spec SpecPackage) checkPackage(defaults PlatformDefaults) (err error) {
	var cmd *exec.Cmd

	switch spec.Type {
	case "rpm":
		rpm, err := exec.LookPath("rpm")
		if err != nil {
			return err
		}
		cmd = exec.Command(rpm, "-q", spec.Name)
	case "dpkg":
		dpkg, err := exec.LookPath("dpkg")
		if err != nil {
			return err
		}
		cmd = exec.Command(dpkg, "-L", spec.Name)
	case "pacman":
		// TODO
	case "ebuild":
		// TODO
	case "homebrew":
		cmd = exec.Command("/usr/local/bin/brew", "ls", spec.Name)
	case "gem":
		cmd = exec.Command("/bin/bash", "-ic", "gem contents "+spec.Name)
	default:
		return errors.New("Unknown package manager type " + spec.Type)
	}

	err = cmd.Run()
	if err != nil && !spec.Absent {
		return err
	} else {
		return nil
	}
}
开发者ID:vivus-ignis,项目名称:libnodespec,代码行数:35,代码来源:spec_package.go

示例11: main

func main() {
	c1 := exec.Command("df", "-h")
	c2 := exec.Command("sort")

	r, err := c1.StdoutPipe()
	if err != nil {
		fmt.Println("failed to create pipe:", err)
		return
	}
	defer r.Close()

	c1.Stdin = os.Stdin
	c1.Stderr = os.Stderr

	// the stdout of c1 feeds the stdin of c2
	c2.Stdin = r
	c2.Stdout = os.Stdout
	c2.Stderr = os.Stderr

	err = c1.Start()
	if err != nil {
		fmt.Println("process #1 failed to start:", err)
	}

	// we Wait on c1 to clean up its process entry when done
	// (otherwise, it'll remain as a zombie process until this process exits)
	defer c1.Wait()

	err = c2.Run()
	if err != nil {
		fmt.Println("process #2 failed:", err)
	}
}
开发者ID:bsreera,项目名称:gotraining,代码行数:33,代码来源:pipeline.go

示例12: TestCommitAfterContainerIsDone

func TestCommitAfterContainerIsDone(t *testing.T) {
	runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "echo", "foo")
	out, _, _, err := runCommandWithStdoutStderr(runCmd)
	errorOut(err, t, fmt.Sprintf("failed to run container: %v %v", out, err))

	cleanedContainerID := stripTrailingCharacters(out)

	waitCmd := exec.Command(dockerBinary, "wait", cleanedContainerID)
	_, _, err = runCommandWithOutput(waitCmd)
	errorOut(err, t, fmt.Sprintf("error thrown while waiting for container: %s", out))

	commitCmd := exec.Command(dockerBinary, "commit", cleanedContainerID)
	out, _, err = runCommandWithOutput(commitCmd)
	errorOut(err, t, fmt.Sprintf("failed to commit container to image: %v %v", out, err))

	cleanedImageID := stripTrailingCharacters(out)

	inspectCmd := exec.Command(dockerBinary, "inspect", cleanedImageID)
	out, _, err = runCommandWithOutput(inspectCmd)
	errorOut(err, t, fmt.Sprintf("failed to inspect image: %v %v", out, err))

	deleteContainer(cleanedContainerID)
	deleteImages(cleanedImageID)

	logDone("commit - echo foo and commit the image")
}
开发者ID:vettery,项目名称:docker,代码行数:26,代码来源:docker_cli_commit_test.go

示例13: TestPushInterrupt

func (s *DockerRegistrySuite) TestPushInterrupt(c *check.C) {
	repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	pushCmd := exec.Command(dockerBinary, "push", repoName)
	if err := pushCmd.Start(); err != nil {
		c.Fatalf("Failed to start pushing to private registry: %v", err)
	}

	// Interrupt push (yes, we have no idea at what point it will get killed).
	time.Sleep(50 * time.Millisecond) // dependent on race condition.
	if err := pushCmd.Process.Kill(); err != nil {
		c.Fatalf("Failed to kill push process: %v", err)
	}
	if out, _, err := dockerCmdWithError("push", repoName); err == nil {
		if !strings.Contains(out, "already in progress") {
			c.Fatalf("Push should be continued on daemon side, but seems ok: %v, %s", err, out)
		}
	}
	// now wait until all this pushes will complete
	// if it failed with timeout - there would be some error,
	// so no logic about it here
	for exec.Command(dockerBinary, "push", repoName).Run() != nil {
	}
}
开发者ID:ranid,项目名称:docker,代码行数:26,代码来源:docker_cli_push_test.go

示例14: TestTrustedPushWithExpiredTimestamp

func (s *DockerTrustSuite) TestTrustedPushWithExpiredTimestamp(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := fmt.Sprintf("%v/dockercliexpiredtimestamppush/trusted:latest", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	// Push with default passphrases
	pushCmd := exec.Command(dockerBinary, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err := runCommandWithOutput(pushCmd)
	if err != nil {
		c.Fatalf("trusted push failed: %s\n%s", err, out)
	}

	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
		c.Fatalf("Missing expected output on trusted push:\n%s", out)
	}

	// The timestamps expire in two weeks. Lets check three
	threeWeeksLater := time.Now().Add(time.Hour * 24 * 21)

	// Should succeed because the server transparently re-signs one
	runAtDifferentDate(threeWeeksLater, func() {
		pushCmd := exec.Command(dockerBinary, "push", repoName)
		s.trustedCmd(pushCmd)
		out, _, err := runCommandWithOutput(pushCmd)
		if err != nil {
			c.Fatalf("Error running trusted push: %s\n%s", err, out)
		}
		if !strings.Contains(string(out), "Signing and pushing trust metadata") {
			c.Fatalf("Missing expected output on trusted push with expired timestamp:\n%s", out)
		}
	})
}
开发者ID:ranid,项目名称:docker,代码行数:34,代码来源:docker_cli_push_test.go

示例15: TestExecStopNotHanging

func (s *DockerSuite) TestExecStopNotHanging(c *check.C) {
	dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")

	if err := exec.Command(dockerBinary, "exec", "testing", "top").Start(); err != nil {
		c.Fatal(err)
	}

	type dstop struct {
		out []byte
		err error
	}

	ch := make(chan dstop)
	go func() {
		out, err := exec.Command(dockerBinary, "stop", "testing").CombinedOutput()
		ch <- dstop{out, err}
		close(ch)
	}()
	select {
	case <-time.After(3 * time.Second):
		c.Fatal("Container stop timed out")
	case s := <-ch:
		c.Assert(s.err, check.IsNil)
	}
}
开发者ID:ch3lo,项目名称:docker,代码行数:25,代码来源:docker_cli_exec_test.go


注:本文中的os/exec.Command函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。