Swift mac app, run terminal command without knowing the path (so it looks in every path in $PATH)?

前端 未结 1 1233
Happy的楠姐
Happy的楠姐 2021-01-28 02:17

I\'m trying to run terminal commands from my swift mac app, i want the users to enter any command like they would in the terminal without having to specify the real path. Is the

1条回答
  •  生来不讨喜
    2021-01-28 02:39

    You can execute the command via env:

    env utility argument ...
    

    Example:

    let path = "/usr/bin/env"
    let arguments = ["ls", "-l", "/"]
    let task = Process.launchedProcess(launchPath: path, arguments: arguments)
    task.waitUntilExit()
    

    env locates the given utility using the $PATH variable and then executes it with the given arguments. It has additional options to specify a different search path and additional environment variables.

    (This is not a feature of Swift but of macOS and many other operating systems.)

    When started from the Finder (double-click) the PATH may be different from the PATH in your shell environment. If necessary, you can add additional directories:

    var env = task.environment ?? [:]
    if let path = env["PATH"] {
        env["PATH"] = "/usr/local/bin:" + path
    } else {
        env["PATH"] = "/usr/local/bin"
    }
    task.environment = env
    

    execlp and friends also locate the executable using $PATH but offer only the "raw" C interface.

    0 讨论(0)
提交回复
热议问题