using nuitka standalone can the exe be outside ie one lavel up from the dist folder
- User
using nuitka standalone can the exe be outside ie one lavel up from the dist folder
- Assistant
When you use Nuitka with the
--standaloneoption, by default it creates adistfolder inside your current directory, and places the executable and all required files inside thatdistfolder.Your question is whether the final
.exefile can be placed outside thedistfolder, for example one level up.Short answer:
No, not directly. Because
--standalonemode relies on the presence of all the dependency files residing in the same folder as the executable (or subfolders nearby) to allow the executable to run independently.If you move the
.exefile one level up (outside thedistfolder) and leave the supporting files in thedistfolder, the executable will not work as expected, since it cannot find its dependency files (DLLs, extension modules, Python runtime, etc.).
Explanation:
-
The
distfolder created by Nuitka contains all files needed to run the program in standalone mode:- The executable.
- DLLs.
- Python standard library extensions.
- Compiled modules.
- Any shared data files.
-
These files are structured so that relative paths work fine inside the
distfolder. -
The executable is not self-contained in a single file; it needs those files to work.
Workarounds or Suggestions
-
Custom Output Folder
Nuitka allows you to specify the output folder name with
--output-diroption:nuitka --standalone --output-dir=../my_folder your_script.pyThis will put the entire
distfolder contents into../my_folder.However, the structure still keeps everything together.
-
Move the entire
distfolderYou can rename/move the entire
distfolder or its contents to some other place. -
Bundle into a single executable
Nuitka also supports
--onefile. The onefile mode bundles everything into a single executable file. That executable can be placed anywhere.Example:
nuitka --standalone --onefile your_script.pyResult: a single
.exethat can be placed anywhere, no additional files needed. -
Manual attempt
You could try moving just the
.exeone level up and copy all dependency files next to it. But you have to replicate exact folder structure and dependency files, which is complicated and error-prone.
Summary
- Without
--onefile, output is a folder with all dependencies. - Executable depends on those files being in the same folder (or relative locations).
- Moving .exe outside that folder breaks relative resource loading.
- Use
--onefilefor a single executable that you can place anywhere. - Use
--output-dirto control where the standalone folder is created.
If your goal is a standalone executable placed one level up without a dist folder, use:
nuitka --standalone --onefile your_script.pyIf you want the entire standalone folder somewhere else, use:
nuitka --standalone --output-dir=../your_target_folder your_script.py
Let me know if you'd like a specific example or assistance with your Nuitka command!
-
- User
can you give sample code to replicate this in java import sys import os from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout from PySide6.QtCore import Qt
class MainWindow(QWidget): def init(self): super().init() self.setWindowTitle("Button Text Loader")
self.button = QPushButton("Load Text from preferences.txt") self.button.clicked.connect(self.load_text_from_file) layout = QVBoxLayout() layout.addWidget(self.button, alignment=Qt.AlignCenter) self.setLayout(layout) def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller/Nuitka exe """ try: # PyInstaller/Nuitka creates this attribute for the temp folder containing bundled files base_path = sys._MEIPASS # PyInstaller style except AttributeError: base_path = os.path.abspath(os.path.dirname(sys.argv[0])) return os.path.join(base_path, relative_path) def load_text_from_file(self): # Get the folder of the running script base_dir = os.path.dirname(os.path.abspath(__file__)) # Construct the file path to the preferences.txt inside "resources" subfolder file_path = os.path.join(base_dir, "resources", "preferences.txt") try: with open(file_path, "r", encoding="utf-8") as file: text = file.read().strip() self.button.setText(text) except FileNotFoundError: self.button.setText("preferences.txt not found!")if name == "main": app = QApplication(sys.argv) window = MainWindow() window.resize(300, 100) window.show() sys.exit(app.exec())
- Assistant
Certainly! Here's the equivalent Java code using Swing for the GUI, which replicates your PySide6 example, including reading
preferences.txtfrom aresourcesfolder relative to the running.classor.jarexecutable, and updating the button text accordingly.import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.*; import java.nio.charset.StandardCharsets; public class MainWindow extends JFrame { private JButton button; public MainWindow() { setTitle("Button Text Loader"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 100); button = new JButton("Load Text from preferences.txt"); button.addActionListener(this::loadTextFromFile); // Center the button in the frame using BorderLayout and JPanel JPanel panel = new JPanel(); panel.setLayout(new FlowLayout(FlowLayout.CENTER)); panel.add(button); add(panel); setLocationRelativeTo(null); // Center window on screen } private void loadTextFromFile(ActionEvent event) { // Get absolute path to the folder containing the running .class or .jar String baseDir = getBaseDir(); // Construct file path to preferences.txt inside "resources" folder File prefFile = new File(baseDir, "resources/preferences.txt"); if (prefFile.exists()) { try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(prefFile), StandardCharsets.UTF_8))) { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } String text = sb.toString().trim(); button.setText(text); } catch (IOException e) { button.setText("Error reading preferences.txt"); e.printStackTrace(); } } else { button.setText("preferences.txt not found!"); } } private String getBaseDir() { /* * This method tries to detect the base directory from which the program is running, * similar to what you do in Python with sys._MEIPASS or __file__. * * This works both when run from .class files or from a bundled .jar. */ try { String path = MainWindow.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); File file = new File(path); if (file.isFile()) { // Running from a jar file, so get the parent folder of the jar return file.getParentFile().getAbsolutePath(); } else { // Running from .class files in a folder - path points to classes folder, get its parent folder return file.getAbsolutePath(); } } catch (Exception e) { e.printStackTrace(); // Fallback: current working directory return new File(".").getAbsolutePath(); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { MainWindow window = new MainWindow(); window.setVisible(true); }); } }
Explanation:
- Creating the window: By extending
JFrame. - Button: A
JButtonwhose text updates after loading from the file. - Layout: Center using a
FlowLayoutinside aJPanel. - Reading the file:
- Base directory determined by where the
.classor.jaris located. - Looks for
resources/preferences.txtrelative to that. - Reads text and updates button text.
- Base directory determined by where the
- Error handling: Changes button text if file not found or error reading.
Folder structure to run this Java example:
your_project/ │ ├── resources/ │ └── preferences.txt │ └── MainWindow.javaCompile:
javac MainWindow.javaRun:
java MainWindowThe program will look for the file at
./resources/preferences.txtrelative to your current working directory or the jar location if bundled later.
If you want this to work the same when packaged as a jar, keep the
resourcesfolder next to the jar, not inside it (or load resource files from inside the jar via the classloader, which is a different approach).
If you want me to give you the code variant that loads the file from inside the jar's resources (compiled inside the jar file), let me know!
- Creating the window: By extending
- User
can you give me a pyinstaller script equiv to this @echo off REM Compile Python script into onefile standalone executable using Nuitka (updated syntax)
REM Change this to your Python script filename set SCRIPT=main.py
REM Run Nuitka to compile into a onefile exe for Windows with updated options python -m nuitka ^ --standalone ^ --windows-console-mode=disable ^ --enable-plugin=pyside6 ^ %SCRIPT%
pause
- Assistant
Certainly! To get a PyInstaller equivalent batch script that compiles a Python script into a single-file standalone executable for Windows, using your example as a basis, here is a corresponding
.batscript for PyInstaller:@echo off REM Compile Python script into onefile standalone executable using PyInstaller REM Change this to your Python script filename set SCRIPT=main.py REM Run PyInstaller to compile into a onefile exe for Windows with windowed mode (no console) pyinstaller ^ --onefile ^ --windowed ^ %SCRIPT% pause
Explanation of PyInstaller options used:
--onefile: Bundle everything into a single executable file.--windowed: Disable the console window (equivalent to--windows-console-mode=disablein Nuitka).%SCRIPT%: Your Python script name.
Additional notes:
- PyInstaller automatically detects PySide6 imports and packages them. If you experience any missing modules from PySide6, you can add the
--hidden-importoption, but usually it's not necessary. - Output executable will be placed in the
distfolder. - If you want console output, remove
--windowed. - You can customize the output directory with
--distpath=<folder>.
Example - full batch script in one snippet:
@echo off REM Compile main.py into single-file executable using PyInstaller set SCRIPT=main.py pyinstaller --onefile --windowed %SCRIPT% pauseRun this batch file in the command prompt inside your project folder where
main.pyis located.
If you want the equivalent with console enabled, omit
--windowed. For example:pyinstaller --onefile %SCRIPT%
Let me know if you want me to add extra settings like icon, additional data files, or anything else!
- User
amend to create a shortcut to the xex once generated one level up @echo off REM Compile Python script into onefile standalone executable using PyInstaller
REM Change this to your Python script filename set SCRIPT=main.py
REM Run PyInstaller to compile into a onefile exe for Windows with windowed mode (no console) pyinstaller ^ --onedir ^ --windowed ^ %SCRIPT%
pause
- Assistant
Certainly! Your current script uses
--onedir, which generates the executable inside adist\folder along with dependencies. You want to:- Compile the script with PyInstaller using
--onedir. - Create a shortcut to the generated
.exeplaced one level up from thedistfolder (i.e., next to your project folder or wherever your batch runs).
Amended
.batscript to do this:@echo off REM Compile Python script into onefile standalone executable using PyInstaller (onedir) REM Change this to your Python script filename set SCRIPT=main.py REM Run PyInstaller to compile into an onedir exe for Windows with windowed mode (no console) pyinstaller ^ --onedir ^ --windowed ^ %SCRIPT% REM Pause to let PyInstaller finish REM (optional, since pyinstaller blocks until done) REM pause REM Variables for paths set DIST_DIR=dist set PROJECT_DIR=%cd% set EXE_NAME=%~nSCRIPT%.exe REM Path to the actual .exe in dist\<script name>\ set EXE_PATH=%PROJECT_DIR%\%DIST_DIR%\%~nSCRIPT%\%EXE_NAME% REM Shortcut location: one folder up from current dir REM Assuming %cd% is your script root folder, REM one level up is %cd%\.. set SHORTCUT_DIR=%PROJECT_DIR%\.. set SHORTCUT_PATH=%SHORTCUT_DIR%\%EXE_NAME% - Shortcut.lnk echo Creating shortcut to %EXE_PATH% at %SHORTCUT_PATH% powershell -Command ^ "$WScriptShell = New-Object -ComObject WScript.Shell; ^ $Shortcut = $WScriptShell.CreateShortcut('%SHORTCUT_PATH%'); ^ $Shortcut.TargetPath = '%EXE_PATH%'; ^ $Shortcut.WorkingDirectory = '%PROJECT_DIR%\%DIST_DIR%\%~nSCRIPT%'; ^ $Shortcut.WindowStyle = 1; ^ $Shortcut.Save()" echo Shortcut created. pause
How this works:
-
Runs PyInstaller with
--onedirand--windowedon your script. -
The
.exewill be in:dist\<script_name>\<script_name>.exe -
The shortcut (
.lnk) is created one folder above your current dir (i.e.,%cd%\..) pointing to the.exeinsidedist\. -
PowerShell is used via
-Commandto create the Windows shortcut using the COM objectWScript.Shell.
Notes:
- If your batch script runs from another folder, adjust
%PROJECT_DIR%accordingly (e.g.,%~dp0for the batch file folder). - The shortcut name is set to
<scriptname>.exe - Shortcut.lnk. - The
WorkingDirectoryis set to the folder containing the.exeto ensure relative file access works.
Example assumptions:
- You run the batch inside your project folder containing
main.py. dist\main\main.exeis created.- Shortcut created at parent folder (i.e., one up from your project folder).
If you want the shortcut placed somewhere else or with a custom name, feel free to ask!
- Compile the script with PyInstaller using
- User
The following usage of the path operator in batch-parameter substitution is invalid: %~nSCRIPT%.exe
- Assistant
The error message
The following usage of the path operator in batch-parameter substitution is invalid: %~nSCRIPT%.exeis because
%~nsyntax only applies to a batch parameter (like%1,%2, etc.), but here you're trying to use it on an environment variable%SCRIPT%.How to fix this:
You can’t do
%~nSCRIPT%— instead, you should assign it properly.
Correct way to get the filename without extension from a variable in batch:
set SCRIPT=main.py for %%f in ("%SCRIPT%") do set SCRIPT_NAME=%%~nf- This sets
SCRIPT_NAMEto the filename part ofmain.py, i.e.,main.
So, the fixed batch script with shortcut creation becomes:
@echo off REM Compile Python script into onedir standalone executable using PyInstaller REM Change this to your Python script filename set SCRIPT=main.py REM Extract filename without extension into SCRIPT_NAME variable for %%f in ("%SCRIPT%") do set SCRIPT_NAME=%%~nf REM Run PyInstaller to compile into an onedir exe for Windows with windowed mode (no console) pyinstaller ^ --onedir ^ --windowed ^ %SCRIPT% REM Paths set DIST_DIR=dist set PROJECT_DIR=%cd% set EXE_NAME=%SCRIPT_NAME%.exe REM Path to the actual .exe in dist\<script name>\ set EXE_PATH=%PROJECT_DIR%\%DIST_DIR%\%SCRIPT_NAME%\%EXE_NAME% REM Shortcut location: one folder up from current dir set SHORTCUT_DIR=%PROJECT_DIR%\.. set SHORTCUT_PATH=%SHORTCUT_DIR%\%EXE_NAME% - Shortcut.lnk echo Creating shortcut to %EXE_PATH% at %SHORTCUT_PATH% powershell -Command ^ "$WScriptShell = New-Object -ComObject WScript.Shell; ^ $Shortcut = $WScriptShell.CreateShortcut('%SHORTCUT_PATH%'); ^ $Shortcut.TargetPath = '%EXE_PATH%'; ^ $Shortcut.WorkingDirectory = '%PROJECT_DIR%\%DIST_DIR%\%SCRIPT_NAME%'; ^ $Shortcut.WindowStyle = 1; ^ $Shortcut.Save()" echo Shortcut created. pause
Explanation
-
We first run:
for %%f in ("%SCRIPT%") do set SCRIPT_NAME=%%~nfto get the name without extension into
SCRIPT_NAME. -
Then use
%SCRIPT_NAME%wherever you want the base filename.
This will get rid of your
%~nSCRIPT%invalid substitution error.
Feel free to ask if you'd like help to make it more robust or easily reusable!
- This sets
- User
Creating shortcut to C:\DEV\Nuitka Tests\dist\main\main.exe at C:\DEV\Nuitka Tests..\main.exe - Shortcut.lnk ^ : The term '^' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:54
- $WScriptShell = New-Object -ComObject WScript.Shell; ^
-
~- CategoryInfo : ObjectNotFound: (^:String) [], CommandNotFoundException
- FullyQualifiedErrorId : CommandNotFoundException
'$Shortcut' is not recognized as an internal or external command,
- Assistant
The issue you are encountering arises because the PowerShell command inside the batch file uses
^line continuation characters that are interpreted literally by PowerShell rather than being processed by the Windows batch parser.When you use PowerShell's
-Commandfrom a batch script, you need to either:- Write the entire PowerShell command as a single line without batch-style line continuations (
^), or - Separate your PowerShell script into a
.ps1file and invoke that separately.
How to fix your batch script:
Replace the PowerShell command by a single-line command, no caret (
^) line continuations.Modified section of your batch file:
powershell -Command "$WScriptShell = New-Object -ComObject WScript.Shell; $Shortcut = $WScriptShell.CreateShortcut('%SHORTCUT_PATH%'); $Shortcut.TargetPath = '%EXE_PATH%'; $Shortcut.WorkingDirectory = '%PROJECT_DIR%\\%DIST_DIR%\\%SCRIPT_NAME%'; $Shortcut.WindowStyle = 1; $Shortcut.Save()"
Full fixed batch script snippet:
@echo off REM Compile Python script into onedir standalone executable using PyInstaller REM Change this to your Python script filename set SCRIPT=main.py REM Extract filename without extension into SCRIPT_NAME variable for %%f in ("%SCRIPT%") do set SCRIPT_NAME=%%~nf REM Run PyInstaller to compile into an onedir exe for Windows with windowed mode (no console) pyinstaller --onedir --windowed %SCRIPT% REM Paths set DIST_DIR=dist set PROJECT_DIR=%cd% set EXE_NAME=%SCRIPT_NAME%.exe REM Path to the actual .exe in dist\<script name>\ set EXE_PATH=%PROJECT_DIR%\%DIST_DIR%\%SCRIPT_NAME%\%EXE_NAME% REM Shortcut location: one folder up from current dir set SHORTCUT_DIR=%PROJECT_DIR%\.. set SHORTCUT_PATH=%SHORTCUT_DIR%\%EXE_NAME% - Shortcut.lnk echo Creating shortcut to %EXE_PATH% at %SHORTCUT_PATH% powershell -Command "$WScriptShell = New-Object -ComObject WScript.Shell; $Shortcut = $WScriptShell.CreateShortcut('%SHORTCUT_PATH%'); $Shortcut.TargetPath = '%EXE_PATH%'; $Shortcut.WorkingDirectory = '%PROJECT_DIR%\\%DIST_DIR%\\%SCRIPT_NAME%'; $Shortcut.WindowStyle = 1; $Shortcut.Save()" echo Shortcut created. pause
Explanation:
- No caret continuation characters, the whole PowerShell command is passed as one argument string.
- Escape backslashes in the Windows-style paths inside PowerShell if needed, i.e.,
\\inside the string. - Paths like
%PROJECT_DIR%\%DIST_DIR%\%SCRIPT_NAME%will be expanded by batch first and passed as literals to PowerShell.
Optional improvements:
If your paths contain spaces (e.g.,
C:\DEV\Nuitka Tests\...), it’s safer to quote variables in PowerShell:powershell -Command "$WScriptShell = New-Object -ComObject WScript.Shell; $Shortcut = $WScriptShell.CreateShortcut('%SHORTCUT_PATH%'); $Shortcut.TargetPath = '%EXE_PATH%'; $Shortcut.WorkingDirectory = '%PROJECT_DIR%\\%DIST_DIR%\\%SCRIPT_NAME%'; $Shortcut.WindowStyle = 1; $Shortcut.Save()"This passes the paths as strings including spaces.
Let me know if you want me to create a standalone PowerShell script or another approach!
- Write the entire PowerShell command as a single line without batch-style line continuations (
- User
amend so that the resources folder is found one level up from the exe
- Assistant
Certainly! To amend your PyInstaller-compiled executable so that at runtime it looks for the
resourcesfolder one level up from the executable location, you need to adjust your Python code that computes the resource path accordingly.Below is a typical pattern for this, and I'll also summarize what you need to do in your batch script or packaging:
1. Adjust Python code for resource path
Imagine your exe is here (after PyInstaller dist):
my_project/dist/myapp.exeYour
resourcesfolder is one level abovedist:my_project/resources/preferences.txtYou want your Python code (running inside
myapp.exe) to look at..\resources\preferences.txt.
Python function to get resource path one level above executable
import sys import os def resource_path(relative_path): """Get path to resource folder/file relative to exe When PyInstaller bundles the exe: sys._MEIPASS points inside temporary extraction folder, so we use its path as base. Then, since your resources is **one level up** from executable, go one level up from that base folder. When running as normal script: __file__ is used and goes one level up from script folder. """ try: # PyInstaller creates this temporary folder and sets this attr base_path = sys._MEIPASS except AttributeError: # When running normally (not bundled) base_path = os.path.abspath(os.path.dirname(__file__)) # One level up from base_path base_path = os.path.abspath(os.path.join(base_path, "..")) # Return final absolute path return os.path.join(base_path, relative_path)
Example usage in your
load_text_from_filemethoddef load_text_from_file(self): file_path = resource_path(os.path.join("resources", "preferences.txt")) try: with open(file_path, "r", encoding="utf-8") as file: text = file.read().strip() self.button.setText(text) except FileNotFoundError: self.button.setText("preferences.txt not found!")
2. Check your packaging / folder layout
Your folder structure after packaging should be something like:
my_project/ ├── dist/ │ └── myapp.exe ├── resources/ │ └── preferences.txt └── your_script.py
3. Optional: PyInstaller .spec file or command
Since your resources are outside the bundled directory and you want to keep them external, do NOT bundle the
resourcesfolder inside the exe/dist.Just keep
resourcesfolder adjacent outside your exe's folder, and rely on the runtime code locating that folder one level up.
Summary
- Modify your Python code as shown to look one level UP from executable folder.
- Keep
resourcesfolder next to the parent folder of the.exe. - Ensure your PyInstaller or Nuitka command does not bundle
resourcesif you want it external. - Always test your exe with
resourcesplaced one level above the exe.
If you'd like, I can also provide a Java equivalent for this path logic, or help with your batch/build scripts!
- User
this will now be built as onedir not onefile
- Assistant
Got it! When building with
--onedirmode (not--onefile), your executable lives inside a folder (dist/<appname>/), along with all the dependencies. So:- The
.exeis at:dist/<appname>/<appname>.exe - You want your app at runtime to find the
resourcesfolder one level up from the.exefolder—i.e.,dist/resources/or possibly relative to where you place it.
Summary & recommended approach:
- Your folder structure on disk after build could be:
dist/ │ ├── <appname>/ <-- contains exe and dependencies │ └── <appname>.exe │ └── resources/ └── preferences.txt- Or alternatively (more common):
your_project/ ├── dist/ │ └── <appname>/ │ └── <appname>.exe ├── resources/ │ └── preferences.txt
Key Python code to locate
resourcesfolder one level above exe folderimport os import sys def resource_path(relative_path): """ Get an absolute path to resource, searching ONE level above executable folder. Works when running from onedir build or normal script. """ try: # PyInstaller temp folder for onefile; for onedir this usually does not exist base_path = sys._MEIPASS except AttributeError: # Fallback to directory of executable or script if getattr(sys, 'frozen', False): # Onedir build: sys.executable points to .exe inside 'dist/<appname>/' base_path = os.path.dirname(sys.executable) else: # Normal script mode base_path = os.path.abspath(os.path.dirname(__file__)) # Go one directory up from base_path (one level above exe folder) base_path = os.path.abspath(os.path.join(base_path, "..")) return os.path.join(base_path, relative_path)
Usage example in your code:
def load_text_from_file(self): file_path = resource_path(os.path.join("resources", "preferences.txt")) try: with open(file_path, "r", encoding="utf-8") as file: text = file.read().strip() self.button.setText(text) except FileNotFoundError: self.button.setText("preferences.txt not found!")
Why this works in
--onedirmode- In onedir mode, your executable is in
dist/<appname>/. sys.executablepoints to the full path of that executable.- Going one directory up from
sys.executableputs you indist/, so"resources/preferences.txt"resolves todist/resources/preferences.txtif you've placed your resources folder there.
Very important: your folder layout for this to work
If you want your resources outside
dist/, e.g., one level abovedist, adjust the code accordingly:- If resources is in the project root (
your_project/resources), and your exe is inyour_project/dist/<appname>, then you'd go two levels up:
base_path = os.path.abspath(os.path.join(base_path, "..", ".."))You can customize that depending on where you actually place
resources.
Example folder structure for two-level up resources:
your_project/ ├── resources/ │ └── preferences.txt └── dist/ └── <appname>/ └── <appname>.exe-> Then use:
base_path = os.path.abspath(os.path.join(base_path, "..", ".."))
Summary for
--onedir- Use
sys.executableto locate exe path. - Go one level up to get to a sibling folder (e.g.
dist/resources). - Adjust your folder structure or the number of
..in path accordingly. - Do not rely on
sys._MEIPASS(which is mainly for onefile builds).
If you want me to generate a complete minimal working example or help with your packaging script to place files accordingly, I can do that!
- The
- User
amend so that the resources folder can be found next to the exe, onedir pyinstaller build
- Assistant
Certainly! If you want your
resourcesfolder to be next to the executable in a PyInstaller--onedirbuild (i.e.,resourcesis a sibling folder of your.exeinside the same directory), the Python code should look forresourcesinside the same directory as the.exe.
Folder layout for this scenario
dist/ └── myapp/ ├── myapp.exe └── resources/ └── preferences.txt
Updated Python
resource_pathfunctionimport sys import os def resource_path(relative_path): """ Get absolute path to resource next to exe (for onedir PyInstaller builds). """ try: # When bundled by PyInstaller, sys.executable points to the exe location base_path = os.path.dirname(sys.executable) except Exception: # Fallback for normal Python scripts base_path = os.path.abspath(os.path.dirname(__file__)) return os.path.join(base_path, relative_path)
Usage example
def load_text_from_file(self): file_path = resource_path(os.path.join("resources", "preferences.txt")) try: with open(file_path, "r", encoding="utf-8") as file: text = file.read().strip() self.button.setText(text) except FileNotFoundError: self.button.setText("preferences.txt not found!")
Explanation
sys.executablecontains the full path to the running.exe.os.path.dirname(sys.executable)is the folder where your.exelives.- So
resources/preferences.txtis looked for inside the same folder as the.exe. - This works perfectly in
--onedirmode when resources is included alongside the executable folder.
Important
- Make sure your
resourcesfolder is copied into thedist/myapp/folder alongside themyapp.exe. - PyInstaller does NOT automatically copy folders like
resources— you have to copy it manually after the build, or add it explicitly with--add-dataoption:
Example to add the resources folder during build:
pyinstaller --onedir --windowed --add-data "resources;resources" main.pyNote: On Windows, use a semicolon
;between source and destination paths in--add-data.This tells PyInstaller to copy your
resourcesfolder next to the executable inside the dist folder.
Summary
- Use
sys.executableto get folder of the exe. - Put
resourcesin that folder. - Use
--add-datato includeresourcesfolder automatically.
If you want, I can provide a sample PyInstaller build command including
--add-datafor your resources folder as well! - User
whole script please
- Assistant
Certainly! Here's the full minimal PySide6 Python script that:
- Places a QPushButton.
- Loads text from
resources/preferences.txtlocated next to the executable (inside aresourcesfolder). - Uses a
resource_pathfunction suitable for PyInstaller--onedirbuilds. - Changes button text to the file contents or shows an error if the file is missing.
import sys import os from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout from PySide6.QtCore import Qt def resource_path(relative_path): """ Get absolute path to resource located NEXT TO the executable (PyInstaller onedir). """ try: base_path = os.path.dirname(sys.executable) except Exception: base_path = os.path.abspath(os.path.dirname(__file__)) return os.path.join(base_path, relative_path) class MainWindow(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Button Text Loader") self.button = QPushButton("Load Text from preferences.txt") self.button.clicked.connect(self.load_text_from_file) layout = QVBoxLayout() layout.addWidget(self.button, alignment=Qt.AlignCenter) self.setLayout(layout) self.resize(300, 100) def load_text_from_file(self): file_path = resource_path(os.path.join("resources", "preferences.txt")) try: with open(file_path, "r", encoding="utf-8") as file: text = file.read().strip() self.button.setText(text) except FileNotFoundError: self.button.setText("preferences.txt not found!") if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
How to build with PyInstaller
Open a terminal inside the folder containing your script and your
resourcesfolder, then run:pyinstaller --onedir --windowed --add-data "resources;resources" main.py--onedir— creates a folder with exe and dependencies.--windowed— prevents console window.--add-data "resources;resources"— copies yourresourcesfolder into the dist directory next to the exe.
Expected folder structure after build
dist/ └── main/ ├── main.exe └── resources/ └── preferences.txtWhen you run
main.exe, it will look inside the same folder (dist/main/) for theresourcesfolder.
If you want me to provide a batch script for building this as well, just ask!