我正在做一个 macOS 应用程序,尝试在子进程中运行 shell 命令。我会收到一个错误Couldn't posix_spawn: error 13
如果我不将 launchPath 设置为/usr/bin/env
,为什么会这样呢?如何在其他路径中运行 shell 命令?
class Helper {
static func shell(launchPath path: String, arguments args: [String]) -> String {
let task = Process()
task.launchPath = path
task.arguments = args
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
task.waitUntilExit()
return(output!)
}
}
let res = Helper.shell(launchPath: "/Users/myUserName", arguments: ["ls"]) //error
可以访问类似的路径/Users/myName/myWorkspace
,
但您首先必须禁用应用程序沙箱:
如果你想跑步ls
在自定义目录中,您可以尝试以下示例:
let res = Helper.shell(launchPath: "/bin/ls", arguments: ["/Users/myUserName/myworkspace"])
print("*** ls ***:\n\(res)")
就我而言,我有以下输出:
*** ls ***:
file1.txt
file2.txt
file3.txt
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)