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,如果是的話打印一些友好的東西,然後退出?
你也可以使用'if __name__ ==「foo」'塊,它的工作方式類似於'if __name__ =='__main __「',但在輸入'foo'時執行 – inspectorG4dget
不會被考慮更多* Pythonic *使用EAFP,只需將'__report_thing'的輸入放入'try'塊中? – martineau
@martineau:我不想這樣做。 'import'可能會成功,而其他錯誤可能發生在'main()'中。你不想在try/except中附上'the_real_thing.main() '。 –