【问题标题】:How to open new app with arguments from swift app using terminal command如何使用终端命令从 swift 应用程序中打开带有参数的新应用程序
【发布时间】:2021-06-18 23:07:00
【问题描述】:

您好,我想在我的应用程序 MacOS 的 swift 代码中使用终端命令打开带有参数的新应用程序

我有终端命令 open -n /Applications/test.app -- args arg1 当我在终端中运行它时,它工作正常

但是当我尝试使用 swift 代码运行它时

 static func shellCommand () {
        
        let task = Process()

        task.launchPath = "/bin/zsh"

        let args:[String] = ["-c","open -n /Applications/test.app","--args aaaa"]

        task.arguments = args
        
        let pipe = Pipe()
        let errorPipe = Pipe()
        task.standardOutput = pipe
        task.standardError = errorPipe
        task.launch()
        task.waitUntilExit()
        
        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: String.Encoding.utf8)!
        let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
        let error = String(decoding: errorData, as: UTF8.self)

        print("out put from shell command \(output) error \(error)")
    }

没用,我也试过了 let args:[String] = ["-c","open -n /Applications/test.app --args arg1"]

感谢您的任何提示或帮助

【问题讨论】:

  • 如果您使用 zsh 启动应用程序,为什么要标记 thsi bash?另外,open 是 Mac 上的一个外部命令(可执行文件),我不明白你为什么要使用 shell 来执行它。
  • 嗨@user1934428 对标签感到抱歉,但我认为对于这个特定命令,当我在open -n /Applications/test.app -- args arg1 上使用 bash 或 zsh 时,结果是相同的。我需要用新参数打开同一个应用程序
  • 为什么要使用shell?你没有做任何需要外壳的花哨的事情吗?
  • 我从未使用过 Swift,但我会使用 this。在您的情况下,要运行的程序是 open,您需要将参数作为具有 4 个元素的数组传递。

标签: swift macos terminal command


【解决方案1】:

我很确定不是这个

let args:[String] = ["-c","open -n /Applications/test.app","--args aaaa"]

应该是这个

let args:[String] = ["-c","open","-n","/Applications/test.app","--args","aaaa"]

此外,您实际上并不需要通过 z shell。您可以直接拨打open

task.launchPath = "/usr/bin/open"
let args:[String] = ["-n","/Applications/test.app","--args","aaaa"]

【讨论】:

    猜你喜欢
    • 2011-02-04
    • 1970-01-01
    • 2014-12-30
    • 2012-02-25
    • 1970-01-01
    • 2017-08-31
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多