如何使用Swift启动终端并向其传递命令



我想以编程方式打开一个终端,并在其中粘贴一条命令,如"cd/Users/…&"。

我可以用这段代码启动一个终端,但是我不知道如何执行命令

guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal") else { return }
let path = "/bin"
let configuration = NSWorkspace.OpenConfiguration()
configuration.arguments = [path]
NSWorkspace.shared.openApplication(at: url, configuration: configuration, completionHandler: nil)

使用沙箱非常重要,Process命令不合适。

如果您想要实现的是在特定位置打开终端,那么您需要做的就是使用以下代码:

let pathToOpen = "/Users/admin/Desktop"
let url = URL(string:"terminal://"+pathToOpen)! 
NSWorkspace.shared.open(url)

如果你只是想在终端上运行一个命令,并在你的应用程序中显示输出,这里是另一个有用的代码片段:

func shell(_ command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/zsh"
task.standardInput = nil
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output
}
//Usage:
shell("yourCommandHere")
//please note that you are not allowed to use commands that require sudo

最新更新