0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonをVSCode上でセル実行している場合のフラグ

Posted at

はじめに

Pythonコードを記述する際に、Jupyter Notebookのようなセル単位での実行が可能な環境は非常に便利です。
Visual Studio Code(VSCode)も、このセル実行機能を利用でき、#%%をコードの頭につけるだけでhoge.pyファイルのままソース管理とセル実行を両立させることができます。
一方でVSCodeから実行する場合は、if __name__ == '__main__'ではスクリプトとして実行する場合特別がつきません。

結論

これで区別できる

sample.py
import sys

if "ipykernel_launcher.py" in sys.argv[0]:
    print("VSCodeのセルから実行されています")
else:
    print("シェルなどから実行されています")

なぜこれでわかるのか

sys.argv[0]にはスクリプトの実行時にはスクリプト自身のファイル名が格納されます。
コマンドラインから実行した場合はsample.pyが格納されますが
セル実行の場合、このファイル名がipykernel_launcher.pyになります。
(ipykernelは、Jupyter 用の IPython カーネルを提供するパッケージ)

何が嬉しいのか

  • セル実行とスクリプトとしての実行を区別できるのでセル実行時だけデバック出力を行う、可視化結果を出力する等が可能になる。
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?