I am working on a script to do some local file management tasks on computer startup. As part of its regular operation, it will occasionally create some temp files in the same folder as it is running from.
In order to keep this as simple as possible, I compiled the script with Pyinstaller with the --onefile and --noconsole arguments, and added the path to the compiled .exe file to the registry, under HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run. The script works properly while in a development environment, or if started up manually. However, if it starts by means of starting up the computer (through the reg key), it fails to create the files it is supposed to in the right place. After some tests, I have concluded that the file path changes depending on how the file is run:
If started up manually (e.g., double clicking the .exe file or running the .py script):
print(os.path.dirname(os.path.realpath(__file__)))
Correctly yields the file folder:
C:\Projects\Test
But if the script starts through run at startup, the same line yields a different location:
C:\Windows\system32
This causes file operations to be conducted in the system32 folder, which is not supposed to happen.
Is there any explanation for this behavior? Batch files executed by the script to perform file operations (for example, restarting the script itself) also fail if they use relative instead of absolute paths, for the same reasons stated above. How to fix this other than hardcoding the absolute file paths everywhere?