简体   繁体   中英

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 ""
}

我目前无法自己测试,但根据源代码https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSTask.swift ,相应的类在Linux上仍然被称为“ Task ” ,而不是Process为苹果平台。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM