Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Process() in Swift 3 for Linux?

The following function executes a process in Swift 3 on macOS. But if I run the same code in Ubuntu I get the error that Process is an unresolved identifier.

How do I run a process / task in Swift 3 for Ubuntu and get its output?

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 ""
}
like image 895
Sebastian Avatar asked Sep 29 '16 08:09

Sebastian


1 Answers

I cannot test it myself currently, but according to the source code https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSTask.swift, the corresponding class is (still) called Task on Linux, not Process as on Apple platforms.

like image 68
Martin R Avatar answered Sep 23 '22 01:09

Martin R