I'm doing a macOS app, trying to run shell command in child process. I'll get an error Couldn't posix_spawn: error 13
if I don't set launchPath to /usr/bin/env
, why is it like this? How can I run shell command in other path?
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
It's possible to access to a path like /Users/myName/myWorkspace
,
but you have first, to disable the app sandbox doing so:
If you want to run ls
in a custom directory, you might try this example:
let res = Helper.shell(launchPath: "/bin/ls", arguments: ["/Users/myUserName/myworkspace"])
print("*** ls ***:\n\(res)")
in my case I have the following output:
*** ls ***:
file1.txt
file2.txt
file3.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With