【问题标题】:How can I run macOS terminal commands from Swift? [closed]如何从 Swift 运行 macOS 终端命令? [关闭]
【发布时间】:2022-01-16 02:52:55
【问题描述】:

我希望能够在 macOS 中通过 Swift for Terminal 运行此代码:

cd ~/Desktop/
mkdir "New Folder"

基本上我想进入桌面级别,然后在那里创建一个新文件夹。我想在 Swift/SwiftUI 中按下一个按钮来运行一个函数来执行终端的代码。使用 Swift/SwiftUI 只是为了 UI。我没有在某个地方保存 shell 文件,我所有的代码都是我希望能够从 Swift 为终端运行这两个命令。

func runBashCode() {

    // need help here
    cd ~/Desktop/
    mkdir "New Folder"

}

【问题讨论】:

  • 为什么(为此使用 bash)?虽然不使用FileManager?
  • 我没看懂你说的,你的意思是我应该用bash?
  • 不,我的意思是为什么在已经存在处理文件级操作的 API 时执行 shell 命令来创建目录 - plenty of examples available
  • 哦,这就是问题的本质,正如我在问题中提到的那样。 @MadProgrammer
  • @jnpdx:你是 bash 的专家吗?我不是,但我知道 bash 需要一个保存的 shell 才能工作!您是否在某个地方看到了一个 shell 文件或提到了一个已保存的 shell?

标签: swift terminal


【解决方案1】:

试试这样的:

注意:需要在“Signing & Capabilities”中删除“App Sandbox”

struct ContentView: View {
    let arg = NSHomeDirectory() + "/Desktop/newfolder"
    
    var body: some View {
        Button("mkdir") {
            runMkdir()
        }.frame(width: 333, height: 333)
    }
    
    func runMkdir() {
        let task = Process()
        task.executableURL = URL(fileURLWithPath: "/bin/mkdir")
        task.arguments = [arg]
        task.launch()
    }
    
}

【讨论】:

  • 不要硬编码你的路径。这仅适用于正在开发应用程序的机器。 stackoverflow.com/a/41384443/2303865
  • 是的,好点。这只是一个例子。我会根据您的建议更新我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 2021-01-15
  • 2023-03-23
相关资源
最近更新 更多