我尝试编写一个 macOS Swift 应用程序,它在/usr/local/bin
(例如 Homebrew-installed /usr/local/bin/cowsay
)中启动一个可执行文件。
但是,这不起作用,因为/usr/local/bin
不在PATH
环境变量中。
在应用程序中,我尝试添加/usr/local/bin
到PATH
via setenv
,这似乎也不起作用。
这是带有 Xcode 12.5 beta 3 (12E5244e) 的代码复制器:
import Foundation
import SwiftUI
func addPathComponentIfNotSet(_ pathComponent: String) {
// If path component already exists in PATH, return.
let path = ProcessInfo.processInfo.environment["PATH"]!
let pathComponents = path.split(separator: ":")
if pathComponents.contains(Substring(pathComponent)) {
return
}
// Otherwise, prepend path component to PATH via setenv.
let newPath = "\(pathComponent):\(path)"
setenv("PATH", newPath, 1)
// Print new PATH.
print("Actual new PATH:", ProcessInfo.processInfo.environment["PATH"]!)
}
@discardableResult
func shell(_ args: String...) -> Int32 {
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = args
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
struct DummyContentView: View {
var body: some View {
Button("Press me") {
// Add "/usr/local/bin" to PATH if it doesn't exist.
// Prints: "Actual new PATH: /usr/local/bin:/Applications/Xcode-beta.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
addPathComponentIfNotSet("/usr/local/bin")
// Test: running "ls" works.
shell("ls")
// Error 1: running "cowsay" here fails with "env: cowsay: Operation not permitted".
shell("cowsay", "Test this")
// Error 2: running "cowsay" here fails with "The file “cowsay” doesn’t exist".
let executableURL = URL(fileURLWithPath: "/usr/local/bin/cowsay")
try! Process.run(
executableURL,
arguments: ["Test this too"],
terminationHandler: nil)
}
}
}
/usr/local/bin/cowsay
会失败?
/usr/local/bin
?
比尔的解决方案对我有用。这是显示修复程序的屏幕截图 –Build Settings > Signing > Code Signing Entitlements
清空:
主要问题是沙箱。如果这仅供您自己使用,您可以为此应用程序禁用沙箱。为此,请转到目标/构建设置/签名。从代码签名权利中删除权利文件的名称。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句