carrier
carrier

Reputation: 33049

Is it possible for a running python program to overwrite itself?

Is it possible for a python script to open its own source file and overwrite it?

The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version.

Upvotes: 20

Views: 7237

Answers (4)

David
David

Reputation: 18281

You might also want to check out this module ( which is in 2.5 & 3 as well )

http://www.python.org/doc/2.1.3/lib/os-process.html

Specifically the execv method will overwrite the current process with whatever you call from this method. I've done some personnel tests and it works pretty reliably.

Upvotes: 1

Matthew Schinckel
Matthew Schinckel

Reputation: 35629

If you put most of the code into a module, you could have the main file (which is the one that is run) check the update location, and automatically download the most recent version and install that, before the module is imported.

That way you wouldn't have to have a restart of the application to run the most recent version, just reimport the module.

# Check version of module
import module

# Check update address
if update_version > module.version:
    download(update_module)
    import module
    reload(module)

module.main()

You can use the reload() function to force a module to reload it's data. Note there are some caveats to this: objects created using classes in this module will not be magically updated to the new version, and "from module import stuff" before the reimport may result in "stuff" referring to the old object "module.stuff".

[Clearly, I didn't read the previous post clearly enough - it does exactly what I suggest!]

Upvotes: 16

tzot
tzot

Reputation: 95971

Actually, it's preferable that your application starts with a dummy checker-downloader that changes rarely (if ever); before running, it should check if any updates are available; if yes, then it would download them (typically the rest of the app would be modules) and then import them and start the app.

This way, as soon as updates are available, you start the application and will run the latest version; otherwise, a restart of the application is required.

Upvotes: 8

Martin v. Löwis
Martin v. Löwis

Reputation: 127467

That's certainly possible. After the script is loaded/imported, the Python interpreter won't access it anymore, except when printing source line in a exception stack trace. Any pyc file will be regenerated the next time as the source file is newer than the pyc.

Upvotes: 26

Related Questions