【问题标题】:Xcode/Swift: How to add extra argument to a bash executionXcode/Swift:如何向 bash 执行添加额外的参数
【发布时间】:2018-12-09 19:11:57
【问题描述】:

我有这个代码:

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 bash macos process


    【解决方案1】:

    您可以在 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"])
    

    【讨论】:

    • 我在 process.arguments 处收到此错误:可选类型“字符串?”的值未拆封;你的意思是用'!'要么 '?'?如果添加 !我得到:二元运算符“+”不能应用于“[String]”和“String?”类型的操作数
    • @Sascha7777:您是否按照我的建议在Bundle.main.path(forResource: "initial", ofType: "command")! 添加了!?
    • 好的,我按照你的方式插入了它。编译正常但没有功能:fs5.directupload.net/images/180701/zyvuiqh6.png 和 fs5.directupload.net/images/180701/gfjrmgfe.png
    • @Sascha7777:shell 脚本是什么样的?
    • @Sascha7777:那个脚本只定义了一个函数。您确定从 shell 调用 /usr/bin/bash initial.command _ExecuteIt 会调用该函数吗? – 可能有帮助:stackoverflow.com/a/16159057/1187415.
    猜你喜欢
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    相关资源
    最近更新 更多