system("the command here")
在我想知道运行此命令的结果后,例如如果我跑
system("git status")
我想阅读有关我的回购变更的实际信息.有没有办法在swift中做到这一点?
NSTask是将另一个程序作为子进程运行的类.您可以捕获程序的输出,错误输出,退出状态等等.
扩展我对xcode 6 swift system() command的回答,
这是一个简单的实用程序函数,用于同步运行命令,
并返回输出,错误输出和退出代码(现在更新为Swift 2):
func runcommand(cmd : String,args : String...) -> (output: [String],error: [String],exitCode: Int32) { var output : [String] = [] var error : [String] = [] let task = NSTask() task.launchPath = cmd task.arguments = args let outpipe = NSPipe() task.standardOutput = outpipe let errpipe = NSPipe() task.standardError = errpipe task.launch() let outdata = outpipe.fileHandleForReading.readDataToEndOffile() if var string = String.fromCString(UnsafePointer(outdata.bytes)) { string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()) output = string.componentsSeparatedByString("\n") } let errdata = errpipe.fileHandleForReading.readDataToEndOffile() if var string = String.fromCString(UnsafePointer(errdata.bytes)) { string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()) error = string.componentsSeparatedByString("\n") } task.waitUntilExit() let status = task.terminationStatus return (output,error,status)}
样品用法:
let (output,status) = runcommand("/usr/bin/git",args: "status")print("program exited with status \(status)")if output.count > 0 { print("program output:") print(output)}if error.count > 0 { print("error output:") print(error)}
或者,如果您只对输出感兴趣,而不是对输出感兴趣
错误消息或退出代码:
let output = runcommand("/usr/bin/git",args: "status").output
输出和错误输出作为字符串数组返回,一个
每行的字符串.
runcommand()的第一个参数必须是a的完整路径
可执行文件,例如“/usr/bin/git”.你可以使用shell启动程序(这也是system()也是如此):
let (output,status) = runcommand("/bin/sh",args: "-c","git status")
优点是自动找到“git”可执行文件
通过默认搜索路径.缺点是你必须这样做
如果它们包含空格或其他,则正确引用/转义参数
在shell中具有特殊含义的字符.
Swift 3的更新:
func runcommand(cmd : String,exitCode: Int32) { var output : [String] = [] var error : [String] = [] let task = Process() task.launchPath = cmd task.arguments = args let outpipe = Pipe() task.standardOutput = outpipe let errpipe = Pipe() task.standardError = errpipe task.launch() let outdata = outpipe.fileHandleForReading.readDataToEndOffile() if var string = String(data: outdata,enCoding: .utf8) { string = string.trimmingCharacters(in: .newlines) output = string.components(separatedBy: "\n") } let errdata = errpipe.fileHandleForReading.readDataToEndOffile() if var string = String(data: errdata,enCoding: .utf8) { string = string.trimmingCharacters(in: .newlines) error = string.components(separatedBy: "\n") } task.waitUntilExit() let status = task.terminationStatus return (output,status)}总结
以上是内存溢出为你收集整理的命令swift后获取终端输出全部内容,希望文章能够帮你解决命令swift后获取终端输出所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)