如何在Swift 3 for Linux中使用Process()?

时间:2021-12-12 20:56:45

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.

以下函数在macOS上的Swift 3中执行一个进程。但是如果我在Ubuntu中运行相同的代码,我会得到Process是一个未解析的标识符的错误。

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

如何在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 个解决方案

#1


6  

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.

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

#2


2  

Try replacing Process with CommandLine. See this github issue and this SO question

尝试使用CommandLine替换Process。看到这个github问题和这个问题

#1


6  

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.

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

#2


2  

Try replacing Process with CommandLine. See this github issue and this SO question

尝试使用CommandLine替换Process。看到这个github问题和这个问题