How to execute external program from Swift?

前端 未结 2 1758
后悔当初
后悔当初 2020-12-10 05:09

I am new in Swift and I did not found anything about executing external programs or access external processes using Swing language.

Is it possible to do in the curr

2条回答
  •  臣服心动
    2020-12-10 05:34

    Improved version of Rob's answer (in that you don't need to specify the full path of your executable), and also updated for Swift 3:

    import Foundation
    
    func execCommand(command: String, args: [String]) -> String {
        if !command.hasPrefix("/") {
            let commandFull = execCommand(command: "/usr/bin/which", args: [command]).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
            return execCommand(command: commandFull, args: args)
        } else {
            let proc = Process()
            proc.launchPath = command
            proc.arguments = args
            let pipe = Pipe()
            proc.standardOutput = pipe
            proc.launch()
            let data = pipe.fileHandleForReading.readDataToEndOfFile()
            return String(data: data, encoding: String.Encoding.utf8)!
        }
    }
    

提交回复
热议问题