美文网首页
在swift脚本里执行sh语句

在swift脚本里执行sh语句

作者: KeepYounger | 来源:发表于2019-10-24 16:21 被阅读0次
    //#!/usr/bin/env swift
    
    import Foundation
    
    struct ProcessRunResult{
        let isSuccess: Bool
        let stdError: String
        let stdOutput: String
    }
    
    func cmd(_ launchPath: String, arguments: [String], currentDir: URL? = nil) -> ProcessRunResult{
        let process = Process()
        process.launchPath = launchPath
        process.arguments = arguments
        if let url = currentDir {
            process.currentDirectoryPath = url.path
        }
        
        let errPipe = Pipe()
        let outputPipe = Pipe()
        process.standardError = errPipe
        process.standardOutput = outputPipe
        
        process.launch()
        process.waitUntilExit()
        
        let error = String(data: errPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
        let output = String(data: outputPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
        return ProcessRunResult(isSuccess: process.terminationStatus == 0,
                                stdError: error.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines),
                                stdOutput: output.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))
    }
    
    func which(_ command: String) -> String {
        let result = cmd("/usr/bin/which", arguments: [command])
        return result.stdOutput.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    }
    
    func shell(_ command: String, currentDir: URL? = nil) -> String {
        var args = command.components(separatedBy: CharacterSet.whitespacesAndNewlines)
        let cmdName = which(args.first!)
        args.removeFirst()
        let result = cmd(cmdName, arguments: args, currentDir: currentDir)
        print(result.isSuccess ? result.stdOutput : result.stdError)
        return result.stdOutput
    }
    

    相关文章

      网友评论

          本文标题:在swift脚本里执行sh语句

          本文链接:https://www.haomeiwen.com/subject/faldvctx.html