Skip to content

Instantly share code, notes, and snippets.

@0xdade
Created January 23, 2020 04:26
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xdade/272afa7fe0446acbe0303b03b2ef34ba to your computer and use it in GitHub Desktop.
Save 0xdade/272afa7fe0446acbe0303b03b2ef34ba to your computer and use it in GitHub Desktop.
Simple code snippet for a python file to delete itself, whether it's a standalone .py file or compiled into an executable using pyinstaller
#!/usr/bin/env python3
'''
Determine if this python is part of an executable or a standalone script and then delete the file accordingly.
If the script has been bundled into an executable using pyinstaller (such as pyinstaller --onefile <fname>.py) then the realpath of __file__ will be incorrect, thus the use of sys.executable.
Example of just relying on __file__:
$ pyinstaller --onefile test.py
[...]
$ ls dist/
test
$ ./test
Frozen
/Users/dade/dist/test.py
Example of using the sys.executable realpath:
$ pyinstaller --onefile test.py
[...]
$ cd dist/ && ls
test
$ ./test
Frozen
/Users/dade/dist/test
'''
import os
import sys
if getattr(sys, 'frozen', False):
path = os.path.realpath(sys.executable)
elif __file__:
path = os.path.realpath(__file__)
os.remove(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment