使用Swift编写脚本

使用Swift编写脚本

通常我们在编写脚本处理自动化或者通用处理的时候,使用的是 Shell 语言,但是作为有一个 Swift 语言使用者,你应该知道,Swift 也可以作为脚本语言来编写脚本。

Why Swfit

  • 降低 iOS 开发者的脚本开发难度
  • 利用 Swift 高级语言特点
  • 轻松调用 Swfit 库
  • 在 iOS Mac 上处理脚本更方便

Hello World

其实 Swift 脚本和 shell 脚本大致流程一致,只是编写语言不同而已。

编写 Swift 脚本

先来一个简单的 hello world 输出吧

创建一个 helloworld.swift 文件,并指定解释器\#!/usr/bin/env swift 或者\#!/usr/bin/swift

#!/usr/bin/env swift
import Foundation
func sayHelloWorld() -> Void {
    
    
    print("hello world")
    
}
sayHelloWorld()

修改文件为可执行

一般 swift 文件是没有具备可执行权限的,需要将文件权限修改为可执行:chmod u+x helloworld.swfit

运行Swift 脚本

和运行 shell 脚本一致,cd 到文件目录下执行./helloworld.swift

Swift 脚本调用 Shell 脚本

Swift脚本中需要通过 Process 来调用Shell 脚本,需要定义如下方法

/// 执行 Shell 命令 (会等待执行完成)
/// - Parameters:
///   - command: 命令
///   - path: 路径 默认为 "/bind/bash",即 shell 脚本
/// - Returns: 运行结果和命令执行标准输出
func shell(_ command: String, at path: String = "/bin/bash") -> (status: Int, results:String) {
    
    
    let task = Process();
    task.executableURL = URL(fileURLWithPath:path)
    var environment = ProcessInfo.processInfo.environment
    environment["PATH"] = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    task.environment = environment
    task.arguments = ["-c", command]
    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = String(data: data, encoding: String.Encoding.utf8)!
    task.waitUntilExit()
    pipe.fileHandleForReading.closeFile()
    return (Int(task.terminationStatus),output)
}

调用示例

调用其他 shell 脚本

print(run_shell(launchPath: "./helloShell.sh").results)

调用命令

let pwd = shell("pwd").results
print(pwd)

第三方库框架,当命令行需要或者项目级需要时可以使用第三方库,不过维护和其他系统支持。

SwiftShell支持运行命令并处理输出,异步运行,上下文改变,错误处理,读取和写入文件等功能

ShellOut让你简单运行你的 shell 命令,只有一个文件

代码提示技巧

如果直接新建 Swift 文件编辑,可能在编写过程中无法进行代码提示,也不能看到运行效果和警告错误。那应该在哪种环境下编写 Swift 脚本更方便了?

我习惯用 Storyboard, 模板选择 Mac 下的 Black,先注释掉解释器,然后定义 start 方法,可用于测试,也可用于脚本主要流程。

等测试完成后在将其复制到脚本文件中

//#!/usr/bin/env swift  // 先注释,以便无法运行和编译
import Foundation
start()
func start() {
    
    
    sayHello()
    let echoStr = shell("echo \"李好\"").results
    print(echoStr)
}

func sayHello() -> Void {
    
    
    print("hello Swift")
    
}
/// 执行 Shell 命令 (会等待执行完成)
/// - Parameters:
///   - command: 命令
///   - path: 路径 默认为 "/bind/bash",即 shell 脚本
/// - Returns: 运行结果和命令执行标准输出
func shell(_ command: String, at path: String = "/bin/bash") -> (status: Int, results:String) {
    
    
    let task = Process();
    task.executableURL = URL(fileURLWithPath:path)
    var environment = ProcessInfo.processInfo.environment
    environment["PATH"] = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    task.environment = environment
    task.arguments = ["-c", command]
    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = String(data: data, encoding: String.Encoding.utf8)!
    task.waitUntilExit()
    pipe.fileHandleForReading.closeFile()
    return (Int(task.terminationStatus),output)
}

Swift 脚本获取参数

首先我们先来熟悉下 Shell 获取脚本参数脚本格式为:$nn 代表一个数字,0 为执行的文件名(包含文件路径),1 为执行脚本的第一个参数,2 为执行脚本的第二个参数,以此类推……

Swift 是通过的参数在 CommandLine.arguments 中,规则与 Shell 类似

CommandLine.arguments[0] //文件名
CommandLine.arguments[1] //第一个参数

参考

使用 Swift 编写 CLI 工具的入门教程

从创建到开发到测试一系列。

Swift Script and Command Line Arguments

如果创造 Swift 命令行,以及 怎么获取参数

Using Swift for scripting

使用 Swift 来编写脚本示例,有很多示例项目,比如:如何获取参数、标准输入输出(stdin, stdout, stderr)、Progress/Pipe 的使用,进程命令和接收其他命令结果处理,输入命令行获取,使用exit(1)提前结束脚本。

Shell 调用 Swift 脚本

待定

猜你喜欢

转载自blog.csdn.net/qq_14920635/article/details/124500984