running the exe agian does not find the file but gives the location as a temp file
Assistant
It sounds like you're running an executable file, but when it tries to access another file, it's failing because it can't find the file—the location given is a temporary file path. This can happen in a few situations. To help you better, I need a bit more information, but here are some general troubleshooting steps:
Clarify the scenario:
What executable are you running?
What file is it trying to find (input file, config file, some resource)?
Are you running it from a command line, script, or double-clicking it?
What exactly does the error message say?
What temporary path is it pointing to?
Common causes and solutions:
File extracted to a temp folder but deleted after the process ends:
Sometimes applications extract files to a temporary folder but clean them after the process finishes. If you re-run the EXE and it refers to the previous temp location which no longer exists, you get this error.
Running from a compressed archive:
If you are running the EXE directly from a ZIP or similar archive without fully extracting it, temporary files may be extracted on-the-fly and then disappear.
Antivirus or cleanup software removing files from temp:
Security software can delete temp files or quarantine files needed.
File path issues:
The program might be using relative paths and looking in the wrong directory.
What you can try:
Fully extract/unpack the application and supporting files to a permanent location and run it from there.
Check if your antivirus quarantined or deleted some files.
Run the program as Administrator if permissions are preventing file access.
Look for any config files or command line options that let you specify input/output file locations.
Check if the application creates logs or debugging info that indicate where it's looking for files.
If this is your own program or script:
Review code that works with temporary files or paths.
Make sure temp files are created and not deleted before they're used.
Use absolute paths or verify current working directory.
If you provide the exact error message, the executable name, and context, I can give you more precise advice.
User
this
import sys
import os
from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QMessageBox
from PySide6.QtCore import Qt
def resource_path(relative_path):
"""
Returns absolute path to resource, works for dev and for bundled exe.
"""
if getattr(sys, 'frozen', False):
# We are running in a bundle (PyInstaller, Nuitka)
base_path = os.path.dirname(sys.executable)
else:
# Running in normal Python environment
base_path = os.path.dirname(os.path.abspath(file))
return os.path.join(base_path, relative_path)
class MainWindow(QWidget):
def init(self):
super().init()
self.setWindowTitle("Button Text Loader")
code
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 load_text_from_file(self):
file_path = resource_path(os.path.join("resources", "preferences.txt"))
# Debug: Show message box with path tried
# QMessageBox.information(self, "Debug", f"Trying to load:\n{file_path}")
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!")
QMessageBox.critical(self, "Error", f"File not found:\n{file_path}")
if name == "main":
app = QApplication(sys.argv)
window = MainWindow()
window.resize(300, 100)
window.show()
sys.exit(app.exec())
using nuitka
@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 ^
--onefile ^
--windows-console-mode=disable ^
--enable-plugin=pyside6 ^
%SCRIPT%
pause
Assistant
Thanks for sharing your code and the Nuitka compile command! Based on your description and your setup, the issue you’re encountering is a file not found error when running the onefile executable, and the failing path refers to a temporary folder (likely where the onefile bundle extracts to at runtime).
What’s Happening?
When you use --onefile mode with Nuitka (or PyInstaller), your executable is bundled into one single file. At runtime, the executable extracts all bundled resources and the Python interpreter into a temporary folder and runs from there. This folder is usually a temporary directory in the system's TEMP folder, and it is removed when the program exits.
Your current resource_path function determines the base path as:
When frozen, you use the directory of sys.executable.
However, in onefile mode, sys.executable points to that temporary folder at runtime, which disappears after the program ends.
This means your program looks for the resources/preferences.txt inside that temporary folder, but it’s not there (or it’s a different temporary folder at each run).
Why is the file missing?
Your preferences.txt is not bundled inside the executable by default, so even in the temporary runtime folder it does not exist.
How to fix: Bundle preferences.txt inside your executable and access it correctly
Option 1: Bundle the file using Nuitka’s data file support
You need to tell Nuitka to include your resource files (preferences.txt) in the executable. In Nuitka, you can do this by:
This tells Nuitka to bundle your local file inside the executable and extract it at runtime into the temporary folder with the same relative path.
User
ok so i understand about the missing or not found folder and file in temp, but how does one make sure that files in folders beside the exe that launches the unpacking can be read and written too
Assistant
Great question! You want your distributed onefile executable to read and write files that live alongside the .exe file itself, not just inside the temporary unpack folder it uses at runtime.
Key points
The unpacked temp folder is temporary and deleted after exit.
Files that ship beside your .exe are not inside the temp folder.
Your program runs from the extracted temp folder, so sys.executable points there, not to the .exe's actual permanent folder.
To **access files next to the actual .exe**, you need to find the directory of the .exe itself before or instead of the temporary folder.
How to get the folder where the .exe (launcher) lives on disk?
You can use one of these approaches in your Python code:
python
import sys
import os
def get_exe_dir():
if getattr(sys, 'frozen', False):
# sys.executable points to the temp extracted exe at runtime
# but the real exe location is in sys._MEIPASS or for Nuitka we can try sys.executable
# Actually, sys.executable is usually the unpacked exe in onefile mode,
# but __file__ does NOT exist when frozen.
# Best way: use sys.argv[0] or os.path.realpath(sys.argv[0])
# Use this to get directory of the actual executable on disk (next to .exe file)
exe_path = os.path.realpath(sys.argv[0])
return os.path.dirname(exe_path)
else:
# Running as script, so __file__ exists
return os.path.dirname(os.path.abspath(__file__))
sys.argv[0] is the path used to launch the program — which, in onefile mode, is the real exe location, not the temp path.
Using os.path.realpath(sys.argv[0]) handles shortcuts and relative paths.
User
apply changes to the main.py
Assistant
Certainly! Here is your updated main.py with the resource_path function modified so it accesses files located next to the executable (outside the temporary unpack folder). This allows you to place your resources/preferences.txt folder beside your .exe, and the program will read from it correctly.
python
import sys
import os
from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QMessageBox
from PySide6.QtCore import Qt
def resource_path(relative_path):
"""
Returns absolute path to resource located relative to the executable.
Works for both dev environment and bundled onefile executable,
accessing files beside the .exe, not inside the unpack temp folder.
"""
if getattr(sys, 'frozen', False):
# We are running in a bundled onefile executable
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
else:
# Running in normal Python environment (script)
base_path = os.path.dirname(os.path.abspath(__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)
def load_text_from_file(self):
file_path = resource_path(os.path.join("resources", "preferences.txt"))
# Optional debug message to check path
# QMessageBox.information(self, "Debug", f"Trying to load:\n{file_path}")
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!")
QMessageBox.critical(self, "Error", f"File not found:\n{file_path}")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.resize(300, 100)
window.show()
sys.exit(app.exec())
User
please amend so that errors can be seen in a consul window
Assistant
Certainly! To see errors and standard outputs in a console window on Windows, you need to:
Compile with the console enabled (not --windows-console-mode=disable).
Or launch the program via a console manually to see print and traceback messages.
And in your Python code, you can add exception traceback printing so errors are output clearly.
Here is your amended main.py that:
Prints exception tracebacks to the console.
Includes an example of catching all exceptions in the main app loop to print errors.
Keeps the Qt error messageboxes for user feedback.
python
import sys
import os
import traceback
from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QMessageBox
from PySide6.QtCore import Qt
def resource_path(relative_path):
"""
Returns absolute path to resource located relative to the executable.
Works for both dev environment and bundled onefile executable,
accessing files beside the .exe, not inside unpack temp folder.
"""
if getattr(sys, 'frozen', False):
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
else:
base_path = os.path.dirname(os.path.abspath(__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)
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 as e:
print("FileNotFoundError:", e)
traceback.print_exc()
self.button.setText("preferences.txt not found!")
QMessageBox.critical(self, "Error", f"File not found:\n{file_path}")
except Exception as e:
print("Unexpected error:", e)
traceback.print_exc()
self.button.setText("Error loading preferences.txt")
QMessageBox.critical(self, "Error", f"Unexpected error:\n{e}")
if __name__ == "__main__":
try:
app = QApplication(sys.argv)
window = MainWindow()
window.resize(300, 100)
window.show()
sys.exit(app.exec())
except Exception:
print("Unhandled exception during application startup:")
traceback.print_exc()
input("Press Enter to exit...") # So the console window stays open on error
User
can you explain how the error printing fuction work
Assistant
Certainly! Let me explain how the error printing in your updated main.py works step-by-step, focusing on the use of try/except blocks and traceback.print_exc():
1. try/except in load_text_from_file()
python
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 as e:
print("FileNotFoundError:", e)
traceback.print_exc()
self.button.setText("preferences.txt not found!")
QMessageBox.critical(self, "Error", f"File not found:\n{file_path}")
except Exception as e:
print("Unexpected error:", e)
traceback.print_exc()
self.button.setText("Error loading preferences.txt")
QMessageBox.critical(self, "Error", f"Unexpected error:\n{e}")
Goal: Handle file I/O errors gracefully and print useful debug info in the console.
How it works:
Python tries to open and read your preferences file.
If the file doesn’t exist, a FileNotFoundError is raised.
The first except FileNotFoundError as e: catches this specific error.
It prints a simple error message (the exception string e) to the console.
It then calls traceback.print_exc().
This prints the full traceback of the last caught exception, showing exactly where the error happened in code.
The button text is updated to reflect the error.
A GUI error message box pops up to inform the user.
The second generic except Exception as e: catches (permission denied, I/O errors, encoding errors etc).
User
no cosule displayed
import sys
import os
import traceback
from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QMessageBox
from PySide6.QtCore import Qt
def resource_path(relative_path):
"""
Returns absolute path to resource located relative to the executable.
Works for both dev environment and bundled onefile executable,
accessing files beside the .exe, not inside unpack temp folder.
"""
if getattr(sys, 'frozen', False):
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
else:
base_path = os.path.dirname(os.path.abspath(file))
return os.path.join(base_path, relative_path)
class MainWindow(QWidget):
def init(self):
super().init()
self.setWindowTitle("Button Text Loader")
code
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 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 as e:
print("FileNotFoundError:", e)
traceback.print_exc()
self.button.setText("preferences.txt not found!")
QMessageBox.critical(self, "Error", f"File not found:\n{file_path}")
except Exception as e:
print("Unexpected error:", e)
traceback.print_exc()
self.button.setText("Error loading preferences.txt")
QMessageBox.critical(self, "Error", f"Unexpected error:\n{e}")
if name == "main":
try:
app = QApplication(sys.argv)
window = MainWindow()
window.resize(300, 100)
window.show()
sys.exit(app.exec())
except Exception:
print("Unhandled exception during application startup:")
traceback.print_exc()
input("Press Enter to exit...") # So the console window stays open on error
Assistant
The issue you're facing ("no console displayed") is because your executable was compiled in windowed mode, so Windows does not show a console window (the terminal) where print() and traceback.print_exc() outputs go.
Why no console?
When building a GUI application on Windows, you can choose to build a console executable or a windowed (GUI) executable.
If built as a windowed exe (which is default when using --windows-console-mode=disable or similar flags), Windows suppresses the console window entirely.
print() and traceback.print_exc() still go to standard output/error, but since no console is shown, you don't see them.
How to see the console output?
Build/run with Console enabled
If using Nuitka, do NOT pass--windows-console-mode=disable.
This builds a onefile exe that opens a console window alongside your GUI on launch, so you will see print output.
Run the app from an existing console
Open cmd.exe or PowerShell.
Run your .exe by typing its path.
The console stays open, and your output/errors will be printed.
Manually allocate a console from your app (less common)
If you want a console sometimes even in windowed mode, you can call AllocConsole via ctypes, but this is more complex.
If you want the console and GUI both visible by default…
Just do not disable console mode in your build.
Your program will have both windows (console + GUI).
If you want the program to be GUI only but still capture errors somewhere:
You need to redirect standard output and error to a log file.
User
C:\DEV\Nuitka Tests>main.exe
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\smudg\AppData\Local\Temp\onefile_17600_133915281688401782\resources\preferences.txt'
Traceback (most recent call last):
File "C:\Users\smudg\AppData\Local\Temp\onefile_17600_133915281688401782\main.py", line 34, in load_text_from_file
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\smudg\AppData\Local\Temp\onefile_17600_133915281688401782\resources\preferences.txt'
which is the temporary extraction folder where Nuitka unpacks the onefile executable at runtime.
Why? Even though you updated resource_path?
Because the error shows you are still using a resource_path function that returns the path relative to sys.executable, which in onefile mode points to the temp folder.
If you want the program to read preferences.txt from beside the .exe (the folder where your executable lives, not the temp), your resource_path function must use:
python
os.path.realpath(sys.argv[0])
to get the directory of the original .exe file, not sys.executable.
Action steps
Double-check your resource_path function — it must be exactly like this:
python
def resource_path(relative_path):
if getattr(sys, 'frozen', False):
# sys.argv[0] points to the original .exe path (not the extracted temp file)
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
else:
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, relative_path)
Make sure you rebuild your executable after making this change.
Place your resources/preferences.txt folder next to the .exe.
For example, your folder structure should look like:
Thanks for confirming the code is correct but you’re still seeing the file-not-found error with the temp path.
This means that although your resource_path is correctly written to point next to your .exe using sys.argv[0], your running app is somehow still trying to access the temp extraction folder.
This typically happens in two scenarios:
1) The executable you are launching is not the real .exe file, but the extracted temporary copy:
When you run a bundled onefile executable, it unpacks itself to a temp folder, then launches from there internally.
sys.argv[0] should still point to the original .exe location, but sometimes other code or PySide internals may reference sys.executable or use relative paths inside the temp folder.
Check exactly how you run the executable:
Are you running it from Windows Explorer by double-clicking? This should be fine.
Are you running the temporary exe inside the temp folder? (Maybe copying it elsewhere?)
Are you launching the exe via a shortcut or script that changes current directory?
2) The resources/preferences.txt does not exist in the expected location:
The executable’s directory as per sys.argv[0] is presumably C:\DEV\Nuitka Tests.
Does C:\DEV\Nuitka Tests\resources\preferences.txtreally exist?
If the file is missing or the path differs by capitalization/path separator (very rare on Windows), you will get a FileNotFoundError.
How to diagnose the actual problem:
Add diagnostic prints / message boxes to confirm:
This snippet explicitly prints multiple paths:
python
User
add to the main.py
Assistant
Certainly! I've added the diagnostic prints and a message box to your existing main.py so that when you click the button, you see the key paths your app is using. This will help us understand whether the file path points to the temp folder or next to your .exe.
Here's the updated full main.py with diagnostics added inside load_text_from_file:
python
User
output
C:\DEV\Nuitka Tests>main.exe
sys.executable: C:\DEV\Nuitka Tests\main.exe
sys.argv[0]: C:\DEV\Nuitka Tests\main.exe
Resolved resource path: C:\Users\smudg\AppData\Local\Temp\onefile_5212_133915291596106672\resources\preferences.txt
Current working directory: C:\DEV\Nuitka Tests
File exists? False
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\smudg\AppData\Local\Temp\onefile_5212_133915291596106672\resources\preferences.txt'
Traceback (most recent call last):
File "C:\Users\smudg\AppData\Local\Temp\onefile_5212_133915291596106672\main.py", line 50, in load_text_from_file
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\smudg\AppData\Local\Temp\onefile_5212_133915291596106672\resources\preferences.txt'
also from the nuitka manual
There is a difference between sys.argv[0] and file of the main module for onefile more, that is caused by using a bootstrap to a temporary location. The first one will be the original executable path, where as the second one will be the temporary or permanent path the bootstrap executable unpacks to. Data files will be in the later location, your original environment files will be in the former location.
means the relative_path you pass contains this temp folder inside it.
That strongly suggests something else is constructing the path differently — perhaps your call to resource_path is nested inside a call that uses __file__ or some other variable pointing to the temp directory?
If "resources/preferences.txt" is passed as relative path, resource_path should prepend the base path.
User
please add all suggestions to main.py
Assistant
Certainly! Below is your full updated main.py incorporating:
The dual-path resource_path() that first tries the bundled (temp) location, then the external exe folder.
Diagnostic prints showing the locations checked and whether files exist.
Message boxes for diagnostics.
Proper error handling with tracebacks printed.
Comments explaining what is happening at each step.
python
User
here are the outputs
===== Debug Info =====
sys.executable: C:\DEV\Nuitka Tests\main.exe
sys.argv[0]: C:\DEV\Nuitka Tests\main.exe
file: C:\Users\smudg\AppData\Local\Temp\onefile_21192_133915297727491229\main.py
Current working directory: C:\DEV\Nuitka Tests
File at temp unpacked folder: C:\Users\smudg\AppData\Local\Temp\onefile_21192_133915297727491229\resources\preferences.txt exists? False
File next to exe: C:\DEV\Nuitka Tests\resources\preferences.txt exists? True
Using resource_path():
C:\Users\smudg\AppData\Local\Temp\onefile_21192_133915297727491229\resources\preferences.txt
File exists? False
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\smudg\AppData\Local\Temp\onefile_21192_133915297727491229\resources\preferences.txt'
Traceback (most recent call last):
File "C:\Users\smudg\AppData\Local\Temp\onefile_21192_133915297727491229\main.py", line 67, in load_text_from_file
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\smudg\AppData\Local\Temp\onefile_21192_133915297727491229\resources\preferences.txt'
Assistant
Thanks for posting the output — it nails down the issue precisely.
What your output confirms:
__file__ points to the temp unpack folder: C:\Users\smudg\AppData\Local\Temp\onefile_21192_133915297727491229\main.py
sys.argv[0] is the real exe path: C:\DEV\Nuitka Tests\main.exe
The file exists next to the exe: C:\DEV\Nuitka Tests\resources\preferences.txt = True
The path your code actually tries to open is inside the temp folder: C:\Users\smudg\AppData\Local\Temp\onefile_21192_133915297727491229\resources\preferences.txt
That file does not exist, so you get FileNotFoundError.
Why does resource_path return the temp folder path when the file exists next to the exe?
If temp_path exists, returns it; else returns exe_path.
But your diagnostic shows:
temp_pathdoes NOT exist (False)
so it should return exe_path
But your print states clearly:
code
Using resource_path():
C:\Users\smudg\AppData\Local\Temp\onefile_21192_133915297727491229\resources\preferences.txt
File exists? False
User
apply the forced exe folder approach to main.py
Assistant
Certainly! Here is your updated main.py with the forced exe folder approach applied to resource_path().
This version will always look for resource files relative to the folder where your executable (main.exe) lives, ignoring the temporary unpack folder.
python
import sys
import os
import traceback
from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QMessageBox
from PySide6.QtCore import Qt
def resource_path(relative_path):
"""
Returns absolute path to resource file located next to the executable (for frozen apps),
or next to the script file (when running normally).
"""
if getattr(sys, 'frozen', False):
# Always use folder next to the executable for resources
base_path = os.path.dirname(sys.argv[0])
else:
# Running normally (not frozen)
base_path = os.path.dirname(os.path.abspath(__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)
def load_text_from_file(self):
file_path = resource_path(os.path.join("resources", "preferences.txt"))
print(f"Trying to open resource file: {file_path}")
print(f"Exists? {os.path.exists(file_path)}")
try:
with open(file_path, "r", encoding="utf-8") as file:
text = file.read().strip()
self.button.setText(text)
except FileNotFoundError as e:
print("FileNotFoundError:", e)
traceback.print_exc()
self.button.setText("preferences.txt not found!")
QMessageBox.critical(self, "Error", f"File not found:\n{file_path}")
except Exception as e:
print("Unexpected error:", e)
traceback.print_exc()
self.button.setText("Error loading preferences.txt")
QMessageBox.critical(self, "Error", f"Unexpected error:\n{e}")
if __name__ == "__main__":
try:
app = QApplication(sys.argv)
window = MainWindow()
window.resize(300, 100)
window.show()
sys.exit(app.exec())
except Exception:
print("Unhandled exception during application startup:")
traceback.print_exc()
input("Press Enter to exit...") # Keep console open on crash
User
still not found
C:\DEV\Nuitka Tests>main
Trying to open resource file: C:\Users\smudg\AppData\Local\Temp\onefile_6024_133915308428172445\resources\preferences.txt
Exists? False
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\smudg\AppData\Local\Temp\onefile_6024_133915308428172445\resources\preferences.txt'
Traceback (most recent call last):
File "C:\Users\smudg\AppData\Local\Temp\onefile_6024_133915308428172445\main.py", line 39, in load_text_from_file
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\smudg\AppData\Local\Temp\onefile_6024_133915308428172445\resources\preferences.txt'
Assistant
The issue you’re seeing — that even with the forced exe folder approach, your app tries to load the resource from the temp folder — means the code isn't (sys.argv[0]) giving the path you think.
In your print output, you show:
code
Trying to open resource file: C:\Users\smudg\AppData\Local\Temp\onefile_6024_133915308428172445\resources\preferences.txt
meaning that resource_path() is returning a path inside the temp folder — which contradicts the forced exe folder approach.
Why is this happening, and the key understanding:
When running a onefile bundled exe from Nuitka, sys.argv[0] is NOT reliable on Windows for the exe path; it often returns the temporary path to the extracted executable in the temp directory where Nuitka unpacks its onefile bundle.
This is somewhat like PyInstaller’s sys._MEIPASS when running onefile, where the actual executable is extracted to a temporary folder and run from there.
So, for onefile executables, sys.argv[0] on Windows points to the temp extracted exe, NOT the original exe path.
This is why your code:
python
base_path = os.path.dirname(sys.argv[0])
returns a path inside the temp folder!
Solution: Get the path to the actual executable (sys.executable)
On Windows onefile apps, the better way to find the actual executable’s folder on disk is:
python
base_path = os.path.dirname(sys.executable)
According to Python docs, sys.executable in a frozen onefile app points to the original executable on disk, not the extracted temp copy.
ok still the same. could we maybe use bat file to get its path and read that in
Assistant
Yes, using a batch file to provide the actual executable folder path to the program is a practical and straightforward workaround, especially if sys.executable and sys.argv[0] do not give the expected path due to how Nuitka unpacks the executable in onefile mode.
Idea: Pass the folder path via environment variable or command line argument from a .bat
Create a batch file that launches your EXE and provides the path
Example: run_main.bat
batch
@echo off
REM Get the directory of this batch file (which is assumed to be where exe lives)
set EXE_DIR=%~dp0
REM Remove trailing backslash if any (optional)
set EXE_DIR=%EXE_DIR:~0,-1%
REM Launch your exe passing EXE_DIR as argument or env var
REM Option 1: Pass as argument
main.exe "%EXE_DIR%"
REM Option 2: Pass as environment variable then launch
REM set MYAPP_EXEDIR=%EXE_DIR%
REM main.exe
2. Modify your Python code to read this info
Option A: Read from command line argument
python
import sys
import os
def get_resource_path(relative_path):
"""
Determine resource path by reading first CLI argument as base path if frozen.
Otherwise use script directory.
"""
if getattr(sys, 'frozen', False):
# Expect first argument to be the exe directory passed from .bat
if len(sys.argv) > 1:
base_path = sys.argv[1]
else:
# fallback (optional): try sys.executable folder
base_path = os.path.dirname(sys.executable)
else:
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, relative_path)
3. Adjust load_text_from_file and usage example:
User
or could the exe run a bat to get the path
Assistant
Yes, your executable can invoke a batch file to retrieve the folder path and then read that path in Python. This is a slightly more complex approach but also feasible.
How this would work in broad strokes:
The executable runs a batch script (e.g., using subprocess) which outputs the directory path (usually the folder where the .bat file resides).
The Python code captures the output of this batch script (the folder path), then uses it as the base path when loading resources.
Step-by-step example:
1. Create a simple batch file getpath.bat (placed next to your exe and resources):
batch
@echo off
REM Output this batch file folder path without trailing backslash
set BINPATH=%~dp0
REM Remove trailing backslash (optional)
set BINPATH=%BINPATH:~0,-1%
echo %BINPATH%
2. Modify your Python code to run this bat and read the path:
python
import subprocess
import sys
import os
def get_executable_folder_via_bat():
"""
Runs getpath.bat and returns the output folder path.
Assumes getpath.bat is located next to the exe.
"""
# Get folder of this exe or script
if getattr(sys, 'frozen', False):
exe_folder = os.path.dirname(sys.executable)
else:
exe_folder = os.path.dirname(os.path.abspath(__file__))
bat_path = os.path.join(exe_folder, "getpath.bat")
try:
result = subprocess.run([bat_path], capture_output=True, text=True, check=True)
folder_path = result.stdout.strip()
return folder_path
except Exception as e:
print(f"Failed to run {bat_path}: {e}")
return exe_folder # fallback
def resource_path_bat(relative_path):
base_path = get_executable_folder_via_bat()
return os.path.join(base_path, relative_path)
User
please apply to main.py
Assistant
Certainly! Below is your full updated main.py that runs a batch file (getpath.bat) placed alongside the executable to determine the folder containing your .exe, then loads resources/preferences.txt relative to that folder.
Please also create a file named getpath.bat alongside your executable with this content:
batch
@echo off
REM Output the folder where this batch file lives (without trailing backslash)
set BINPATH=%~dp0
set BINPATH=%BINPATH:~0,-1%
echo %BINPATH%
With data files included as above, your resource_path function will point to the right temporary extraction folder.
To be explicit, Nuitka provides a variable called sys._MEIPASS (like PyInstaller), but Nuitka does not necessarily define this. Instead, your code approach of using os.path.dirname(sys.executable) is valid, but just make sure the data files are included.
Option 3: Use embedded resource approach (for PySide6 resources)
If your preferences.txt can be converted into a Qt resource .qrc file and compiled into Python with pyside6-rcc, the resource will be embedded in your application and available at runtime without external files. That is more complex but sometimes preferred.
Keep your resource_path function as is, it should work because the extracted file will appear inside the temp folder with the same relative path.
Make sure your app requests the file as resources/preferences.txt (as you do)
Test by keeping the debug message to confirm the runtime path being accessed:
python
QMessageBox.information(self, "Debug", f"Trying to load:\n{file_path}")
Optional: Confirm file presence without bundling
If you want to debug outside the onefile bundle, run your Python script normally and make sure resources/preferences.txt exists at:
code
<your-script-folder>/resources/preferences.txt
Additional note on temp file warnings
Because onefile bundles extract to temp folders which are deleted after the program ends, beware that:
Running the executable twice in quick succession might point to a new temp folder each time.
You cannot rely on relative paths outside the bundle unless you use absolute system paths or paths relative to a fixed location.
If you want, I can help you generate the exact command or further adapt your code to find the file outside the bundle (e.g., next to the EXE or in user folders)! Let me know!
Putting it all together
Modify your resource_path like this if you want to access sibling files beside your exe:
python
def resource_path(relative_path):
"""
Return absolute path for files located relative to the .exe file (not unpack temp).
"""
if getattr(sys, 'frozen', False):
# Get directory of the actual exe on disk
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
else:
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, relative_path)
Now:
Your preferences.txt file can be placed in a resources folder right next to your myprogram.exe.
Your program will look for resources/preferences.txtnext to the exe, not inside the temp folder.
This also means you can write back to this directory or update files here.
Notes on write permissions
When running the exe from Program Files, Windows permissions might prevent writing files beside your exe.
For writing data, a better approach is to store user-writable config or data in standard locations like %APPDATA% or user documents.
Reading files next to exe is fine for static data or defaults.
Optional: Example usage in your button click
python
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!")
QMessageBox.critical(self, "Error", f"File not found:\n{file_path}")
This will reliably find your resources/preferences.txtnext to the exe, regardless of temporary extraction folders.
Now, when you run your exe by double-click or from a terminal, the console window will show print output and error tracebacks.
If an unexpected exception happens, it will be printed in the console and the program will wait for Enter key to keep the window open.
If you prefer no console window on launch but want to capture errors in a log file instead, I can help you set that up too.
Let me know if you want that!
any other unexpected errors
Similar to above, it prints the error and full traceback.
Updates the UI and shows user an error message.
2. What does traceback.print_exc() do?
When an exception occurs inside a try block, Python stores traceback information internally.
Calling traceback.print_exc()prints that traceback to the current standard error stream (sys.stderr), which shows up directly in the console window.
The traceback includes:
File name and line number where the exception occurred.
The call stack at the time.
The exception type and message.
This detailed info helps you debug where and why the program failed.
3. Unhandled exceptions in the main application
python
if __name__ == "__main__":
try:
app = QApplication(sys.argv)
window = MainWindow()
window.resize(300, 100)
window.show()
sys.exit(app.exec())
except Exception:
print("Unhandled exception during application startup:")
traceback.print_exc()
input("Press Enter to exit...") # Keeps console open on error
This wraps the whole app start-up in a try/except block.
If any exception escapes from anywhere during initialization or the main Qt event loop, it is caught here.
It prints a message and then prints the full traceback.
input("Press Enter to exit...") is used to pause the console, so you can see the error message before the console window closes.
This is useful especially when launching by double-click from Explorer, where the console closes immediately after crash if not paused.
4. Why print to console and show message boxes both?
Console output is mostly for developers and debugging when you run your app from command line or want detailed error logs.
Message boxes give user-friendly info for end users, who might not see or understand console output.
Summary:
try/except blocks catch errors so your app doesn't crash abruptly.
print(e) shows a brief error description in the console.
traceback.print_exc() prints detailed error stack trace helping you find exactly where it failed.
The global try/except around your app startup catches and reports unhandled exceptions so you can still see/debug them.
Pausing on error (input()) keeps the console open for inspection.
If you want, I can also help you log errors to a file instead of console, or integrate advanced error tracking! Just ask!
Or use a logging framework that writes errors to logs, because console won't be visible.
In summary:
Your current code does print the errors, but since there is no console, you can't see it.
To fix this:
Rebuild without --windows-console-mode=disable so console window opens.
Or run your exe from an existing command prompt.
Or implement logging to a file to capture errors/prints if you want GUI-only mode.
Quick test: run exe from command prompt
Open Command Prompt (cmd.exe).
Navigate to folder with exe.
Run: yourprogram.exe
Errors and prints will appear there.
If you want, I can help you:
Show how to redirect errors to a log file in your PySide6 app.
Or show how to enable a console window programmatically on Windows.
Let me know!
If you run main.exe, it will look for "resources/preferences.txt" relative to C:\DEV\Nuitka Tests\.
Why does the error still show the temp path?
Because Nuitka's default sys.executable points to the temp extraction folder at runtime.
If your code uses os.path.dirname(sys.executable), it will resolve to that temp folder (which is deleted after the program exits and will not have your external resources).
Using os.path.dirname(os.path.realpath(sys.argv[0])) gives you the real path to the original .exe file on disk.
How to check at runtime?
Add this debug in your application to verify paths:
and run from the build folder, your code may behave differently.
Last considerations:
If you want to read files from disk next to your executable at runtime, do NOT bundle them into the executable; just distribute them alongside the exe.
If you want to bundle your resource files inside the onefile executable, include them using --include-data-file=...and keep your resource_path based on sys.executable to access them inside the extracted temp folder.
Summary:
You have a mismatch between:
Where your executable thinks the resource is (temp folder).
Where you want to load it from (next to exe).
You must either:
Make sure your code tries to load resources based on sys.argv[0]and run the executable normally (not the extracted temp exe), with the resources folder next to the exe.
OR
Bundle the resources inside the executable and load them relative to sys.executable.
If you want, I can help you write two resource loaders:
One tries to read from external folder next to exe (for user-editable files).
If not found, fallback to bundled one inside extracted temp folder.
Please run the diagnostics above to show the information from the message box, paste the output, and we will continue from there!
import sys
import os
import traceback
from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QMessageBox
from PySide6.QtCore import Qt
def resource_path(relative_path):
"""
Returns absolute path to resource located relative to the executable.
Works for both dev environment and bundled onefile executable,
accessing files beside the .exe, not inside unpack temp folder.
"""
if getattr(sys, 'frozen', False):
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
else:
base_path = os.path.dirname(os.path.abspath(__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)
def load_text_from_file(self):
file_path = resource_path(os.path.join("resources", "preferences.txt"))
# Diagnostic prints:
print("sys.executable:", sys.executable)
print("sys.argv[0]:", sys.argv[0])
print("Resolved resource path:", file_path)
print("Current working directory:", os.getcwd())
print("File exists?", os.path.isfile(file_path))
# Diagnostic message box:
QMessageBox.information(self, "Paths Info",
f"sys.executable:\n{sys.executable}\n\n"
f"sys.argv[0]:\n{sys.argv[0]}\n\n"
f"Resource path:\n{file_path}\n\n"
f"Current working directory:\n{os.getcwd()}\n\n"
f"File exists: {os.path.isfile(file_path)}")
try:
with open(file_path, "r", encoding="utf-8") as file:
text = file.read().strip()
self.button.setText(text)
except FileNotFoundError as e:
print("FileNotFoundError:", e)
traceback.print_exc()
self.button.setText("preferences.txt not found!")
QMessageBox.critical(self, "Error", f"File not found:\n{file_path}")
except Exception as e:
print("Unexpected error:", e)
traceback.print_exc()
self.button.setText("Error loading preferences.txt")
QMessageBox.critical(self, "Error", f"Unexpected error:\n{e}")
if __name__ == "__main__":
try:
app = QApplication(sys.argv)
window = MainWindow()
window.resize(300, 100)
window.show()
sys.exit(app.exec())
except Exception:
print("Unhandled exception during application startup:")
traceback.print_exc()
input("Press Enter to exit...") # Keep console open on crash
How to use:
Rebuild your executable.
Ensure resources/preferences.txt exists in the folder next to your .exe.
Run your exe from a console or just double-click.
Click the "Load Text from preferences.txt" button.
A message box will pop up showing the relevant paths and file existence.
Check the console output for the printed debug info (if console available).
Report back what paths are shown in the message box, especially:
Does file_path point to your temp folder or your exe folder?
Does File exists: say True or False?
What are sys.executable and sys.argv[0]?
This info will clarify whether the app is looking in the right folder or not so we can help fix it properly.
Why might os.path.realpath(sys.argv[0]) point to the temp directory?
Ideally, sys.argv[0] should be "C:\DEV\Nuitka Tests\main.exe", but the fact that os.path.realpath() leads to the temp folder means:
Either you are running the temp-extracted executable directly (instead of the original exe).
Or your app is restarted internally from the temp folder and sys.argv[0] points there.
Your options:
You need to differentiate clearly:
For files next to the original .exe, use:
python
exe_dir = os.path.dirname(sys.argv[0])
For files inside the extracted onefile temp folder, use:
python
temp_dir = os.path.dirname(__file__)
So, update resource_path as follows:
python
def resource_path(relative_path):
"""
Returns path to resource file.
- If running frozen, first try inside temp extraction folder (__file__)
- if not found there, fallback to folder beside the original exe (sys.argv[0])
"""
if getattr(sys, 'frozen', False):
# Try temp dir first
temp_path = os.path.join(os.path.dirname(__file__), relative_path)
if os.path.exists(temp_path):
return temp_path
# fallback, folder where the exe is located
exe_path = os.path.join(os.path.dirname(sys.argv[0]), relative_path)
return exe_path
else:
# running from script
return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path)
Explanation:
In onefile mode, Python runs the unpacked script from the temp folder (__file__ points inside it).
Data files bundled inside the onefile will be inside that temp folder — check there first.
But your external resources/preferences.txt, which you want next to the exe, is next to the original .exe — check that second.
When you run unpacked exe from temp manually, sys.argv[0] can also contain the temp path if launched that way.
Immediate workaround: Force resource_path to always pick the external exe folder
Since your external preferences file actually exists there, and temp location does not have it, you can force:
python
def resource_path(relative_path):
if getattr(sys, 'frozen', False):
# Ignore temp_path, always use exe path to find resource outside the exe
return os.path.join(os.path.dirname(sys.argv[0]), relative_path)
else:
return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path)
This guarantees your exe will look for resources/preferences.txtnext to the main.exe, not inside temp unpack folder.
Important note:
If you plan to bundle that file inside the onefile archive (with --include-data-file), then you do want to use the temp folder path in resource_path to read the extracted file.
If you want to keep an external editable file beside your exe, point resource_path only to the exe folder.
Trying to do both (first temp, then exe folder) can confuse if the temp folder does not contain the file (common case).
Recommendation for your case:
Since you said C:\DEV\Nuitka Tests\resources\preferences.txt exists and you want to edit it externally, use the forced exe folder approach — simplest and surest.
Final suggested resource_path for your current setup:
python
def resource_path(relative_path):
if getattr(sys, 'frozen', False):
# Always load resource from folder next to the exe (external file)
return os.path.join(os.path.dirname(sys.argv[0]), relative_path)
else:
return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path)
Summary:
Change your resource_path as above.
Put your resources/preferences.txt folder alongside your exe.
Run the exe and it will successfully find and open the file.
Prints/debug message box will show the correct paths.
If you want me, I can prepare the full updated main.py with this change and diagnostics removed or simplified for you. Would you like that?
Important:
Make sure the folder resources with preferences.txt is placed next to your compiled main.exe file.
When you run main.exe, it will look for resources/preferences.txt in that same directory.
Prints will tell you exactly what file path it’s trying and whether it exists.
Errors will be printed with traceback and also shown in message boxes.
Let me know if you need further help!
Why use sys.executable instead of sys.argv[0]?
In onefile mode on Windows, sys.argv[0] points to the temporary unpacked executable (inside temp folder).
sys.executable points to the real user-launched executable on disk.
We want the location where your .exe actually resides (so your external files beside the exe are found).
Please apply this minimal resource_path change in main.py:
def load_text_from_file(self):
file_path = resource_path_bat(os.path.join("resources", "preferences.txt"))
print("Using resource file:", file_path)
print("Exists?", os.path.exists(file_path))
try:
with open(file_path, "r", encoding="utf-8") as file:
text = file.read().strip()
self.button.setText(text)
except Exception as e:
print(e)
self.button.setText("Failed to load preferences.txt")
Notes:
Running the batch file adds an external dependency, so remember to ship getpath.bat alongside your executable.
This method "outsources" folder detection to the batch file, totally avoiding quirks with sys.executable or sys.argv[0].
The batch echo output is read by Python.
This approach works cross-version of Python and regardless of Nuitka internal extraction details.
If you'd like, I can help you by preparing a full main.py and getpath.bat example ready to test!
import sys
import os
import traceback
import subprocess
from PySide6.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QMessageBox
from PySide6.QtCore import Qt
def get_executable_folder_via_bat():
"""
Runs getpath.bat located next to the executable or script,
reads the folder path from its output.
"""
if getattr(sys, 'frozen', False):
exe_folder = os.path.dirname(sys.executable)
else:
exe_folder = os.path.dirname(os.path.abspath(__file__))
bat_path = os.path.join(exe_folder, "getpath.bat")
try:
result = subprocess.run([bat_path], capture_output=True, text=True, check=True)
folder_path = result.stdout.strip()
return folder_path
except Exception as e:
print(f"Failed to run {bat_path}: {e}")
return exe_folder # fallback
def resource_path(relative_path):
base_path = get_executable_folder_via_bat()
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)
def load_text_from_file(self):
file_path = resource_path(os.path.join("resources", "preferences.txt"))
print("Using resource file:", file_path)
print("Exists?", os.path.exists(file_path))
try:
with open(file_path, "r", encoding="utf-8") as file:
text = file.read().strip()
self.button.setText(text)
except FileNotFoundError as e:
print("FileNotFoundError:", e)
traceback.print_exc()
self.button.setText("preferences.txt not found!")
QMessageBox.critical(self, "Error", f"File not found:\n{file_path}")
except Exception as e:
print("Unexpected error:", e)
traceback.print_exc()
self.button.setText("Error loading preferences.txt")
QMessageBox.critical(self, "Error", f"Unexpected error:\n{e}")
if __name__ == "__main__":
try:
app = QApplication(sys.argv)
window = MainWindow()
window.resize(300, 100)
window.show()
sys.exit(app.exec())
except Exception:
print("Unhandled exception during application startup:")
traceback.print_exc()
input("Press Enter to exit...") # Keep console open on crash
How to deploy and test:
Put your main.exe (compiled with Nuitka) in a folder.
In the same folder, create a folder named resources and place your preferences.txt inside it.
Also in the same folder, place getpath.bat file with the content shown above.
Run main.exe.
Click the "Load Text from preferences.txt" button.
It should properly load the preferences.txt file from the resources folder next to your exe.
This approach completely avoids relying on Python's sys.executable or argv quirks and uses the batch script to tell the app exactly where it is on disk.
Let me know if you want me to help with packaging or further improvements!