3

コードに IPython シェルを埋め込み、それが呼び出された行番号と関数を自動的に表示するにはどうすればよいですか?

現在、コードに IPython シェルを埋め込むための次のセットアップがあります。

from IPython.frontend.terminal.embed import InteractiveShellEmbed
from IPython.config.loader import Config

# Configure the prompt so that I know I am in a nested (embedded) shell
cfg = Config()
prompt_config = cfg.PromptManager
prompt_config.in_template = 'N.In <\\#>: '
prompt_config.in2_template = '   .\\D.: '
prompt_config.out_template = 'N.Out<\\#>: '

# Messages displayed when I drop into and exit the shell.
banner_msg = ("\n**Nested Interpreter:\n"
"Hit Ctrl-D to exit interpreter and continue program.\n"
"Note that if you use %kill_embedded, you can fully deactivate\n"
"This embedded instance so it will never turn on again")   
exit_msg = '**Leaving Nested interpreter'

# Put ipshell() anywhere in your code where you want it to open.
ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg, exit_msg=exit_msg)

これにより、 を使用するだけで、コード内のどこからでも完全な IPython シェルを開始できますipshell()。たとえば、次のコード:

a = 2
b = a
ipshell()

aとの値を検査できる呼び出し元のスコープで IPython シェルを開始しますb

私がやりたいことは、私が呼び出すたびに次のコードを自動的に実行ipshell()することです:

frameinfo = getframeinfo(currentframe())
print 'Stopped at: ' + frameinfo.filename + ' ' +  str(frameinfo.lineno)

これにより、IPythonシェルが開始されるコンテキストが常に表示されるため、デバッグ中のファイル/関数などがわかります。

おそらく、デコレータを使用してこれを行うことができますが、元のコンテキスト内でipshell()実行する必要があるため (IPython シェルにアクセスしたり、IPython シェルからアクセスしたりできるようにするため)、これまでの試みはすべて失敗しました。ab

どうすればこれを達成できますか?

4

1 に答える 1

6

ipshell()別のユーザー定義関数内から呼び出すことができます。ipsh()

from inspect import currentframe

def ipsh():
    frame = currentframe().f_back
    msg = 'Stopped at {0.f_code.co_filename} and line {0.f_lineno}'.format(frame)
    ipshell(msg,stack_depth=2) # Go back one level!

次にipsh()、IPython シェルにドロップしたいときにいつでも使用します。

説明:

  • stack_depth=2ipshell新しい IPython シェルの名前空間を取得するときに、1 レベル上に移動するように求められます (デフォルトは です1)。
  • currentframe().f_back()が呼び出された場所の行番号とファイルを印刷できるように、前のフレームを取得します。ipsh()
于 2013-03-27T23:03:28.927 に答える