【发布时间】: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