3 回答

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果你不在Swift代碼中使用命令輸出,那么下面就足夠了:
#!/usr/bin/env swiftimport Foundation@discardableResultfunc shell(_ args: String...) -> Int32 { let task = Process() task.launchPath = "/usr/bin/env" task.arguments = args task.launch() task.waitUntilExit() return task.terminationStatus}shell("ls")shell("xcodebuild", "-workspace", "myApp.xcworkspace")
更新:適用于Swift3 / Xcode8

TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果您想在命令行中“完全”使用命令行參數(shù)(不分離所有參數(shù)),請嘗試以下操作。
(這個(gè)答案改進(jìn)了LegoLess的答案,可以在Swift 4 Xcode 9.3中使用)
func shell(_ command: String) -> String {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
return output
}
// Example usage:
shell("ls -la")

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
這里的問題是你不能混淆和匹配Bash和Swift。您已經(jīng)知道如何從命令行運(yùn)行Swift腳本,現(xiàn)在需要添加方法以在Swift中執(zhí)行Shell命令。來自PracticalSwift博客的總結(jié):
func shell(launchPath: String, arguments: [String]) -> String?{ let task = Process() task.launchPath = launchPath task.arguments = arguments let pipe = Pipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: String.Encoding.utf8) return output}
以下Swift代碼將xcodebuild
使用參數(shù)執(zhí)行,然后輸出結(jié)果。
shell("xcodebuild", ["-workspace", "myApp.xcworkspace"]);
至于搜索目錄內(nèi)容(這是ls
Bash中的內(nèi)容),我建議NSFileManager
直接在Swift中使用和掃描目錄,而不是Bash輸出,這可能很難解析。
- 3 回答
- 0 關(guān)注
- 2338 瀏覽
添加回答
舉報(bào)