py2exe编译后,如何取得exe的绝对路径

本文介绍了一种在Python中无论是否通过py2exe编译,都能获取到程序所在目录绝对路径的方法。该方法对于运行在不同环境下的程序尤其有用,如在网站中定位静态资源文件或记录日志。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

py2exe编译后,如何取得exe的绝对路径

 

 

 

官网的解决方案

 http://www.py2exe.org/index.cgi/WhereAmI

You want to know WHERE your .exe is

Why? Maybe, you are building a website and have a subdir ./static below the directory in which your .exe resides, from where you server all .css and .js that is static. Or, you put the logs right below the programs dir within ./log

See also  HowToDetermineIfRunningFromExe   for a shorter recipe

上面的链接

See also WhereAmI for another take on this problem.

ThomasHeller   posted this tip to the mailing list:

main_is_frozen()   returns  True   when running the exe, and  False   when  running from a script.

get_main_dir()   returns the directory name of the script or the directory  name of the exe - this is also sometimes useful.

 

切换行号显示
   1 
import
 imp
,
 os
,
 sys


2
3 def main_is_frozen ( ) :
4 return ( hasattr ( sys , "frozen" ) or # new py2exe
5 hasattr ( sys , "importers" ) # old py2exe
6 or imp . is_frozen ( "__main__" ) ) # tools/freeze
7
8 def get_main_dir ( ) :
9 if main_is_frozen ( ) :
10 return os . path . dirname ( sys . executable )
11 return os . path . dirname ( sys . argv [ 0 ] )
--结束链接

Problem

You cannot rely on  __file__ , because  __file__   is not there in the py2exed main-script.  You could try to rely on ".", the "Current Directory", but that only works if your application was started there. That may happen, but it is not guaranted.

Solution

 

import os
import jpath

if hasattr(sys,"frozen") and sys.frozen == "windows_exe":
p=jpath.path(os.path.abspath(sys.executable)).dirname()

now p contains the directory where your exe resides, no matter from where your exe has been called (maybe it is in the path)

"jpath" is the famous path module from  "Jason Orendorff"

Alternate Solution

The solution above will fail with a  UnicodeDecodeError   when using a Japanese (or Chinese/Korean, probably) version of Windows (XP + others?), and the path contains double-byte characters. This is because the  sys.executable   is in the file system encoding ('mbcs' on WinXP Japanese), and python tries to decode it to Unicode using the default Python encoding ('ascii'). The solution is to explicitly convert the path to Unicode using the default file system encoding. Additionally, checking only for a value of "windows_exe" will fail for a console application. I decided to live dangerously, and just test for "frozen" :-).

 

import os
import sys

def we_are_frozen():
"""Returns whether we are frozen via py2exe.
This will affect how we find out where we are located."""

return hasattr(sys, "frozen")


def module_path():
""" This will get us the program's directory,
even if we are frozen using py2exe"""

if we_are_frozen():
return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))

return os.path.dirname(unicode(__file__, sys.getfilesystemenco

### 解决 PyInstaller 打包 Python 文件为 EXE 后出现闪退的方法 当使用 PyInstaller 将 Python 文件打包成可执行文件 (EXE),并遇到程序启动即刻关闭的情况时,有几种常见的解决方法。 #### 使用 `-D` 参数打包成目录而非单个文件 为了更方便地调试和处理依赖关系,可以选择不将所有内容压缩至单一的 .exe 文件内。通过增加 `-D` 或 `--onedir` 命令行选项来指示 PyInstaller 创建一个包含应用程序及其所需库和支持文件的独立工作区[^1]: ```bash pyinstaller -D project.py ``` 这样做的好处是可以更容易访问日志和其他诊断信息,从而有助于定位潜在的问题所在。 #### 应用绝对路径调用 PyInstaller 如果系统报告无法识别 pyinstaller 命令,则建议采用其完整的安装位置作为前缀来进行操作。具体做法是从命令提示符窗口进入目标项目的根目录,并利用类似于以下方式输入完整路径下的工具名完成编译过程[^2]: ```bash C:\Path\To\Scripts\pyinstaller.exe myscript.py ``` 这种方法能够有效规避由于环境变量配置不当所引起的错误。 #### 修改 `.spec` 文件以适应特定需求 有时默认生成的 spec 配置并不能满足实际应用场景的要求,特别是涉及到外部数据文件读取的情况下。此时可以通过编辑由 PyInstaller 自动生成的 spec 文件,在其中显式声明额外的数据项或修改其他设置参数[^5]。例如,假设存在名为 config.yaml 的配置文档位于子文件夹 bayeslibs/config 中,那么可以在对应的列表里加入如下条目: ```python a = Analysis(['myscript.py'], pathex=['.'], binaries=None, datas=[('path/to/bayeslibs/config', 'bayeslibs/config')], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) ``` 上述更改使得最终产物能够在运行期间正确加载所需的辅助资料而不至于因为找不到它们而导致崩溃退出。 #### 处理模块导入失败的情形 尽管原文提到如果没有遭遇 "No module named..." 类型的信息则无需特别关注 pip 安装环节;然而实际上任何遗漏的重要第三方库都可能导致类似的异常终止现象发生。因此还是有必要确认所有必要的扩展均已妥善安置于本地环境中。可通过查阅官方文档获取最新的兼容版本号以及遵循推荐的最佳实践指南实施相应的部署措施。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值