python脚本程序中如果需要获取程序自身所在的目录,一般会使用以下方法:
os.path.dirname(__file__)
__file__
变量是Python内置的全局变量,代表当前程序文件的全路径。
假如python脚本程序的路径为d:\demo\hello.py
,
那么__file__
变量的值就是d:\demo\hello.py
,
os.path.dirname(__file__)
的返回值就是d:\demo
但是使用py2exe编译成exe文件以后,会提示__file__
变量未被定义而报错。
可以在python脚本中使用以下代码来代替。
(参考py2exe的建议:http://www.py2exe.org/index.cgi/WhereAmI)
#当前程序无论是py代码,还是编译以后的exe文件,
#都用以下代码获取当前所在的目录
def module_path():
if hasattr(sys, "frozen"):
return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))
return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))
__my_dir__ = module_path()
以上的代码中,__my_dir__
就是当前程序所在的目录。