gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:31:59 25 4
gpt4 key购买 nike

我喜欢使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com