LoginSignup
2
2

More than 5 years have passed since last update.

NSUserUnixTaskでJXAスクリプトを実行して結果を得る

Posted at
DoShellScript.swift
#!/usr/bin/env swift

import Cocoa

guard let pathToMe = URL(string: "\(#file)", relativeTo: URL(fileURLWithPath: FileManager.default.currentDirectoryPath))?.path else {
  print("Error: current path of #file")
  exit(-1)
}
let __file__ = pathToMe as NSString

let scriptsPath = "\(__file__.deletingLastPathComponent)/DoShellScript.js"
let scriptsURL = URL(fileURLWithPath: scriptsPath)
guard let task = try? NSUserUnixTask(url: scriptsURL) else {
  print("Error: task is nil")
  exit(-2)
}
let stdout = Pipe()
let stderr = Pipe()
task.standardOutput = stdout.fileHandleForWriting
task.standardError = stderr.fileHandleForWriting
task.execute { error in
  if let error = error {
    print(error.localizedDescription)
    exit(-3)
  }
  let outdata = stdout.fileHandleForReading.readDataToEndOfFile()
  let errdata = stderr.fileHandleForReading.readDataToEndOfFile()
  stdout.fileHandleForReading.closeFile()
  stderr.fileHandleForReading.closeFile()
  let out = (String(data: outdata, encoding: .utf8) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
  let err = (String(data: errdata, encoding: .utf8) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
  print("stdout:\n\(out)")
  print("stderr:\n\(err)")
  NSApplication.shared().terminate(nil)
}
NSApplication.shared().run()
DoShellScript.js
#!/usr/bin/osascript
delay(3) //歯車アイコン確認用
App = Application.currentApplication()
App.includeStandardAdditions = true
App.doShellScript('ls ~/', {alteringLineEndings:false})

DoShellScript.swift と DoShellScript.js を同ディレクトリに置き実行。結果は以下の通り。

$ DoShellScript.swift 
stdout:
Applications
Desktop
Documents
Downloads
Library
Movies
Music
Pictures
Projects
Public
Sites
stderr:
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2