我試圖找出是否可以快速執行位于我的應用程式包中的 shell 腳本。這是一個禁用沙盒的 Mac 應用程式。
這就是我獲取網址的方式并且它正在作業:
guard let saveScriptURL = Bundle.main.url(forResource: "scripts/save", withExtension: "sh") else {
VsLogger.logDebug("***", "Unable to get save.sh file")
return false
}
回傳這個
/Users/me/Library/Developer/Xcode/DerivedData/appName-fcowyecjzsqnhrchpnwrtthxzpye/Build/Products/Debug/appName.app/Contents/Resources/scripts/save.sh
那么這是我運行它的代碼。
func shell(_ scriptURL: URL) throws {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.executableURL = scriptURL
try task.run()
}
但我得到了錯誤:
Error Domain=NSCocoaErrorDomain Code=4 "The file “save.sh” doesn’t exist." UserInfo={NSFilePath=/Users/me/Library/Developer/Xcode/DerivedData/appName-fcowyecjzsqnhrchpnwrtthxzpye/Build/Products/Debug/appName.app/Contents/Resources/scripts/save.sh}
任何指標表示贊賞。
uj5u.com熱心網友回復:
您的代碼存在一些問題需要修復。
首先,您使用 Process 不正確,該屬性executableURL適用于可執行檔案,在這種情況下是 shell,您想使用它來運行您的腳本,因此對于 zsh 它應該設定為
task.executableURL = URL(fileURLWithPath: "/bin/zsh")
其次,似乎經過一些試驗和錯誤后我們無法直接執行腳本,我認為這是因為即使我們使用 chmod 將腳本設定為可執行檔案,當腳本復制到包時也會丟失。所以腳本需要作為“source save.sh”運行
要設定要運行的腳本,我們使用arguments屬性
task.arguments = ["-c", "source \(scriptURL.path"]
所以你的shell功能一起變成
func shell(_ scriptURL: URL) throws {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.executableURL = URL(fileURLWithPath: "/bin/zsh")
task.arguments = ["-c", "source \(scriptURL.path)"]
try task.run()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/435267.html
上一篇:除非包含“shell=True”,否則為什么subprocess.call()不執行scp?
下一篇:通過指標呼叫成員函式
