dongzhu7329
2016-09-27 22:15
浏览 36
已采纳

如何包装交互式命令

I am building an ftp wrapper that does some stuff before I spawn, I could easily do it in a shell script but wondering how I could do it in go

While exec.Command works for simple commands.

out, err := exec.Command("ls").Output() // Works

How do I wrap commands that are interactive e.g., ftp

out, err := exec.Command("ftp").Output()

It just exits. How do I deal with stdin ?

e.g., bash equivalent :

> ./t.sh 
Welcome to myftp 

ftp> open blahblah.com

> cat t.sh 
#!/bin/bash
echo "Welcome to myftp "
#extra commands such as auth/authoriz.. etc.,
shift
echo "$@"
ftp

c++ equivalent :

int main() {
    system("ftp");
    return 0;
}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzao5487 2016-09-28 01:34
    已采纳

    I would probably do something like this which is more native and doesn't involve an external package

    package main
    import (
        "os"
        "os/exec"
    )
    
    func main() {
    
        cmd := exec.Command("ls")
        // redirect the output to terminal
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
    
        cmd.Run()
    
    }
    
    已采纳该答案
    打赏 评论
  • doulin2025 2016-09-28 01:09

    Traditionally these sorts of interactive scripting exercises are best done with expect. May I suggest checking out a pure Go equivalent?

    From the readme:

    child, err := gexpect.Spawn("python")
    if err != nil { panic(err) }
    child.Expect(">>>")
    child.SendLine("print 'Hello World'")
    child.Interact()
    child.Close()
    
    打赏 评论

相关推荐 更多相似问题