我有此代码:
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"))
现在,我想为脚本本身添加一个Extra参数(使用Bashscript中的Functions)。在Terminal中,它是这样的:
/usr/bin/bash initial.command Do_My_Function
如何将其添加到流程中?
答案 0 :(得分:0)
您可以在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"])