繁体   English   中英

os.path 在多个文件导入中使用 Pyinstaller 指向不正确的位置

[英]os.path points to incorrect location with Pyinstaller in multiple file imports

我有两个 python 文件main.pyaux.py位于同一目录中。

main.py包含以下代码:

import aux
print "aux imported"

aux.py包含以下代码:

import os
current_path = os.path.dirname(os.path.realpath(__file__))
print current_path

现在,当我使用pyinstaller --onefile main.pypyinstaller --onefile main.py捆绑到 .exe 并尝试运行生成的 main.exe 时,我得到以下输出:

C:\Users\vimanyua\AppData\Local\Temp\3\_MEI90~1
aux imported

可以看出,pyinstaller 使用临时文件夹来定位我的 aux.py,这给我带来了很多问题,因为我的实际代码中的aux.py读取位于其当前目录中的其他同级文件。 如果我只是为aux.py创建一个 .exe 就像pyinstaller --onefile aux.py - 它会输出正确的路径

C:\\Users\\vimanyua\\Documents\\pyinstaller test\\dist

我阅读了 此链接上的文档,因为我想先运行aux.py ,所以我aux.py创建一个这样的 exe 文件 -

pyinstaller --onefile --runtime-hook=aux.py main.py

它创建了一个main.exe ,它首先运行aux.py ,然后运行main.exe 当它运行 aux.py 时,我得到以下输出:

C:\Users\vimanyua\Documents\pyinstaller test\dist
C:\Users\vimanyua\AppData\Local\Temp\3\_MEI90~1
aux imported

main.py实际使用来自多个函数/变量aux.py让我无法摆脱的import aux在声明中main.py ,我真的不想代码合并到一个单一的文件。

任何人都可以为我提供任何指导吗? 谢谢!

而不是使用__file__来引用路径,请使用sys._MEIPASS 要引用aux.py文件的同级文件,请使用以下帮助函数:

import sys
import os

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

例如,如果要在aux.py中读取名为readme.txt同级文件,则可以引用为:

filepath = resource_path('readme.txt')

此处查看文档。

尝试在没有 --onefile 的情况下打包,这对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM