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?

More than 1 year has passed since last update.

#python の __main__ 関数とは何なのか (いや関数じゃないよ) (初心者向け)

Last updated at Posted at 2019-04-09

import時の挙動が違うらしい。

  • main 関数の中に書かないと import 時にスクリプトが実行される
  • main 関数の中に書いておくと import 時に実行されない
  • むしろ import 時に実行させたい処理の場合は main 判定の中に入れず、ベタで書いておくと良いのかもしれない (スマートではない気がする)

./a.py

処理をべた書き

print("this is a")

./b.py

main 関数判定をする

if __name__ == "__main__":
  print("This is b")

./c.py

二つのスクリプトをimportする

import a
import b

exe

二つのスクリプトを import すると 処理がべた書きされている a.py の内容だけが実行される

python3 ./c.py 
this is a

ところで

  • ついつい最初、ものすごくぼんやりとしたイメージで main 関数というキーワードでググってしまったが、よく見ると全く関数ではなかった件。
  • main という関数も作れるが name という変数に収められた main という値とは全く関係ない。
def __main__():
  print("this is __main__ function")

if __name__ == "__main__":
  print('__name__ is ' + __name__)

  __main__()
python3 script.py

__name__ is __main__
this is __main__ function

で何?

  • 特殊変数 name には「直接実行された場合には main が」「importされた時にはスクリプトのモジュール名」が収まるらしい。(本当に?)

name (A Special variable) in Python - GeeksforGeeks

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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?