1

For no particular reason (mainly just the joy of experimentation), I'm looking for a way to write a python script, that self-destroys after execution. One simple approach would be to determine the file, that is being called from the file itself and delete it afterwards as in:

import os
DIR_PATH = os.path.realpath(__file__)
os.remove(DIR_PATH)

which fails for obvious reasons (at least on windows) as the file is hold by the python process. How would I go about to achieve this? Bonus karma points for a real-world application on why anyone would do this.

Nouman
  • 6,947
  • 7
  • 32
  • 60
Dschoni
  • 3,714
  • 6
  • 45
  • 80
  • 1
    Well, your script works on debian :) – Stanowczo Aug 23 '19 at 13:30
  • Run the delete in a subprocess. – slybloty Aug 23 '19 at 13:31
  • 1
    Because Debian can! – Dschoni Aug 23 '19 at 13:31
  • 1
    Of course, `os.remove` only removes *one* link to the script, not *all* links. – chepner Aug 23 '19 at 13:31
  • I'm not able to reproduce the windows behaviour, because i'm on linux, but obvious solution is to spawn another one process, which will remove file, maybe with a little delay. I think you can just send a command into shell – Alexandr Zayets Aug 23 '19 at 13:33
  • Regarding Subprocesses: Is this defined behaviour to kill the parent while a child process is active? – Dschoni Aug 23 '19 at 13:36
  • 1
    If you want to have fun then write the python file (this works if you need one file only), put it on git as public and then run it like this: `curl https://gitlab.com/username/project/raw/master/demo.py | python -` this way, the script will just be executed, not save and no need to delete. you usually don't do this, but this is how I proceed with my installers – Marius Bogdan Aug 23 '19 at 13:40

0 Answers0