iTerm2 バージョン3.3で追加されたPython scripting APIを使って、現在アクティブなセッションのカレントディレクトリを取得する方法です。
1. スクリプト
iterm2.run_until_complete
に指定したコルーチンの仮引数(Connection
型)からApp
オブジェクトを取得し、そこからcurrent_terminal_window
、current_tab
、current_session
プロパティで現在フォアグラウンドなセッションを取得します。
そのセッション内の変数path
に、カレントディレクトリが格納されているので、async_get_variable( "path" )
で取得できます。
# !/usr/bin/env python3.7
import iterm2
import os
async def main( connection ):
print( f"Current path on Python script: {os.path.abspath( os.path.curdir )}" )
app = await iterm2.async_get_app( connection )
# 現在フォアグラウンドなターミナルウィンドウを取得
cur_window = app.current_terminal_window
# ↑のウィンドウで、現在フォアグラウンドなタブを取得
cur_tab = cur_window.current_tab
# ↑のタブで、現在フォアグラウンドなセッションを取得
cur_session = cur_tab.current_session
# ↑のセッション内の変数から、現在フォアグラウンドなセッションのカレントディレクトリを取得
cur_path = await cur_session.async_get_variable( "path" )
print( f"Current path on Foreground session: {cur_path}" )
iterm2.run_until_complete( main )
# 実行結果(iTerm2のスクリプトコンソールのログより)
Current path on Python script: /
Current path on Foreground session: /usr/local/Cellar
ちなみに実行結果より、iTerm2から実行したPythonスクリプト上での現在のディレクトリ(os.path.curdir
)は、システムのルートディレクトリになっていることが分かります。