如何在不丢弃缩进的情况下优雅地在Python中实现版本检查?

eas*_*de5 2 python

我想非常优雅地在Python中集成版本检查.

但是,我不希望版本检查例程抛弃我所有代码的缩进.

if old_version:
   print 'hey, upgrade.'
else:
  # main body of whole script
Run Code Online (Sandbox Code Playgroud)

在上面的实现中,整个脚本的主体需要缩进一个级别,这只是凌乱.

有没有更好的办法?

Eri*_*got 7

你可以做

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
Run Code Online (Sandbox Code Playgroud)

如果代码需要升级,这将退出解释器.

返回非零退出代码的原因是,如果从Unix shell脚本调用程序并且需要升级,shell将检测到存在问题并且用户将知道它(而不是您的程序无声地失败) ).

PS:正如现在删除的答案中所建议的那样,您也可以这样做sys.exit("hey, upgrade").这将自动返回退出代码1,视情况而定.