LoginSignup
9
12

More than 5 years have passed since last update.

rubyからmac上で実行中のアプリケーションを操作

Last updated at Posted at 2016-01-13

やりたいこと

  • MacOS上で動いているアプリケーションに、rubyスクリプトからテキスト送ったりしたい
  • AppleScriptを使用する際は、アプリケーション名がわからない場合でもなんとかしたい

rb-appscript(gem)

gemがあったので使ってみる。
rb-appscript

インストール

$ gem install rb-appscript

で使えるようになる、、、はずだった。

*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=$HOME/.rbenv/versions/2.3.0/bin/$(RUBY_BASE_NAME)
extconf.rb:44:in `<main>': uninitialized constant Config (NameError)

extconf failed, exit code 1

ううむ。何かConfigっちゅうのが気に食わないらしい。
調べてみると、Ruby2.2以降にこのgemが対応できていないらしい。
rb-appscriptのGithub Issue

使い方

ruby2.1以下だと

require "rubygems"
require "appscript"
include Appscript

app("TextEdit").activate
app("System Events").keystroke("send text message!")

こんな感じで使えるらしい。最近rubyバージョン上げたばっかりだったので残念。
gemの修正リクエストも出ているので、2.2以降は待った方が良さそう。

gemを使わない方法

は、この辺りを参考にrubyからシェルコマンド実行させる感じで出来そう。
RubyからMacの通知センターで通知する簡単な方法 (AppleScript)

アプリケーション名を指定して操作

立ち上がっているAtomにテキストを入力するスクリプトを書いてみた。無事こっちは動きました。

write-to-atom.rb
`osascript -e '
  tell application "Atom"
    activate
    tell application "System Events"
      keystroke "send to this message to Atom."
    end tell
  end tell'`

アプリケーション名が不明な場合の対応(pidを使用)

tell applicationでアプリケーション名を指定しなくてはいけないのですが、今回処理したかったapplication名がどうしてもわからず。
pidだけはなんとか取得できたので、それを使ってapplicationをactivateする方法。

write-to-specified-from-pid-app.rb
`osascript -e '
tell application "System Events"
  set frontmost of the first process whose unix id is "#{pid}" to true
  keystroke "send to this message to #{pid} app."
end tell'`

この方法を探すのに、結構苦労しました。

参考サイト

動作検証環境

  • Mac OS X 10.9.5
  • ruby 2.3.0
9
12
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
9
12