如何快速运行shell命令? [英] How do I run shell command in swift?
本文介绍了如何快速运行shell命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一个macOS应用,试图在子进程中运行shell命令.如果我未将launchPath设置为/usr/bin/env
,则会收到错误Couldn't posix_spawn: error 13
,为什么会这样?如何在其他路径中运行shell命令?
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
推荐答案
可以访问/Users/myName/myWorkspace
之类的路径,
但首先,您需要禁用应用程序沙箱:
It's possible to access to a path like /Users/myName/myWorkspace
,
but you have first, to disable the app sandbox doing so:
如果要在自定义目录中运行ls
,则可以尝试以下示例:
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
这篇关于如何快速运行shell命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文