我更新了 hbowie 的答案,将从 shell 接收到的值作为字符串返回:
func safeShell(_ strExecutable:String, _ arrArguments:Array<String>) throws -> String {
let task = Process()
let pipe = Pipe()
let bundle = Bundle.main
let execURL = bundle.url(forResource: strExecutable, withExtension: nil)
//no point in going on if we can't find the program
guard execURL != nil else {
print("\(strExecutable) executable could not be found!")
return ""
}
task.executableURL = execURL!
task.arguments = arrArguments
task.standardOutput = pipe
task.standardError = pipe
//task.arguments = ["-c", command]
//task.executableURL = URL(fileURLWithPath: "/bin/zsh") //<--updated
do {
try task.run() //<--updated
}
catch{ throw error }
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output
}
}
使用示例:
let strOutput = try myAppManager.safeShell("pandoc", ["--version"])
print(strOutput)
回报:
pandoc 2.16.2
Compiled with pandoc-types 1.22.1, texmath 0.12.3.2, skylighting 0.12.1,
citeproc 0.6, ipynb 0.1.0.2
User data directory: /Users/stevesuranie/Library/Containers/MartianTribe.MD2HTML/Data/.local/share/pandoc
Copyright (C) 2006-2021 John MacFarlane. Web: https://pandoc.org
This is free software; see the source for copying conditions. There is no
warranty, not even for merchantability or fitness for a particular purpose.