Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restarting a self-updating python script

I have written a script that will keep itself up to date by downloading the latest version from a website and overwriting the running script.

I am not sure what the best way to restart the script after it has been updated.

Any ideas?

I don't really want to have a separate update script. oh and it has to work on both linux/windows too.

like image 666
Ashy Avatar asked Nov 17 '09 18:11

Ashy


People also ask

How do I restart a Python script?

Restart the Program Script in Python Using the os. execv() Function. The os. execv(path, args) function executes the new program by replacing the process.

Can a Python script change itself?

Yes it is possible.

What happens if you change Python code while running?

It happens nothing. Once the script is loaded in memory and running it will keep like this. An "auto-reloading" feature can be implemented anyway in your code, like Flask and other frameworks does.

How do I update my Python program?

Updating to a new Python version is easy on a computer running Windows. All you have to do is visit the Python downloads page and download the latest version. Clicking on the button will replace the existing version of Python with the new version. The older version will be removed from your computer.


2 Answers

In Linux, or any other form of unix, os.execl and friends are a good choice for this -- you just need to re-exec sys.executable with the same parameters it was executed with last time (sys.argv, more or less) or any variant thereof if you need to inform your next incarnation that it's actually a restart. On Windows, os.spawnl (and friends) is about the best you can do (though it will transiently take more time and memory than os.execl and friends would during the transition).

like image 152
Alex Martelli Avatar answered Sep 23 '22 18:09

Alex Martelli


The CherryPy project has code that restarts itself. Here's how they do it:

    args = sys.argv[:]     self.log('Re-spawning %s' % ' '.join(args))      args.insert(0, sys.executable)     if sys.platform == 'win32':         args = ['"%s"' % arg for arg in args]      os.chdir(_startup_cwd)     os.execv(sys.executable, args) 

I've used this technique in my own code, and it works great. (I didn't bother to do the argument-quoting step on windows above, but it's probably necessary if arguments could contain spaces or other special characters.)

like image 41
Josh Avatar answered Sep 22 '22 18:09

Josh