I'd like to very elegantly integrate version checking in Python.
I don't want a version checking routine to throw off the indentation of all of my code, however.
I.e.
if old_version:
print 'hey, upgrade.'
else:
# main body of whole script
In the above implementation, the main body of the whole script would need to be indented one level and that's just messy.
Is there a better way?
You can do
import sys
if old_version:
print 'hey, upgrade.'
sys.exit(1) # A non-zero code indicates failure, on Unix (sys.exit() exits too, but it returns a 0 [=success] exit code)
# main body of whole script
This exits the interpreter if the code needs to be upgraded.
The reason for returning a non-zero exit code is that if your program is called from a Unix shell script and an upgrade is necessary, the shell will detect that there was problem and the user will know about it (instead of your program failing silently).
PS: As suggested in an answer which is now deleted, you can also do sys.exit("hey, upgrade"), instead. This automatically returns an exit code of 1, as is appropriate.
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