【问题标题】:Creating process with arguments in Swift?在 Swift 中使用参数创建流程?
【发布时间】:2016-11-04 12:13:01
【问题描述】:

在 Swift 3 中执行过程的问题,它不起作用,我单击并没有任何反应。

let open = Process()
open.launchPath = "/usr/bin/openssl"
open.arguments = ["openssl enc -aes-256-cbc -d -in \"" + existing.stringValue +
                 "\" -out \"" + new.stringValue + "/" + name.stringValue + "\""]
open.launch()
open.waitUntilExit()

如何在 Swift 中创建带参数的进程?

【问题讨论】:

  • 您必须将参数作为单独的数组元素传递:open2.arguments = ["enc", "-aes-256-cbc", "d", ...]

标签: swift xcode process openssl command


【解决方案1】:

使用此函数,您可以将参数作为字符串传递。

func shell(at: String, _ args: String) {
    let task = Process()
    task.launchPath = at
    task.arguments = ["-c", args]

    let pipeStandard = Pipe()
    task.standardOutput = pipeStandard
    task.launch()

    let dataStandard = pipeStandard.fileHandleForReading.readDataToEndOfFile()
    let outputStandard = String(data: dataStandard, encoding: String.Encoding.utf8)!
    if outputStandard.count > 0  {
        let lastIndexStandard = outputStandard.index(before: outputStandard.endIndex)
        print(String(outputStandard[outputStandard.startIndex ..< lastIndexStandard]))
    }
    task.waitUntilExit()
}

【讨论】:

  • Task.launch 已弃用,请使用 Task.run()String(data: dataStandard, encoding: String.Encoding.utf8)! 是强制解包,使用 guard let 优雅地处理错误,请参阅 hackingwithswift.com/example-code/system/… 以了解如何执行此操作的体面示例
猜你喜欢
  • 2018-06-27
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多