How can I elegantly implement version checking in Python without throwing off indentation?
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 bo开发者_运维知识库dy 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.
This should only be a problem if you aren't putting your code in functions.
If you aren't putting your code in functions you should do that.
How about
if old_version:
raise Exception ('Hey, upgrade')
?
Well, depending on if the upgrade is required or not.
Just sys.exit(0)
:
if old_version:
print 'hey, upgrade.'
sys.exit(0)
As Adam Vandenberg points out, a non-zero exit code will indicate failure to anything capturing the exit code. So that might be more appropriate.
精彩评论