Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

using nuitka standalone can the exe be outside ie one lavel up from the dist folder

  1. User

    using nuitka standalone can the exe be outside ie one lavel up from the dist folder

  2. Assistant

    When you use Nuitka with the --standalone option, by default it creates a dist folder inside your current directory, and places the executable and all required files inside that dist folder.

    Your question is whether the final .exe file can be placed outside the dist folder, for example one level up.

    Short answer:

    No, not directly. Because --standalone mode 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 .exe file one level up (outside the dist folder) and leave the supporting files in the dist folder, the executable will not work as expected, since it cannot find its dependency files (DLLs, extension modules, Python runtime, etc.).


    Explanation:

    • The dist folder 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 dist folder.

    • The executable is not self-contained in a single file; it needs those files to work.


    Workarounds or Suggestions

    1. Custom Output Folder

      Nuitka allows you to specify the output folder name with --output-dir option:

      nuitka --standalone --output-dir=../my_folder your_script.py
      

      This will put the entire dist folder contents into ../my_folder.

      However, the structure still keeps everything together.

    2. Move the entire dist folder

      You can rename/move the entire dist folder or its contents to some other place.

    3. 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.py
      

      Result: a single .exe that can be placed anywhere, no additional files needed.

    4. Manual attempt

      You could try moving just the .exe one 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 --onefile for a single executable that you can place anywhere.
    • Use --output-dir to 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.py
    

    If 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!

  3. 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())

  4. Assistant

    Certainly! Here's the equivalent Java code using Swing for the GUI, which replicates your PySide6 example, including reading preferences.txt from a resources folder relative to the running .class or .jar executable, 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 JButton whose text updates after loading from the file.
    • Layout: Center using a FlowLayout inside a JPanel.
    • Reading the file:
      • Base directory determined by where the .class or .jar is located.
      • Looks for resources/preferences.txt relative to that.
      • Reads text and updates button text.
    • 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.java
    

    Compile:

    javac MainWindow.java
    

    Run:

    java MainWindow
    

    The program will look for the file at ./resources/preferences.txt relative 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 resources folder 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!

  5. 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

  6. 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 .bat script 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=disable in 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-import option, but usually it's not necessary.
    • Output executable will be placed in the dist folder.
    • 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%
    
    pause
    

    Run this batch file in the command prompt inside your project folder where main.py is 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!

  7. 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

  8. Assistant

    Certainly! Your current script uses --onedir, which generates the executable inside a dist\ folder along with dependencies. You want to:

    • Compile the script with PyInstaller using --onedir.
    • Create a shortcut to the generated .exe placed one level up from the dist folder (i.e., next to your project folder or wherever your batch runs).

    Amended .bat script 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 --onedir and --windowed on your script.

    • The .exe will 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 .exe inside dist\.

    • PowerShell is used via -Command to create the Windows shortcut using the COM object WScript.Shell.


    Notes:

    • If your batch script runs from another folder, adjust %PROJECT_DIR% accordingly (e.g., %~dp0 for the batch file folder).
    • The shortcut name is set to <scriptname>.exe - Shortcut.lnk.
    • The WorkingDirectory is set to the folder containing the .exe to ensure relative file access works.

    Example assumptions:

    • You run the batch inside your project folder containing main.py.
    • dist\main\main.exe is 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!

  9. User

    The following usage of the path operator in batch-parameter substitution is invalid: %~nSCRIPT%.exe

  10. Assistant

    The error message

    The following usage of the path operator in batch-parameter substitution is invalid: %~nSCRIPT%.exe
    

    is because %~n syntax 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_NAME to the filename part of main.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=%%~nf
      

      to 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!

  11. 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,

  12. 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 -Command from 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 .ps1 file 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!

  13. User

    amend so that the resources folder is found one level up from the exe

  14. Assistant

    Certainly! To amend your PyInstaller-compiled executable so that at runtime it looks for the resources folder 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.exe
    

    Your resources folder is one level above dist:

    my_project/resources/preferences.txt
    

    You 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_file method

    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!")
    

    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 resources folder inside the exe/dist.

    Just keep resources folder 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 resources folder next to the parent folder of the .exe.
    • Ensure your PyInstaller or Nuitka command does not bundle resources if you want it external.
    • Always test your exe with resources placed 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!

  15. User

    this will now be built as onedir not onefile

  16. Assistant

    Got it! When building with --onedir mode (not --onefile), your executable lives inside a folder (dist/<appname>/), along with all the dependencies. So:

    • The .exe is at: dist/<appname>/<appname>.exe
    • You want your app at runtime to find the resources folder one level up from the .exe folder—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 resources folder one level above exe folder

    import 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 --onedir mode

    • In onedir mode, your executable is in dist/<appname>/.
    • sys.executable points to the full path of that executable.
    • Going one directory up from sys.executable puts you in dist/, so "resources/preferences.txt" resolves to dist/resources/preferences.txt if 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 above dist, adjust the code accordingly:

    • If resources is in the project root (your_project/resources), and your exe is in your_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.executable to 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!

  17. User

    amend so that the resources folder can be found next to the exe, onedir pyinstaller build

  18. Assistant

    Certainly! If you want your resources folder to be next to the executable in a PyInstaller --onedir build (i.e., resources is a sibling folder of your .exe inside the same directory), the Python code should look for resources inside the same directory as the .exe.


    Folder layout for this scenario

    dist/
    └── myapp/
        ├── myapp.exe
        └── resources/
            └── preferences.txt
    

    Updated Python resource_path function

    import 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.executable contains the full path to the running .exe.
    • os.path.dirname(sys.executable) is the folder where your .exe lives.
    • So resources/preferences.txt is looked for inside the same folder as the .exe.
    • This works perfectly in --onedir mode when resources is included alongside the executable folder.

    Important

    • Make sure your resources folder is copied into the dist/myapp/ folder alongside the myapp.exe.
    • PyInstaller does NOT automatically copy folders like resources — you have to copy it manually after the build, or add it explicitly with --add-data option:

    Example to add the resources folder during build:

    pyinstaller --onedir --windowed --add-data "resources;resources" main.py
    

    Note: On Windows, use a semicolon ; between source and destination paths in --add-data.

    This tells PyInstaller to copy your resources folder next to the executable inside the dist folder.


    Summary

    • Use sys.executable to get folder of the exe.
    • Put resources in that folder.
    • Use --add-data to include resources folder automatically.

    If you want, I can provide a sample PyInstaller build command including --add-data for your resources folder as well!

  19. User

    whole script please

  20. Assistant

    Certainly! Here's the full minimal PySide6 Python script that:

    • Places a QPushButton.
    • Loads text from resources/preferences.txt located next to the executable (inside a resources folder).
    • Uses a resource_path function suitable for PyInstaller --onedir builds.
    • 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 resources folder, 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 your resources folder into the dist directory next to the exe.

    Expected folder structure after build

    dist/
    └── main/
        ├── main.exe
        └── resources/
            └── preferences.txt
    

    When you run main.exe, it will look inside the same folder (dist/main/) for the resources folder.


    If you want me to provide a batch script for building this as well, just ask!