简体   繁体   中英

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

I have two python files main.py and aux.py located in the same directory.

main.py contains the following code:

import aux
print "aux imported"

aux.py contains the following code:

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

Now, when I bundle main.py to .exe using pyinstaller --onefile main.py and try running the main.exe which gets produced, I get the following output:

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

As can be seen, pyinstaller using a temp folder to locate my aux.py which is creating a lot of issue for me because aux.py in my actual code reads other sibling files located in its current directory. If I just create a .exe for aux.py like pyinstaller --onefile aux.py - it outputs the correct path

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

I read the documentation at this link and as I want to run aux.py first, I trie creating an exe file like this -

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

It creates a single main.exe which runs aux.py first and then runs main.exe . When it runs aux.py I get following output:

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

My main.py actually uses multiple functions/variables from aux.py so I cannot get rid of the import aux statement in main.py and I really do not want to merge the code into a single file.

Can anyone please provide me any guidance? Thanks!

Instead of use __file__ to refer to path, please use sys._MEIPASS . To refer to the sibling of the aux.py file, please use this helper function:

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)

For example, if in your aux.py you want to read sibling files named readme.txt , you can refer as:

filepath = resource_path('readme.txt')

See the docs here .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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