[PYTHON] How to create * .spec files for pyinstaller.

You can use the created python script to create a MacOS application using pyinstaller.

At first I used py2app, but the result file size was different as below. --Py2app result: 35MB --Pyinstaller result: 25MB There is no reason not to use Pyinstaller. Installation is now possible with PIP. (I couldn't do it last year)

pip install pyinstaller

That's it

It is recommended to drive the pyinstaller through * .spec files.

The basic structure of the spec file is as follows.

# -*- mode: python -*-
# filename = Main.spec

a = Analysis(['Main.py'],
             pathex=['/Users/.../ProgramNameDir'],
             hiddenimports=[],
             hookspath=None,
             runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='Main',
          debug=False,
          strip=None,
          upx=True,
          console=False , icon='mainIcon.ico')
app = BUNDLE(exe,
             name='Main.app',
             icon='mainIcon.ico')

In this case, read main.py and create Main.app. icon wears mainIcon.ico.

Main.py exists in "/ Users / ... / ProgramNameDir" and refers to the lib file of "./lib" under it. So, modify it a little so that the * .spec file can recognize "./lib".

# -*- mode: python -*-
# filename = Main.spec

###personal./Code to recognize libs###
import sys 
myLibPath = './libs'
sys.path.append(myLibPath)
############################

a = Analysis(['Main.py'],
             pathex=['/Users/.../ProgramNameDir'],
             hiddenimports=[],
             hookspath=None,
             runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='Main',
          debug=False,
          strip=None,
          upx=True,
          console=False , icon='mainIcon.ico')
app = BUNDLE(exe,
             name='Main.app',
             icon='mainIcon.ico')

There is another problem. Main.py uses the image file in / Users / ... / ProgramNameDir / img. This cannot be read by the final app even if it is added in sys.path.append. This is because the image file handling mechanism is different.

When the application created by pyinstaller is driven, necessary files (image files, etc.) are copied in the temporary folder (temp folder) at the location "_MEIPASS". Therefore, it is necessary to recognize "_MEIPASS" in the * .py code.

Add this function in Main.py.

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

Then convert the image reference child in the code. example:

"./img/Title.png " --> resource_path("./img/Title.png ")



 Add Tree () to the * .spec file.

-- mode: python --

#filename = Main.spec import sys myLibPath = './libs' sys.path.append(myLibPath) a = Analysis(['Main.py'], pathex=['/Users/.../ProgramNameDir'], hiddenimports=[], hookspath=None, runtime_hooks=None) pyz = PYZ(a.pure) exe = EXE(pyz, Tree('img',prefix='img'), #<--Folder name with the image to add a.scripts, a.binaries, a.zipfiles, a.datas, name='Main', debug=False, strip=None, upx=True, console=False , icon='mainIcon.ico') app = BUNDLE(exe, name='Main.app', icon='mainIcon.ico')


 I have a MacBook pro. That is, I am using Retina Display. If you make an application made with pyinstaller as it is, the message box and dialog will appear blurred on the Retina Display, so it is ugly.
 Add info_plist to BUNDLE to solve it.


-- mode: python --

#filename = Main.spec import sys myLibPath = './libs' sys.path.append(myLibPath) a = Analysis(['Main.py'], pathex=['/Users/.../ProgramNameDir'], hiddenimports=[], hookspath=None, runtime_hooks=None) pyz = PYZ(a.pure) exe = EXE(pyz, Tree('img',prefix='img'), a.scripts, a.binaries, a.zipfiles, a.datas, name='Main', debug=False, strip=None, upx=True, console=False , icon='mainIcon.ico') app = BUNDLE(exe, name='Main.app',        info_plist={ 'NSHighResolutionCapable': 'True'}, #<-- Option for High Resolution icon='mainIcon.ico')


 This is about the end.

#### **`pyinstaller Main.spec`**
```spec

 You can make an app with.

 In the case of py2exe and py2app, there are many cases, but in the case of pyinstaller, there are not so many, so I recorded it for organization.


Recommended Posts

How to create * .spec files for pyinstaller.
How to create large files at high speed
How to create a shortcut command for LINUX
[Go] How to create a custom error for Sentry
How to create a local repository for Linux OS
How to create a SAS token for Azure IoT Hub
[Python Kivy] How to create an exe file with pyinstaller
[For non-programmers] How to walk Kaggle
How to create a Conda package
How to create your own Transform
How to create an email user
How to create a virtual bridge
How to create / delete symbolic links
How to create a Dockerfile (basic)
How to create a config file
How to create a label (mask) for segmentation with labelme (semantic segmentation mask)
How to create a git clone folder
How to create an NVIDIA Docker environment
[Python] Organizing how to use for statements
How to install Windows Subsystem For Linux
How to use Pylint for PyQt5 apps
How to create a repository from media
How to use "deque" for Python data
How to find large files on Linux
How to read CSV files in Pandas
How to use fingerprint authentication for KDE
How to automatically upload .gpx files to Strava
How to create sample CSV data with hypothesis
How to use MkDocs for the first time
How to create a Python virtual environment (venv)
How to make Spigot plugin (for Java beginners)
[Python] How to easily create Training, Validation, Test folders for multiple classification problems
How to create a function object from a string
Summary of how to import files in Python 3
How to use Template Engine for Network Engineer
How to create explanatory variables and objective functions
How to create a JSON file in Python
How to create an OCF compliant resource agent
What I learned by implementing how to create a Default Box for SSD
How to install Python for pharmaceutical company researchers
How to use data analysis tools for beginners
[For recording] Keras image system Part 1: How to create your own data set?
How to check / extract files in RPM package
How to create data to put in CNN (Chainer)
How to write a ShellScript Bash for statement
How to get the files in the [Python] folder
[Note] How to create a Ruby development environment
How to create a Kivy 1-line input box
How to create a multi-platform app with kivy
[ESXi (vCenter)] How to add NIC for CentOS 7.3
How to create a Rest Api in Django
How to make Python faster for beginners [numpy]
[For beginners] How to study programming Private memo
How to find the correlation for categorical variables
[Note] How to create a Mac development environment
How to force build TensorFlow 2.3.0 for CUDA11 + cuDNN8
How to set CPU affinity for process threads
How to create random numbers with NumPy's random module
Read the Python-Markdown source: How to create a parser
Create a dataset of images to use for learning
How to check for missing values (Kaggle: House Prices)