2016-09-29 50 views
7

以下函數在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 "" 
} 

回答

2

嘗試用CommandLine代替Process。看到這個github上issueSO question

+0

這是另一回事。在Swift 3中,'(NS)Task'被重命名爲'Process',並且'Process'命名爲'CommandLine'。這個問題 - 據我瞭解 - 是關於前者。 –

相關問題