pythonでウィンドウ座標を取得する
某スマホRPGのPC版でいろいろ遊びたくなったのでまずはウィンドウ座標を取得してみました。
ウィンドウ座標を取得する
xwininfoコマンドでウィンドウ情報を取得できます。
今回は調べるウィンドウの名前が決まっているのでnameオプションで指定してあげます。
wami ~/ $ xwininfo -name 某スマホRPG xwininfo: Window id: 0x3e00068 "某スマホRPG" Absolute upper-left X: 1419 Absolute upper-left Y: 200 Relative upper-left X: 3 Relative upper-left Y: 26 Width: 453 Height: 707 Depth: 24 Visual: 0x21 Visual Class: TrueColor Border width: 0 Class: InputOutput Colormap: 0x3e00001 (not installed) Bit Gravity State: NorthWestGravity Window Gravity State: NorthWestGravity Backing Store State: NotUseful Save Under State: no Map State: IsViewable Override Redirect State: no Corners: +1419+200 -1414+200 -1414-173 +1419-173 -geometry 453x707+1416+174
pythonからコマンドを実行する
python上でコマンド実行するために subprocess モジュールを使います。
ここを参考にやってみます。
17.1. subprocess — サブプロセス管理 — Python 2.7.13 ドキュメント
import subprocess cmd = "xwininfo -name 某スマホRPG" subprocess.call(cmd.split(' '))
実行するとターミナルで実行されました。ウィンドウ情報の確認はできますが、これでは実行結果をプログラム内で取得できませんね。
コマンド実行結果を文字列として取得する
上のサイトなどいろいろ調べるとPopenをつかったりするようです。よくわかりませんがやってみます。
from subprocess import Popen, PIPE cmd = "xwininfo -name 某スマホRPG" p = Popen(cmd.split(' '),stdout = PIPE, stderr = PIPE) ret = str(p.communicate()) print(ret)
実行するといろいろ化けてますがうまく出力できました。
('\nxwininfo: Window id: 0x3e00068 "\xe3\x82\xb0\xe3\x83\xa9\xe3\x83\xb3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\x95\xe3\x82\xa1\xe3\x83\xb3\xe3\x82\xbf\xe3\x82\xb8\xe3\x83\xbc[ChromeApps\xe7\x89\x88]"\n\n Absolute upper-left X: 1419\n Absolute upper-left Y: 200\n Relative upper-left X: 3\n Relative upper-left Y: 26\n Width: 453\n Height: 707\n Depth: 24\n Visual: 0x21\n Visual Class: TrueColor\n Border width: 0\n Class: InputOutput\n Colormap: 0x3e00001 (not installed)\n Bit Gravity State: NorthWestGravity\n Window Gravity State: NorthWestGravity\n Backing Store State: NotUseful\n Save Under State: no\n Map State: IsViewable\n Override Redirect State: no\n Corners: +1419+200 -1414+200 -1414-173 +1419-173\n -geometry 453x707+1416+174\n\n', '')
完成
あとは出力から座標を抽出すれば完成です。正規表現を使ってみましたがとっても便利ですね。ついでにマウスの座標表示もしときました。後できっと使います。
import pyautogui import re from subprocess import Popen, PIPE cmd = "xwininfo -name 某スマホRPG" p = Popen(cmd.split(' '),stdout = PIPE, stderr = PIPE) ret = str(p.communicate()) coord = re.search('X:\s+(\d+)[^Y]+Y:\s+(\d+)',ret) print(coord.groups()) print(pyautogui.position())
実行結果
<class 'Xlib.protocol.request.QueryExtension'> ('1419', '200') (817, 496)
うまく座標を取得できました。
これで快適な某スマホRPGライフに一歩近づけたことでしょう。
昨日Amazonで注文したパスタ5kgの支払い番号がこないのはなぜ・・・