NSUserScriptTask是脚本调用代码的基础,NSUserAppleScriptTask和NSUserautomatorTask子类都允许设置变量以将信息从Swift传递到脚本:
Passing variables to an AppleScript
Setting NSUserAutomatorTask variables without requiring Automator Workflows to declare that variable
这留下了NSUserUnixTask,它不支持设置变量.它改为支持一个名为arguments的[String]数组.
执行脚本时,我想从Mac应用程序传递3个变量:
let folderURL: String? = "/files/"let fileURLs: [String] = ["/files/file1","/files/file2"]let selectionType: Int? = 1let arguments: [String] = ["how","should","arguments","be","formatted","?"]let unixScript = try! NSUserUnixTask(url: url)unixScript.execute(withArguments: arguments) { (error) in if let error = error { print(error) }}
必须将3个swift变量压缩为单个[String]数组,以便NSUserUnixTask用作其参数参数.
当脚本运行时,我希望以原型方式为脚本作者提供相同参数的访问权限:
#! /bin/bash say "How should the script then access/parse the arguments?"say $@ #says the arguments
根据脚本作者的易用性,Swift代码应该如何将其信息格式化为参数[String]?
可以提供哪些样板代码,以便从脚本中轻松实用地访问参数?
解决方法 有很多方法可以做,具体取决于shell脚本程序员所期望的.如果我是其中之一,我会要求你保持简单:>位置参数(开始时必需参数的固定数量)
>可选的命名参数(样式的任何参数-flag值)
>更多参数(可变数量的附加参数)
按照你的例子,稍加修改:
import Foundationlet shellScript = Commandline.arguments[1]let folderURL: String = "/files/"let fileURLs: [String] = ["/files/file1","/files/file2"]let selectionType: Int? = 1var arguments = [String]()// script.sh <folder> [-type <type>] file1,file2,...arguments.append(folderURL) // <folder> is mandatoryif let type = selectionType { // -type <type> is optional arguments.append("-type") arguments.append("\(type)")}arguments += fileURLs // file1,... (if it can't be empty check it here)assert(fileManager.default.fileExists(atPath: shellScript))let unixScript = try! NSUserUnixTask(url: URL(fileURLWithPath: shellScript))let stdout = fileHandle.standardOutputunixScript.standardOutput = stdoutunixScript.execute(withArguments: arguments) { error in if let error = error { print("Failed: ",error) } exit(0)}dispatchMain() // I'm not swift script expert,there may be a better way
和相应的shell脚本:
#!/bin/bash# mandatory positional argumentsFolDER= && shift# other mandatory arguments goes hereTYPE=7 # default typefileS=()while [[ $# -gt 0 ]]; do arg= case $arg in -type) TYPE= && shift && shift ;; # other named parameters here *) fileS+=() && shift ;; esacdoneecho FolDER: '<'${FolDER}'>'echo TYPE: '<'${TYPE}'>'echo fileS: '<'${fileS[@]}'>'exit 0
例:
ScriptRunner /path/to/script.sh
输出:
FolDER: </files/>TYPE: <1>fileS: </files/file1 /files/file2>
我使用swift包管理器来构建:
// swift-tools-version:4.2import PackageDescriptionlet package = Package( name: "ScriptRunner",dependencIEs: [],targets: [ .target(name: "ScriptRunner",dependencIEs: []) ])总结
以上是内存溢出为你收集整理的swift – 如何通过NSUserUnixTask传递参数然后通过脚本访问?全部内容,希望文章能够帮你解决swift – 如何通过NSUserUnixTask传递参数然后通过脚本访问?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)