-
Notifications
You must be signed in to change notification settings - Fork 4
/
CocoaPython.swift
100 lines (80 loc) · 2.66 KB
/
CocoaPython.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// CocoaPython.swift
// json2Swift
//
// Created by Shi Jian on 2017/11/9.
// Copyright © 2017年 HHMedic. All rights reserved.
//
import Cocoa
public typealias completeBlock = ((_ results: [String], _ errors: String?)->Void)
public class CocoaPython {
let buildTask = Process()
let outPip = Pipe()
let errorPipe = Pipe()
/// 完成回调
var completed: completeBlock?
/// 是否异步执行回调,只在runAsync下生效
var asyncComlete = false
/// 多个返回结果的分隔符
public var splitPara: Character?
public init(scrPath: String, args: [String]? = nil, complete: completeBlock? = nil) {
completed = complete
buildTask.launchPath = "/usr/bin/python"
var allArgs = [String]()
allArgs.append(scrPath)
if let aArg = args {
allArgs.append(contentsOf: aArg)
}
buildTask.arguments = allArgs
buildTask.standardInput = Pipe()
buildTask.standardOutput = outPip
buildTask.standardError = errorPipe
// buildTask.terminationHandler = { p in
// self.taskFinish()
// }
}
/// 同步执行
public func runSync() {
buildTask.launch()
buildTask.waitUntilExit()
// 错误处理
if let aError = fetchResult(errorPipe), aError != "" {
runComlete(["-1"], aError)
return
}
// let result = fetchResult(outPip)?.split(separator: "\n").map(String.init) ?? [""]
runComlete(processResult(), nil)
}
/// 异步执行
///
/// - Parameter asyncComlete: 回调是否异步主线程执行
public func runAsync(asyncComlete: Bool = true) {
self.asyncComlete = asyncComlete
DispatchQueue.global().async {
self.runSync()
}
}
}
extension CocoaPython {
/// 执行block回调
fileprivate func runComlete(_ result: [String], _ error: String?) {
if asyncComlete {
asyncComlete = false
DispatchQueue.main.async {
self.completed?(result, error)
}
} else {
completed?(result, error)
}
}
// 获取返回数据的字符串形式
fileprivate func fetchResult(_ pipe: Pipe) -> String? {
let data = pipe.fileHandleForReading.readDataToEndOfFile()
return String(data: data, encoding: String.Encoding.utf8)
}
fileprivate func processResult() -> [String] {
let result = fetchResult(outPip) ?? ""
guard let splt = splitPara else { return [result] }
return result.split(separator: splt).map(String.init)
}
}