2

I'm trying to create a python script to convert into exe which just deletes itself. When I run it as .py file it works. The code is this:

import os
os.remove(os.getcwd + "\\test.py")

I'm working in Windows that's why I'm using \\ and the file is obviously named test.py. But when I convert it into an exe file (I've tried both with py2exe and pyinstaller) it gives me access denied error. Does anyone know how to fix this?

PS: Yes, I've changed the name to test.exe if you're asking.

  • 3
    Possible duplicate of [How can a program delete its own executable](http://stackoverflow.com/questions/1606140/how-can-a-program-delete-its-own-executable) – Patrick Haugh Feb 02 '17 at 14:15

2 Answers2

0

It won't be this simple. 1) When you are running the script actually it is the python.exe executing the statements and the script file (test.py) is free. In this way python.exe can delete the script. 2) When you convert convert your script to exe, it is the exe file itself executing, which means the file is 'busy', or said in other words - used by the process, and it cannot be deleted.

Find a way to start another process, which would delete the file after you exit the current process.

Edit(sample code):


import sys
import ctypes
import platform
import subprocess

def execute(command, async=False): """ if async=False Executes a shell command and waits until termination and
returns process exit code if async=True Executes a shell command without waiting for its termination and returns subprocess.Popen object On Windows, does not create a console window. """ if async: call = subprocess.Popen else: call = subprocess.call

if platform.system() == 'Windows':
    # the following CREATE_NO_WINDOW flag runs the process without 
    # a console window
    # it is ignored if the application is not a console application
    return call(command, creationflags=0x08000000)
else:
    return call(command)

def main():

ctypes.windll.user32.MessageBoxA(0, __file__, 'Show path', 0) ctypes.windll.user32.MessageBoxA(0, sys.executable, 'sys.executable', 0) with open(r'D:\delete_me.py', 'w') as f: f.write('import os\n') f.write('import time\n') f.write('time.sleep(2)\n') f.write('os.remove(r"{}")'.format(sys.executable)) execute(r'C:\Python27\python.exe D:\delete_me.py', async=True)

if __name__ == '__main__': main()

And this was compiled with `pyinstaller.exe --onefile --windowed D:\self_delete.py

execute function is something we use to execute calls on both Linux and Windows and I just copied it. This is why the platform check is there. You can use some .bat file with timeout instead of sleep or whatever else you want if you can't execute delete_me.py

DTL
  • 13
  • 4
0

What you can do is to use a VBScript to do this. What I have done is made this:

deleteFile is the location of the exe you want to delete. It doesnt matter if its running or not, If its running then it will first be terminated forcefully then deleted, then the VBScript will delete itself too. All this will happen without the console window opening to make it more convenient for the end user. The Python Code is listed below this code

deleteFile ="Install.exe"
Dim oShell : Set oShell = CreateObject("WScript.Shell")
oShell.Run "taskkill /f /im install.exe", 0, True
Set fso = CreateObject("Scripting.FileSystemObject")
  If fso.FileExists(deleteFile) Then
    Set fs = CreateObject("Scripting.Filesystemobject")
    fs.DeleteFile(deleteFile)
  Else
  End If
Set oFso = CreateObject("Scripting.FileSystemObject") : oFso.DeleteFile Wscript.ScriptFullName, True

The Python Code:

Here you will have to change \Filename.extention to \Yourfilename.yourfilextension for ex. \example.exe

import os
fname = "Filename.extention"
path = os.getcwd() + "\\" + fname

delcode = f'''deleteFile ="{path}"
Dim oShell : Set oShell = CreateObject("WScript.Shell")
oShell.Run "taskkill /f /im install.exe", 0, True
Set fso = CreateObject("Scripting.FileSystemObject")
  If fso.FileExists(deleteFile) Then
    Set fs = CreateObject("Scripting.Filesystemobject")
    fs.DeleteFile(deleteFile)
  Else
  End If
Set oFso = CreateObject("Scripting.FileSystemObject") : oFso.DeleteFile Wscript.ScriptFullName, True'''

f = open("C:\Windows\Temp\delete.vbs", "w")
f.write(delcode)
os.startfile("C:\Windows\Temp\delete.vbs")

The only think you need to do is to add the python code to a function, then change what I said above and just run the function. I have tested it myself and it worked perfectly so there should be no errors in the code

Edit: I know its very old thread but I just wanted to put my answer too since I felt it was easier than others + I was also finding an answer myself to this question so why not to help others too incase someone comes across the same question!

Pandoric
  • 1
  • 2