【问题标题】:Swift + terminal斯威夫特+终端
【发布时间】:2017-03-14 16:37:42
【问题描述】:

我正在寻找一种在 Swift (macOS) 中运行终端命令的方法。我遇到了this 的帖子,但我似乎无法让任何解决方案发挥作用。我正在尝试从我的应用程序中关闭我的 mac,就像您可以从终端 (osascript -e 'tell app "loginwindow" to «event aevtrsdn»') 一样,但每当我这样做时,我都会收到错误消息:Couldn't posix_spawn: error 13。

我正在使用此代码:

func shell(launchPath: String, arguments: [String] = []) -> (String? , Int32) {
        let task = Process()
        task.launchPath = launchPath
        task.arguments = arguments

            let pipe = Pipe()
            task.standardOutput = pipe
            task.standardError = pipe
            task.launch()
            let data = pipe.fileHandleForReading.readDataToEndOfFile()
            let output = String(data: data, encoding: .utf8)
            task.waitUntilExit()
            return (output, task.terminationStatus)
        }

我是这样称呼它的:

let z = shell(launchPath: "/usr/bin/osascript", arguments: ["-e", "\'tell app \"loginwindow\" to «event aevtrsdn»\'"])

有什么帮助吗?

【问题讨论】:

    标签: swift


    【解决方案1】:

    您的代码是正确的,但您不能包含第二个参数 单引号:

    let z = shell(launchPath: "/usr/bin/osascript", arguments: ["-e", "tell app \"loginwindow\" to «event aevtrsdn»"])
    

    这仅在从 shell 执行程序时才需要。 Process 将给定的参数直接传递给生成的可执行文件, 无需 shell 解释。

    【讨论】:

      猜你喜欢
      • 2017-07-22
      • 2017-03-24
      • 1970-01-01
      • 2019-02-27
      • 2016-02-08
      • 2017-11-13
      • 2015-08-19
      • 2014-09-11
      • 1970-01-01
      相关资源
      最近更新 更多