使用 swift 执行 MacOS 中应用程序包中的 shell 脚本
我试图找出是否可以在 swift 中执行位于我的应用程序包中的 shell 脚本。它是一个禁用沙盒的 Mac 应用程序。
这就是我获取 url 并且它正在工作的方式:
guard let saveScriptURL = Bundle.main.url(forResource: "scripts/save", withExtension: "sh") else {
VsLogger.logDebug("***", "Unable to get save.sh file")
return false
}
返回 this
/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}
任何指针都值得赞赏。
I'm trying to find out if is it possible to execute a shell script located in my app bundle in swift. It is a Mac application with Sandbox disabled.
This is how I get the url and it is working:
guard let saveScriptURL = Bundle.main.url(forResource: "scripts/save", withExtension: "sh") else {
VsLogger.logDebug("***", "Unable to get save.sh file")
return false
}
which returns this
/Users/me/Library/Developer/Xcode/DerivedData/appName-fcowyecjzsqnhrchpnwrtthxzpye/Build/Products/Debug/appName.app/Contents/Resources/scripts/save.sh
then this is my code to run it.
func shell(_ scriptURL: URL) throws {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.executableURL = scriptURL
try task.run()
}
but I get the error:
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}
Any pointers are appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码存在一些问题需要修复。
首先,您错误地使用了 Process,属性
executableURL
用于可执行文件,即本例中的 shell,您想用于运行脚本,因此对于 zsh 来说,它应该设置为其次,似乎经过一番尝试和错误后,我们无法直接执行脚本,我认为这是因为即使我们使用 chmod 将脚本设置为可执行文件,当脚本复制到捆绑包时,它也会丢失。因此,脚本需要作为“source save.sh”运行
要设置要运行的脚本,我们使用
arguments
属性因此,您的
shell
函数就变成了There are some issues with your code that needs to be fixed.
Firstly you are using Process incorrectly, the property
executableURL
is meant for the executable, that is the shell in this case, you want to use for running your script so for zsh it should be set toSecondly it seems after some trial and error that we can not execute the script directly, I assume this is because even if we set the script as executable using chmod this is lost when the script is copied to the bundle. So the script needs to be run as "source save.sh"
To set the script to be run we use the
arguments
propertySo together your
shell
function becomes