I want to execute an exe file from a python file that is compiled using pyinstaller
I’m using the following code:
import subprocess, os, sys
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
new_path = resource_path("executable.exe")
print new_path
subprocess.Popen(new_path)
And I compile it using:
pyinstaller --add-binary executable.exe;exe -F incluse.py
Which creates incluse.exe and If I execute it I get the following error:
C:UsersMyUsernameAppDataLocalTemp_MEI13~1executable.exe
Traceback (most recent call last):
File "incluse.py", line 16, in <module>
File "subprocess.py", line 394, in __init__
File "subprocess.py", line 644, in _execute_child
WindowsError: [Error 2] The system cannot find the file specified
[21812] Failed to execute script incluse
What I want it to do is execute the executable.exe that I included, which should come up with a message box.
Advertisement
Answer
You can bundle another binary into your exe with pyinstaller using the --add-binary
option.
In your Python script you can then call the exe embedded within your exe by using subprocess.Popen(exe_path)
. You can use sys._MEIPASS
to access the temporary location that the exe will be found at in order to build the path to the exe.
Example
putty_launcher.py
import os
import sys
import subprocess
if getattr(sys, 'frozen', False):
base_path = sys._MEIPASS
else:
base_path = ""
exe_path = os.path.join(base_path, 'binariesputty.exe')
subprocess.Popen(exe_path)
Folder Structure
root
├── binaries
│ └── putty.exe
├── putty_launcher.py
In the root folder, execute:
pyinstaller --add-binary "binariesputty.exe;binaries" --onefile putty_launcher.py
This will then build an exe from the putty_launcher.py script which can successfully call the version of putty.exe that is embedded within the exe.