Get terminal output after a command swift

前端 未结 2 1983
离开以前
离开以前 2020-11-28 09:02

I run some commands in terminal with this code:

system(\"the command here\")

And after I want to know what is the result of running this c

2条回答
  •  没有蜡笔的小新
    2020-11-28 09:39

    system spawns a new process so you can’t capture its ouput. The equivalent that gives you a way to do this would be popen, which you could use like this:

    import Darwin
    
    let fp = popen("ping -c 4 localhost", "r")
    var buf = Array(count: 128, repeatedValue: 0)
    
    while fgets(&buf, CInt(buf.count), fp) != nil,
          let str = String.fromCString(buf) {
        print(str)
    }
    
    fclose(fp)
    

    However, don’t do it this way. Use NSTask as Martin describes.

    edit: based on your request to run multiple commands in parallel, here is some probably-unwise code:

    import Darwin
    
    let commands = [
        "tail /etc/hosts",
        "ping -c 2 localhost",
    ]
    
    let fps = commands.map { popen($0, "r") }
    
    var buf = Array(count: 128, repeatedValue: 0)
    
    let results: [String] = fps.map { fp  in
        var result = ""
        while fgets(&buf, CInt(buf.count), fp) != nil,
              let str = String.fromCString(buf) {
            result += str
        }
        return result
    }
    
    fps.map { fclose($0) }
    
    println("\n\n----\n\n".join(map(zip(commands,results)) { "\($0):\n\($1)" }))
    

    (seriously, use NSTask)

提交回复
热议问题