LoginSignup
0
0

More than 3 years have passed since last update.

[iterm2 / Python API] 現在フォアグラウンドなセッションのカレントディレクトリを取得する

Posted at

iTerm2 バージョン3.3で追加されたPython scripting APIを使って、現在アクティブなセッションのカレントディレクトリを取得する方法です。

active-session.png

1. スクリプト

iterm2.run_until_completeに指定したコルーチンの仮引数(Connection型)からAppオブジェクトを取得し、そこからcurrent_terminal_windowcurrent_tabcurrent_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)は、システムのルートディレクトリになっていることが分かります。

参考サイト

0
0
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
0
0