确定pyInstaller生成的Python EXE中的应用程序路径 [英] Determining application path in a Python EXE generated by pyInstaller

查看:351
本文介绍了确定pyInstaller生成的Python EXE中的应用程序路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个驻留在单个.py文件中的应用程序.我已经能够让pyInstaller将其成功捆绑到Windows的EXE中.问题是,应用程序需要一个.cfg文件,该文件始终直接位于同一目录中的应用程序旁边.

I have an application that resides in a single .py file. I've been able to get pyInstaller to bundle it successfully into an EXE for Windows. The problem is, the application requires a .cfg file that always sits directly beside the application in the same directory.

通常,我使用以下代码构建路径:

Normally, I build the path using the following code:

import os
config_name = 'myapp.cfg'
config_path = os.path.join(sys.path[0], config_name)

但是,当从pyInstaller生成的EXE调用sys.path时,它似乎是空白的.当您运行python交互式命令行并尝试获取sys.path [0]时,也会发生相同的行为.

However, it seems the sys.path is blank when its called from an EXE generated by pyInstaller. This same behaviour occurs when you run the python interactive command line and try to fetch sys.path[0].

是否有更具体的方法来获取当前正在运行的应用程序的路径,以便我可以找到与其相对的文件?

Is there a more concrete way of getting the path of the currently running application so that I can find files that are relative to it?

推荐答案

我找到了解决方案.您需要检查应用程序是作为脚本运行还是作为冻结的exe运行:

I found a solution. You need to check if the application is running as a script or as a frozen exe:

import os
import sys

config_name = 'myapp.cfg'

# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
    application_path = os.path.dirname(sys.executable)
elif __file__:
    application_path = os.path.dirname(__file__)

config_path = os.path.join(application_path, config_name)

这篇关于确定pyInstaller生成的Python EXE中的应用程序路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆