2

I'm trying to creating a macOS application that that involves allowing the user to run terminal commands. I am able to run a command, but it runs from a directory inside my app, as far as I can tell. Running pwd returns /Users/<me>/Library/Containers/<My app's bundle identifier>/Data.

How can I chose what directory the command runs from?

I'm also looking for a way to get cd to work, but if I can chose what directory to run the terminal command from, I can handle cd manually.

Here is the code that I'm currently using to run terminal commands:

func shell(_ command: String) -> String {
    let task = Process()
    let pipe = Pipe()

    task.standardOutput = pipe
    task.arguments = ["-c", command]
    task.launchPath = "/bin/zsh"
    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = String(data: data, encoding: .utf8)!

    return output
    
}

I'm using Xcode 12 on Big Sur.

Thanks!

4

2 回答 2

1

上有一个已弃用的属性 currentDirectoryPathProcess

假设您不想使用已弃用的属性,请在阅读其文档后转到FileManager并查看管理当前目录及其含义的规定。

或者只是cd按照您的考虑使用 - 您正在启动一个zsh带有shell 命令行作为参数的 shell ( )。命令行可以包含多个用分号分隔的命令,因此您可以将 acd添加到您的command值中。

后一种方法避免更改当前进程的当前目录。

高温高压

于 2020-08-23T23:44:45.813 回答
0

要添加到 CRD 的答案,如果使用该cd方法,您还可以考虑使用分隔命令&&来等待先前的命令成功完成,然后再继续执行依赖于它的下一个命令。

尝试您希望在终端中运行的命令,看看它是否按预期完成

例如:/bin/bash -c "cd /source/code/ && git pull && swift build"

如果一切都按预期工作,您可以继续在您的 swift 代码中使用它,如下所示:
shell("cd /source/code/ && git pull && swift build")


关于弃用的主题,您可能希望将 launchPath 替换为executableURL 并将 launch() 替换为run()

带有更新代码的示例实现:

@discardableResult
func shell(_ args: String...) -> Int32 {
    let task = Foundation.Process()
    
    task.executableURL = URL(fileURLWithPath: "/bin/bash")
    task.arguments = ["-c"]
    task.arguments = task.arguments! + args
    
    //Set environment variables
    var environment = ProcessInfo.processInfo.environment
    environment["PATH"]="/usr/bin/swift"
    //environment["CREDENTIALS"] = "/path/to/credentials"
    task.environment = environment
    
    let outputPipe = Pipe()
    let errorPipe = Pipe()
    
    task.standardOutput = outputPipe
    task.standardError = errorPipe
    
    do {
        try task.run()
    } catch {
        // handle errors
        print("Error: \(error.localizedDescription)")
    }
    task.waitUntilExit()
    
    let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
    let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
    
    let output = String(decoding: outputData, as: UTF8.self)
    let error = String(decoding: errorData, as: UTF8.self)
    
    //Log or return output as desired
    print(output)
    print("Ran into error while running: \(error)")
    
    return task.terminationStatus
}
于 2021-07-26T15:22:01.607 回答