You could create a separate uninstallation script that is placed outside the installation directory, and it can call the uninstaller script from within the directory.
1.Create an uninstallation script (uninstall.py) outside the installation directory.
2.Inside uninstall.py, execute the uninstaller script (uninstaller.py) located within the installation directory using os.chdir() to change the working directory.
Example:
import os
def uninstall():
uninstall_script_path = "path/to/installation/directory/uninstaller.py"
try:
os.chdir("path/to/installation/directory")
exec(open(uninstall_script_path).read())
except Exception as e:
print(f"Error during uninstallation: {e}")
if __name__ == "__main__":
uninstall()
With this, users can run uninstall.py from outside the installation directory, and it will execute uninstaller.py located within the installation directory, effectively removing the application without encountering permission issues
———————————————————————————————————
Here’s how you could modify the script to make it delete itself after uninstalling the application:
import os
import sys
import shutil
def uninstall():
install_dir = "path/to/installation/directory"
uninstall_script = os.path.abspath(__file__) # Get absolute path of uninstaller script
try:
# Remove the installation directory
shutil.rmtree(install_dir)
# Remove the uninstaller script itself
os.remove(uninstall_script)
print("Uninstallation complete.")
except Exception as e:
print(f"Error during uninstallation: {e}")
# Delete the script file itself
try:
os.remove(__file__)
print("Uninstaller script deleted.")
except Exception as e:
print(f"Error deleting uninstaller script: {e}")
if __name__ == "__main__":
uninstall()
In this updated version, after uninstalling the application and removing the installation directory, the script attempts to delete itself using os.remove(__file__)
. This line removes the file that is currently being executed (uninstaller.py
).