tags:

views:

572

answers:

4

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.

+11  A: 

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.

Martin v. Löwis
cool... i thought it wasn't because of an error i was getting, but i now see it was a stupid mistake i was making.
carrier
+4  A: 

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.

ΤΖΩΤΖΙΟΥ
i'll probably implement it this way. thanks.
carrier
+4  A: 

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!]

Matthew Schinckel
Yes, but your answer is much more thorough, so it's worth a vote up :)
ΤΖΩΤΖΙΟΥ
+1  A: 

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.

David