Search code examples
pythonpyinstaller

os.startfile() doesn't work after compiling python script with pyinstaller


I've made selfdestruct function that create a batch file that deletes the executable. It works when running the python file and the batch file opens normally. But after compiling it to an exe using pyinstaller it doesn't open.

I tried this

import os, sys
batchFilePath = 'C:\\Users\\Admin\\Desktop\\selfDelete.bat'
pathofscript = sys.argv[0]
batchCode = f'del /F /Q  {pathofscript}'
with open(batchFilePath, 'w') as f:
    f.write(batchCode)
    f.close()
os.startfile(batchFilePath)

Solution

  • Use sys.executable when targeting the executable. However your should note that when running the code as a python script sys.executable points to python.exe. So running your code as a python script would delete your python executable.

    As such, I suggest testing to make sure that the code is being run from the compiled executable before executing the portion that actually runs the batch file. I have included an example of this below.

    import os, sys, pathlib
    
    batchFilePath = pathlib.Path.home() / "Desktop" / 'selfDelete.bat'
    
    if pathlib.Path(__file__).parent.name.startswith("_MEI"):
        batchFilePath.write_text(f'del /F /Q  {sys.executable}')
        os.startfile(batchFilePath)