以下函數在macOS上的Swift 3中執行一個進程。但是,如果我在Ubuntu中運行相同的代碼,則會出現Process
是未解決標識符的錯誤。如何在Swift 3 for Linux中使用Process()?
如何在Swift 3中爲Ubuntu運行進程/任務並獲取其輸出?
import Foundation
// runs a Shell command with arguments and returns the output or ""
class func shell(_ command: String, args: [String] = []) -> String {
let task = Process()
task.launchPath = command
task.arguments = args
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String? = String(data: data,
encoding: String.Encoding.utf8)
task.waitUntilExit()
if let output = output {
if !output.isEmpty {
// remove whitespaces and newline from start and end
return output.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
return ""
}
我用'Task'替換了'Process',現在它可以工作。謝謝! – Sebastian