pythonwindowspopenexecvp

Python script that restarts itself on Windows


I'm writing a python script that checks if there available a new version of it it deletes itself, copies a new version and reruns itself with the same arguments.

The code works on MacOs (Linux):

def main(args):    
    if _version.__version__ == '1.0.3':
        os.remove(sys.argv[0])
        shutil.copytree('/Users/john/Projects/utils/newcode/updatest/', str(script_dir), dirs_exist_ok=True)        
        print('Updating ...')

        args.insert(0, sys.executable)

        os.chdir(_startup_cwd)
        print('Rerunning ...')
        os.execv(sys.executable, args)


if __name__ == "__main__":
    print('This is a new code!')
    main(sys.argv)

In Windows it seems like working too, but it stuck in the cmd until you press "Enter". I also tried to use Popen and it behaves the same on Windows.

How do I do it properly in Windows?


Solution

  • In Windows you used to be unable delete a file which is still opened. It seems to have changed recently (cf this question) but I would not recommend relying on that if you intend to distribute your file, because it would not run on old Windows 10 versions, or non-10 Windows versions.

    Assuming that as long as your program is running you can't delete its own source file to replace it, another way to achieve the same result would be to replace the file indirectly. For that I see two approaches :

    The root problem is that Windows is not POSIX-compliant, so that things that work on POSIX systems (Lunix, MacOS, ...) does not work for Windows.