swift - 为 shell 命令获取实用程序的完整路径,如 7zip 等

标签 swift xcode macos shell path

我喜欢使用 shell 从我的应用程序调用外部应用程序,如 7zip。

let res = shell(launchPath: "/path/7za", arguments: myargs)

shell 命令需要应用程序的完整路径。有了“ls”我就知道了。它始终是“/bin”,但其他附加命令或应用程序又如何。您可以将它们安装在任何您想要的地方。我如何获得这条路径? 我是否必须查询 PATH 变量并尝试每个位置?对我来说听起来很复杂。 那么,如果我知道应用程序名称是例如,我该如何获得 shell 所需的路径呢? “7za”?

shell 函数:

func shell(launchPath: String, arguments: [String] = []) -> String
{
    let task = Process()
    task.launchPath = launchPath
    task.arguments  = arguments

    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()

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

    return output
}

最佳答案

您可以使用which命令找到程序的路径,它通常位于macOS上的/usr/bin/which

WHICH(1)                  BSD General Commands Manual                 WHICH(1)

NAME
     which -- locate a program file in the user's path

SYNOPSIS
     which [-as] program ...

DESCRIPTION
     The which utility takes a list of command names and searches the path for each executable file that would be run had these commands actu-
     ally been invoked.

     The following options are available:

     -a      List all instances of executables found (instead of just the first one of each).

     -s      No output, just return 0 if all of the executables are found, or 1 if some were not found.

     Some shells may provide a builtin which command which is similar or identical to this utility.  Consult the builtin(1) manual page.

SEE ALSO
     builtin(1), csh(1), find(1), locate(1), whereis(1)

HISTORY
     The which command first appeared in FreeBSD 2.1.

AUTHORS
     The which utility was originally written in Perl and was contributed by Wolfram Schneider <wosch@FreeBSD.org>.  The current version of
     which was rewritten in C by Daniel Papasian <dpapasia@andrew.cmu.edu>.

BSD                            December 13, 2006                           BSD

或者,您可以尝试 7za 的最常见路径,如果找不到,则最后执行 which 解决方案

正如@zwbetz 所指出的,您还可以使用 command -v 命令,它也会显示别名。

关于swift - 为 shell 命令获取实用程序的完整路径,如 7zip 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57224677/

相关文章:

ios - animateWithDuration - UITextField 中的淡入/淡出动画

ios - 使用 SwiftUI 创建手势来编辑列表项

Python 模块对象在 OSX Sierra 上没有带有自制软件的 struct_time 属性,但在 debian 上没有

android - 在 Mac 中启动 AVD 时出错

macos - Docker for Mac 教程 - 重叠导出路径

swift - "Ambiguous reference to member ' scheduledTimerWithTimeInterval( _ :invocation:repeats:) '"

ios - Spritekit 在玩游戏时保留 iPhone 音乐

ios - 如何从 UIViewController 对不同 swift 文件的引用中调用它的函数?

iphone - 如何在 ios uitableview(组表)中执行验证?

ios - 如何从 xarchive 启用 iOS 功能?