2012-06-30 28 views
29

我有一大段Python 2代碼。它想在開始時檢查Python 3,如果使用python3則退出。所以我試過了:python 2代碼:if python 3 then sys.exit()

import sys 

if sys.version_info >= (3,0): 
    print("Sorry, requires Python 2.x, not Python 3.x") 
    sys.exit(1) 

print "Here comes a lot of pure Python 2.x stuff ..." 
### a lot of python2 code, not just print statements follows 

但是,退出並沒有發生。輸出是:

$ python3 testing.py 
    File "testing.py", line 8 
     print "Here comes a lot of pure Python 2.x stuff ..." 
                 ^
SyntaxError: invalid syntax 

所以,它看起來像蟒蛇檢查執行任何以前整個代碼,因此錯誤。

python2代碼是否有一個很好的方式來檢查正在使用的python3,如果是的話打印一些友好的東西,然後退出?

回答

51

在開始執行之前,Python會對您的源文件進行字節編譯。整個文件必須至少正確解析,否則您將得到一個SyntaxError

針對您的問題最簡單的解決方案是編寫一個小的包裝器,解析爲Python 2.x和3.x.例如:

import sys 
if sys.version_info >= (3, 0): 
    sys.stdout.write("Sorry, requires Python 2.x, not Python 3.x\n") 
    sys.exit(1) 

import the_real_thing 
if __name__ == "__main__": 
    the_real_thing.main() 

聲明import the_real_thing只會的if語句之後執行,所以這種模塊中的代碼不需要解析像Python 3.X代碼。

+0

你也可以使用'if __name__ ==「foo」'塊,它的工作方式類似於'if __name__ =='__main __「',但在輸入'foo'時執行 – inspectorG4dget

+2

不會被考慮更多* Pythonic *使用EAFP,只需將'__report_thing'的輸入放入'try'塊中? – martineau

+1

@martineau:我不想這樣做。 'import'可能會成功,而其他錯誤可能發生在'main()'中。你不想在try/except中附上'the_real_thing.main() '。 –