Swift Mac应用程序,在不知道路径的情况下运行终端命令(因此它会在$ PATH中的每个路径中查找)? [英] Swift mac app, run terminal command without knowing the path (so it looks in every path in $PATH)?

查看:89
本文介绍了Swift Mac应用程序,在不知道路径的情况下运行终端命令(因此它会在$ PATH中的每个路径中查找)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的Swift Mac应用程序运行终端命令,我希望用户像在终端中一样输入任何命令,而不必指定真实路径.有没有一种方法可以运行命令并使它在$ PATH变量中指定的每个路径中显示?

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 there a way to run a command and make it look in every path that's specified in the $PATH variable?

当我指定路径时,我可以运行命令,但是我需要它来从系统$ PATH变量中的任何路径中自动查找二进制文件

I can run commands when I specify the path but I need it to auto-find the binary from any path in the systems $PATH variable

    let path = "/usr/bin/killall"
    let arguments = ["Dock"]
    let task = Process.launchedProcess(launchPath: path, arguments: arguments)
    task.waitUntilExit()

将来,我想读取.sh文件并运行其中的每一行,因此对于长脚本来说,并非所有二进制文件都位于默认路径中.

In the future I would like to read .sh files and run every line in it, so for long scripts not all binaries will be in the default path.

谢谢!

推荐答案

您可以通过

You can execute the command via env:

env utility argument ...

示例:

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

env使用$PATH变量查找给定的实用程序,然后 然后使用给定的参数执行它.它有额外的 用于指定其他搜索路径和其他选项的选项 环境变量.

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.

(这不是Swift的功能,而是macOS和许多其他操作系统的功能.)

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

从Finder(双击)启动时,PATH可能会有所不同 从您的Shell环境中的PATH中.如有必要,您可以添加 其他目录:

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 和朋友也使用$PATH找到可执行文件,但仅提供原始" C接口.


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

这篇关于Swift Mac应用程序,在不知道路径的情况下运行终端命令(因此它会在$ PATH中的每个路径中查找)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆