我正在尝试创建一个mac应用程序,用户可以输入命令,就像在mac终端中一样,我得到了大部分工作,但我发现从发现者或 xcode运行的应用程序的$PATH变量是不同的比终端使用的$PATH变量. 我可以
我可以运行命令并找到一种方法来为应用程序的$PATH变量添加预定义路径,但是我需要一种方法来自动读取Terminal的$PATH变量并将其复制到Application的$PATH变量.这应该是自动化的,因为用户将在其变量中具有不同的路径.
我还发现,当我使用“open appname.app”从终端运行应用程序时,使用了正确的$PATH变量(终端使用的是同一个变量)
到目前为止这是我的代码:
let task = Process() var env = ProcessInfo.processInfo.environment var path = env["PATH"]! as String path = "/usr/local/bin:" + path env["PATH"] = path task.environment = env task.launchPath = "/usr/bin/env" task.arguments = ["echo","$PATH"] let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe task.launch() task.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String print(output)
这会将“/usr/local/bin”添加到Application的$PATH中,但我需要一种方法来复制终端的$PATH中的值.
谢谢!
添加bash Shell Path可以在/ etc / paths和/etc/path.d/中找到默认的shell路径.读取shell路径的一种方法是使用path_helper命令.扩展上面的代码示例并使用bash作为shell:
let taskShell = Process() var envShell = ProcessInfo.processInfo.environment taskShell.launchPath = "/usr/bin/env" taskShell.arguments = ["/bin/bash","-c","eval $(/usr/libexec/path_helper -s) ; echo $PATH"] let pipeShell = Pipe() taskShell.standardOutput = pipeShell taskShell.standardError = pipeShell taskShell.launch() taskShell.waitUntilExit() let dataShell = pipeShell.fileHandleForReading.readDataToEndOfFile() var outputShell: String = NSString(data: dataShell, encoding: String.Encoding.utf8.rawValue) as! String outputShell = outputShell.replacingOccurrences(of: "\n", with: "", options: .literal, range: nil) print(outputShell) let task = Process() var env = ProcessInfo.processInfo.environment var path = env["PATH"]! as String path = outputShell + ":" + path env["PATH"] = path task.environment = env task.launchPath = "/usr/bin/env" task.arguments = ["/bin/bash", "-c", "echo $PATH"] let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe task.launch() task.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() var output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String output = output.replacingOccurrences(of: "\n", with: "", options: .literal, range: nil) print(output)
注意:
>此代码示例以非交互模式调用shell.这意味着它不会执行任何用户特定的配置文件;例如/Users/*userid*/.bash_profile.
>路径可以在PATH环境变量中多次列出.它们将从左到右遍历.
参考
应用程序上有几个线程,OS X的shell PATH提供了更多上下文
How to set system wide environment variables on OS X Mavericks
和
Setting the system wide path environment variable in mavericks