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.
Yes it is possible.
Python file write() functionIf the file has already content in there, then it will overwrite it. Now, we can also append the content to the file and not overwrite that content by the following code. Due to a flag, it will append the content after the existing content. It does not overwrite the content.
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.
Challenge: Run a piece of Python code forever—until it is forcefully interrupted by the user. Solution: use a while loop with a Boolean expression that always evaluates to True . Examples: have a look at the following variants of an infinite while loop.
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.
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!]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With