Created
January 23, 2020 04:26
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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