Yung Lin Ma
Yung Lin Ma

Reputation: 131

Relative path setting fail via pyinstaller

I am using python 3.6 and windows 10.

I am trying to pack an image by pyinstaller and trying to run the image somewhere else.

It works fine and I packs it via pyinstaller. However, I doesn't work when I remove the image in the folder

All I want is to pack the image into the .exe file. However I am not sure where went wrong with it...

First of all, I have a folder called 'pytest' which included an image called '1up.png' and a 'Rtest.py as below:

import sys, os
from PIL import Image
os.chdir(r"C:\Users\lawre\Desktop\pytest")

def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

image = Image.open('1up.png')
image.show()

It can opens the image successfully! And then I pack it by pyinstaller:

pyinstaller.exe -F -w RTest.py

Rtest.spec generated and I open it and add a code after 'a.datas,':

[('\\1up.png','C:\\Users\\lawre\\Desktop\\pytest\\1up.png','DATA')],

Save and close 'Rtest.spec' file and pack it by pyinstaller again:

pyinstaller.exe -F -w RTest.spec

And I suppose all done because the final 'Rtest.exe' generated and work fine to open the image, but It doesn't work when I remove '1up.png' inside pytest folder.

Error message is: Failed to execute script RTest

Does anyone know how to solve it or suggest me how to rewrite the code?

Thanks in advance

Lawrence

Upvotes: 0

Views: 483

Answers (1)

Masoud Rahimi
Masoud Rahimi

Reputation: 6031

There are two problems with your way:

  1. You are not calling resource_path at all, you need to call your file with this function in your code. Also, you don't need to change your current directory.

  2. I personally don't recommend you edit spec file manually unless you need to. Your syntax seems wrong and you need to add your file to datas=[] in Analysis part. Anyway just use add-data flag.

script file:

import sys
import os
from PIL import Image


def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)


image = Image.open(resource_path('1up.png'))
image.show()

command:

pyinstaller -F --add-data "./1up.png;." script.py

Upvotes: 1

Related Questions