我有这个代码:
func syncShellExec(path: String?) {
let script = [path!]
let process = Process()
let outputPipe = Pipe()
let filelHandler = outputPipe.fileHandleForReading
process.launchPath = "/bin/bash"
process.arguments = script
process.standardOutput = outputPipe
.
.
.
在 Swift 中,我这样称呼它:
self.syncShellExec(path: Bundle.main.path(forResource: "initial", ofType: "command"))
现在我想为脚本本身添加一个额外的参数(使用 Bashscript 中的函数(。在终端中,它将是这样的:
/usr/bin/bash initial.command Do_My_Function
如何将其添加到流程中?
你可以向 Swift 函数添加一个"可变参数", 并将参数附加到process.arguments
:
func syncShellExec(path: String, args: String...) {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = [path] + args
// ...
}
现在您可以调用例如:
let scriptPath = Bundle.main.path(forResource: "initial", ofType: "command")!
syncShellExec(path: scriptPath)
syncShellExec(path: scriptPath, args: "Do_My_Function")
syncShellExec(path: scriptPath, args: "arg1", "arg2")
备注:syncShellExec()
函数需要脚本的路径, 因此我不会将该参数设为可选并强制解包 它在函数内部。另一方面,Bundle.main.path(...)
仅当资源丢失时才会返回 nil。那是一个编程错误,因此强制解开返回值的包装是 合理。
如果参数的数量仅在运行时确定,则 您可以将参数定义为数组
func syncShellExec(path: String, args: [String] = [])
并将其称为
syncShellExec(path: scriptPath)
syncShellExec(path: scriptPath, args: ["Do_My_Function"])
syncShellExec(path: scriptPath, args: ["arg1", "arg2"])