快速执行命令后获取终端输出 [英] Get terminal output after a command swift
问题描述
我使用以下代码在终端中运行一些命令:
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 command, e.g. if I run
system("git status")
我想阅读有关回购中更改的实际信息.有什么办法可以迅速做到这一点?
I want to read the actual information about changes in my repo. Is there any way to do that in swift?
推荐答案
NSTask
是用于将另一个程序作为子进程运行的类.你可以
捕获程序的输出,错误输出,退出状态等等.
NSTask
is class to run another program as a subprocess. You can
capture the program's output, error output, exit status and much more.
扩展我对 xcode 6 swift system()命令的回答, 这是一个简单的实用程序函数,用于同步运行命令, 并返回输出,错误输出和退出代码(现已针对Swift 2更新):
Expanding on my answer to xcode 6 swift system() command, here is a simple utility function to run a command synchronously, and return the output, error output and exit code (now updated for 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, error, 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)
}
或者,如果您仅对输出感兴趣,而对 错误消息或退出代码:
Or, if you are only interested in the output, but not in the error messages or exit code:
let output = runCommand("/usr/bin/git", args: "status").output
输出和错误输出以字符串数组形式返回,一个 每行的字符串.
Output and error output are returned as an array of strings, one string for each line.
runCommand()
的第一个参数必须是指向
可执行文件,例如"/usr/bin/git"
.您可以使用外壳启动程序(system()
也可以这样做):
The first argument to runCommand()
must be the full path to an
executable, such as "/usr/bin/git"
. You can start the program using a shell (which is what system()
also does):
let (output, error, status) = runCommand("/bin/sh", args: "-c", "git status")
优点是可以自动找到"git"可执行文件 通过默认搜索路径.缺点是您必须 如果引号/转义参数包含空格或其他字符,请正确引用/转义 在外壳中具有特殊含义的字符.
The advantage is that the "git" executable is automatically found via the default search path. The disadvantage is that you have to quote/escape arguments correctly if they contain spaces or other characters which have a special meaning in the shell.
更新 Swift 3:
func runCommand(cmd : String, args : String...) -> (output: [String], error: [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, error, status)
}
这篇关于快速执行命令后获取终端输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!