モジュール

import文を使ったモジュールの使用

>>>import math
>>>10*20*math.sin(math.radians(45))/2

from文を使うと以下のように記述できる

>>>from math import sin, radians
>>>10*20*sin(radians(45))/2

モジュールをインポートするときの挙動を以下のスクリプトファイル(testmodule.py)を作成して試した

#!/usr/bin/env python

import sys

a = 1
b = "some string"

def foo():
    print "This is function 'foo'"

print "this is top level"

if __name__== '__main__':
    print "this is code block"

最後のif文はトップレベルのブロックにあるがモジュールをインポートしても実行されない

>>>import testmodule
this is top level

しかし以下のようにモジュールファイルをPythonの引数として直接渡すとif文のブロックを実行する

>python testmodule.py
this is top level
this is code block