金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks
Python获取程序所在目录

解决__file__或sys.argv[0]在py2exe下失效的问题。

选自pathutils模块。
http://www.voidspace.org.uk/python/pathutils.html#get-main-dir

##############################################################################
# These functions get us our directory name
# Even if py2exe or another freeze tool has been used

def main_is_frozen():
    """Return ``True`` if we're running from a frozen program."""
    import imp
    return (
        # new py2exe
        hasattr(sys, "frozen") or
        # tools/freeze
        imp.is_frozen("__main__"))

def get_main_dir():
    """Return the script directory - whether we're frozen or not."""
    if main_is_frozen():
        return os.path.abspath(os.path.dirname(sys.executable))
    return os.path.abspath(os.path.dirname(sys.argv[0]))

##############################
 
posted on 2007-07-18 15:38 金庆 阅读(1255) 评论(0)  编辑 收藏 引用 所属分类: 6. Python

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理