【问题标题】:Swift, macOS: Open terminal window at the locationSwift,macOS:在该位置打开终端窗口
【发布时间】:2021-07-15 14:27:55
【问题描述】:

我正在尝试午餐终端窗口并转到其中的一些本地路径:

我的代码:

public class func openShell(at url: URL?) {
    guard let url = url else { return }
    
    let shellProcess = Process();

    shellProcess.launchPath = url.path;

    //shellProcess.arguments = [
    //  "osascript -e 'tell application \"terminal\" to do script \"cd \(url)\"'"
    //];

    shellProcess.launch();
}

但结果是在 XCode 内部的调试控制台中有一些输出,但没有打开任何 shell 窗口。

注释代码 - 我尝试过的替代方法

【问题讨论】:

    标签: swift macos shell terminal


    【解决方案1】:

    所以基本上你有两个选择:

    1. 您需要关闭沙盒才能使用此方法;
    2. 您需要创建 XPC 服务,然后从那里调用这些东西,它应该可以工作。

    第二个显然更好,在实际应用中你应该使用这种方法。也可以了解更多关于 XPC 服务的信息,您可以查看我的仓库,我对 parse processes info 执行相同操作或查看 this guidethis

    【讨论】:

    • 不需要 sanbox 禁用。我找到了解决方案
    【解决方案2】:

    2021,斯威夫特 5.0

    答案很简单:

    @available(OSX 10.15, *)
    public class func openTerminal(at url: URL?){
        guard let url = url,
              let appUrl = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal")
        else { return }
        
        NSWorkspace.shared.openFile("\(url.path)", withApplication: appUrl.path)
    }
    

    在每次 func 调用时,都会打开具有选定位置的终端的新实例。

    并且无需为此创建 XPC 服务或关闭沙盒。

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2019-02-17
      • 2017-12-03
      • 1970-01-01
      • 2014-07-20
      • 2010-12-20
      • 2018-05-16
      • 2021-01-05
      • 1970-01-01
      相关资源
      最近更新 更多