ybonda
ybonda

Reputation: 1710

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?

Upvotes: 0

Views: 121

Answers (1)

Lenormju
Lenormju

Reputation: 4378

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 :

  • either use a different process (whose code is in another file) so that it can replace the main file and start it after the update, that's why many programs have an auto-updater that is distinct from the main program
  • or at the startup of your program, after it has checked there is a new version, downloaded it and saved it with a different name, tell the user to re-start to use the new version (or force an exit). The new version at startup checks for olf versions, and if it finds any, deletes them.

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.

Upvotes: 1

Related Questions