起動パスを知る

Python では、起動パスが __file__ に仕込まれています。

import os

s0 = __file__
s1 = os.path.abspath( s0 )
s2 = os.path.dirname( s1 )

print( "s0 is \"{0}\"".format( s0 ) )
print( "s1 is \"{0}\"".format( s1 ) )
print( "s2 is \"{0}\"".format( s2 ) )

print( "finish." )

下記が実行結果です。

PS C:\tmp> python test.py
s0 is "C:\tmp\test.py"
s1 is "C:\tmp\test.py"
s2 is "C:\tmp"
finish.