本文整理汇总了Golang中os/exec.Cmd.Output方法的典型用法代码示例。如果您正苦于以下问题:Golang Cmd.Output方法的具体用法?Golang Cmd.Output怎么用?Golang Cmd.Output使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os/exec.Cmd
的用法示例。
在下文中一共展示了Cmd.Output方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ShellExec
func ShellExec(cmd *exec.Cmd) []byte {
stdout, err := cmd.Output()
if err != nil {
log.Fatalln(err)
}
return stdout
}
示例2: Log
// Log returns an array of Commit objects, representing the history as like
// git log. Newest commit is at index zero, oldest at the end. Leave hashish
// as a blank string to get the default "git log" result.
func Log(path, hashish string) ([]*Commit, error) {
logFormat := "%H" // Just the hashes
var cmd *exec.Cmd
if hashish == "" {
cmd = command("git", "log", "--pretty="+logFormat)
} else {
cmd = command("git", "log", "--pretty="+logFormat, hashish)
}
cmd.Dir = path
output, err := cmd.Output()
if err != nil {
return []*Commit{}, err
}
lineBytes := bytes.Split(output, []byte{'\n'})
// The last split is just an empty string, right?
lineBytes = lineBytes[0 : len(lineBytes)-1]
commits := make([]*Commit, len(lineBytes))
for x := 0; x < len(lineBytes); x++ {
commit, commitErr := NewCommit(path, string(lineBytes[x]))
if commitErr != nil {
return []*Commit{}, commitErr
}
commits[x] = commit
}
return commits, nil
}
示例3: mustGetOutput
func mustGetOutput(c *exec.Cmd) []byte {
b, err := c.Output()
if err != nil {
panic(err)
}
return b
}
示例4: getOutputLine
func getOutputLine(cmd *exec.Cmd) (string, error) {
out, err := cmd.Output()
if err != nil {
return "", err
}
return strings.Trim(string(out), " \n\t\r"), nil
}
示例5: TestConstants
/* Checks if the constants are equal to the ones in Python by running the python interpreter.
Also exercises the New(), Join() and Encode() functions.
*/
func TestConstants(t *testing.T) {
var shouldBeBytes []byte
var cmd *exec.Cmd
constants := []string{"ascii_letters", "ascii_lowercase", "ascii_uppercase", "digits", "hexdigits", "octdigits", "punctuation", "printable", "whitespace"}
shouldbe := []string{ASCII_letters, ASCII_lowercase, ASCII_uppercase, Digits, HexDigits, OctDigits, Punctuation, Printable, Whitespace}
for i, constant := range constants {
// Make sure to use python3. Tested on Fedora and Arch Linux.
cmd = exec.Command("python3", "-c", "import string; print(string."+constant+")")
output, err := cmd.Output()
if err != nil {
/* One of the commands failed, assume Python is not available */
// This can be used if one doesn't want to ignore the lack of python:
//t.Errorf("execution failed: %s %s\n", New(" ").Join(cmd.Args), output)
return
}
shouldBeBytes = New(shouldbe[i]).Encode()
for i2, b := range shouldBeBytes {
if (i2 >= len(output)) || (b != output[i2]) {
if len(output) == 0 {
output = New("no output").Encode()
}
t.Errorf("constant %s failed, got: %s\n", constants[i], output)
return
}
}
}
}
示例6: bExec
// Utility Functions
func bExec(cmd exec.Cmd) (out []byte) {
out, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
return
}
示例7: pluginInfo
func pluginInfo(name string) (ver, short, long string) {
if os.Getenv("HKPLUGINMODE") == "info" {
return "", "plugin exec loop", "plugin exec loop"
}
short = "no description"
long = name + ": unknown description"
var cmd exec.Cmd
cmd.Args = []string{name}
cmd.Path = lookupPlugin(name)
cmd.Env = append([]string{"HKPLUGINMODE=info"}, os.Environ()...)
buf, err := cmd.Output()
if err != nil {
return
}
info := string(buf)
if !strings.HasPrefix(info, name+" ") {
return
}
info = info[len(name)+1:]
i := strings.Index(info, ": ")
if i < 0 {
return
}
ver, info = info[:i], info[i+2:]
i = strings.Index(info, "\n\n")
if i < 0 || 50 < i || strings.Contains(info[:i], "\n") {
return
}
short, long = info[:i], info[i+2:]
return ver, strings.TrimSpace(short), strings.TrimSpace(long)
}
示例8: GetWireDefaultGateway
func GetWireDefaultGateway() (net.IP, error) {
var regex *regexp.Regexp
var command *exec.Cmd
switch runtime.GOOS {
case "darwin":
command = exec.Command("netstat", "-rn", "-f", "inet")
regex = regexp.MustCompile(`default\s+(\d+\.\d+\.\d+\.\d+)\s+.*`)
case "linux":
command = exec.Command("ip", "-4", "route", "show")
regex = regexp.MustCompile(`default\s+via\s+(\d+\.\d+\.\d+\.\d+)\s+.*`)
default:
return nil, fmt.Errorf("Getting gateway is not supported in %v", runtime.GOOS)
}
output, err := command.Output()
if err != nil {
return nil, err
}
if result := regex.FindSubmatch(output); result == nil {
return nil, fmt.Errorf("Unable to get default gateway")
} else {
return net.ParseIP(string(result[1])), nil
}
}
示例9: checkVersionPackageExact
func (spec SpecPackage) checkVersionPackageExact(defaults PlatformDefaults) (err error) {
var cmd *exec.Cmd
var verRex string
switch spec.Type {
case "homebrew":
// sbt 0.12.3 0.12.4 0.13.0
cmd = exec.Command("/usr/local/bin/brew", "ls", "--versions", spec.Name)
verRex = " " + spec.Version + "( |$)"
default:
return errors.New("Unknown package manager type " + spec.Type)
}
out, err := cmd.Output()
if err != nil {
return err
}
re, err := regexp.Compile(verRex)
if err != nil {
return fmt.Errorf("Bad verRex %s for package manager type %s", verRex, spec.Type)
}
if re.FindIndex(out) == nil && !spec.Absent {
return errors.New("No such version installed")
}
return nil
}
示例10: worker
func worker(throttle chan struct{}, wg *sync.WaitGroup, e fsnotify.Op, f string) {
defer func() {
<-throttle
wg.Done()
}()
m := findMatch(e, f)
if m == nil {
return
}
// Atomicity for the given match
m.mu.Lock()
defer m.mu.Unlock()
var cmd *exec.Cmd
for i, c := range m.cmds {
if len(c) == 1 {
cmd = exec.Command(c[0])
} else {
cmd = exec.Command(c[0], c[1:]...)
}
if b, err := cmd.Output(); err != nil {
log.Printf("command (%s) error: %s", c, err)
} else if len(b) > 0 {
log.Printf("%s\n%s", m.rule.cmds[i], b)
}
}
}
示例11: add
// stem words and add them to vocabulary
func (vocabulary Dictionary) add(words []string, mode string) (wordIDs []int) {
var lemma string
wordIDs = make([]int, len(words))
for idx, word := range words {
if _, ok := vocabulary.Vtoi[word]; ok {
wordIDs[idx] = vocabulary.Vtoi[word]
} else {
python := new(exec.Cmd)
args := []string{"lemmatizer.py", "--vocabulary"}
args = append(args, word)
args = append(args, "--pos")
args = append(args, mode)
python.Args = args
// python.Path = "/home/lea/Code/Python/lemmatizer.py"
python.Path = "/local/lea/thesis/python/lemmatizer.py"
out, _ := python.Output()
lemma = strings.Trim(string(out), "\n")
if _, ok := vocabulary.Vtoi[lemma]; !ok {
vocabulary.VList[vocabIdx] = lemma
vocabulary.Vtoi[lemma] = vocabIdx
vocabulary.Itov[vocabIdx] = lemma
vocabulary.POSList[vocabIdx] = mode
vocabIdx++
}
wordIDs[idx] = vocabulary.Vtoi[lemma]
}
}
return wordIDs
}
示例12: Recon
func Recon(pkgPath string) (pkgInfo *PkgInfo, err error) {
var gitProgPath, pkgPathAbs string
// Firstly look up if they've got Git
gitProgPath, err = exec.LookPath("git")
if err != nil {
return
}
pkgPathAbs = goSrcify(pkgPath)
args := []string{gitProgPath}
args = append(args, prettyGitHashGetArgs...)
cmd := exec.Cmd{
Args: args,
Dir: pkgPathAbs,
Path: gitProgPath,
}
var output []byte
if output, err = cmd.Output(); err != nil {
return
}
pkgInfo = &PkgInfo{
CommitHash: string(output),
OsInfo: strings.Join([]string{runtime.GOOS, runtime.GOARCH}, "/"),
GoVersion: runtime.Version(),
}
return
}
示例13: executeCommand
func executeCommand(targetPath string, command string) (logContent string, err error) {
logBuffer := new(bytes.Buffer)
defer func() {
logContent = logBuffer.String()
}()
bufferLog(logBuffer, separator)
bufferLog(logBuffer, "\nEntry into target Path: %s\n", targetPath)
err = os.Chdir(targetPath)
if err != nil {
bufferLog(logBuffer, "ChdirError (%s): %s\n", targetPath, err)
return "", err
}
cmdWithArgs := strings.Split(command, " ")
var cmd *exec.Cmd
cmdLength := len(cmdWithArgs)
realCmd := cmdWithArgs[0]
args := cmdWithArgs[1:cmdLength]
bufferLog(logBuffer, "Execute command (cmd=%s, args=%s)...\n", realCmd, args)
if cmdLength > 1 {
cmd = exec.Command(realCmd, args...)
} else {
cmd = exec.Command(realCmd)
}
result, err := cmd.Output()
if err != nil {
bufferLog(logBuffer, "CmdRunError (cmd=%s, args=%v): %s\n", realCmd, args, err)
return "", err
}
bufferLog(logBuffer, "Output: %v\n", string(result))
return "", nil
}
示例14: pluginInfo
func pluginInfo(name string) (ver, short, long string) {
if os.Getenv("HKPLUGINMODE") == "info" {
return "", "[plugin exec loop]", "[plugin exec loop]\n"
}
var cmd exec.Cmd
cmd.Args = []string{name}
cmd.Path = lookupPlugin(name)
cmd.Env = append([]string{"HKPLUGINMODE=info"}, os.Environ()...)
buf, err := cmd.Output()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return "", "[unknown description]", "[unknown description]\n"
}
info := string(buf)
if !strings.HasPrefix(info, name+" ") {
return "", "[unknown description]", "[unknown description]\n"
}
info = info[len(name)+1:]
i := strings.Index(info, ": ")
ver, info = info[:i], info[i+2:]
i = strings.Index(info, "\n\n")
short, long = info[:i], info[i+2:]
if len(short) > 50 || strings.Contains(short, "\n") {
return "", "[unknown description]", "[unknown description]\n"
}
return ver, short, long
}
示例15: ExecShellScriptOrPanic
/**
* Execute command inside shell on linux or windows
*/
func ExecShellScriptOrPanic(args string) string {
var (
shell string
cmd *exec.Cmd
)
switch runtime.GOOS {
case "windows":
shell = "cmd.exe"
cmdArgs := []string{"/C", args}
cmd = exec.Command(shell, cmdArgs...)
break
case "linux":
shell = "bash"
cmdArgs := []string{"-c", args}
cmd = exec.Command(shell, cmdArgs...)
break
default:
panic("Unsupported target OS, unable to exec command !")
break
}
output, err := cmd.Output()
if err != nil {
panic(err)
}
return string(output)
}