activate venv
pip install pyinstaller==5.13.2
pip install psutil==6.1.0
pip install selenium==4.18.1
Install the required modules:
pyinstaller will create the .exe file;
psutil will be used to kill the child process generated to run the project and the venv;
selenium opens a google chrome window.
For this example we assume a Django project mysite in the Desktop and a virtual environment called venv.
import subprocess
import time
import psutil
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
cwd = "C:/Users/jaime/Desktop/mysite"
django_command = "activate venv && python manage.py runserver"
process = subprocess.Popen(django_command, cwd=cwd, shell=True)
chrome_options = Options()
chrome_options.add_experimental_option("useAutomationExtension", False)
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_argument("--window-size=1240,740")
chrome_options.add_argument("--app=http://localhost:8000")
driver = webdriver.Chrome(options=chrome_options)
try:
while True:
time.sleep(2)
driver.title
except Exception as e:
driver.quit()
for child in psutil.Process(process.pid).children(recursive=True):
child.terminate()
The options are removing the information bar from selenium saying it's a testing environment, setting a default windows size and removing the navigation bar. If not necessary remove. There are a lot more options available.
Creating the .exe
pyinstaller --onefile --noconsole --icon=logo.ico installer.py
There are some options here:
--onefile will make one single executable file, which is the goal;
--noconsole will execute the file without opening the command line
--icon will give a .ico image to the .exe icon file
Pyinstaller will generate 2 folders and one file. The .exe file is inside the dist folder.
If you ran pyinstaller without the icon and try to run it again, it probably will not apply the icon anymore unless you change the Python script name, for example to installer2.py, Windows seems to cache the icon for the same name.
The installer.py file will not be necessary anymore. You can delete it
Tested with: django==4.2 selenium==4.18.1 pyinstaller==5.13.2 psutil==6.1.0
20 Nov. 2024
|
Last Updated: 03 Dec. 2025
|
jaimedcsilva Related