29
私は大きなPython 2コードしか持っていません。 Python 3を最初にチェックし、python3を使用すると終了します。だから私は試しました:python 2 code:もしpython 3ならば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
だから、それはPythonのチェックのようなので、全体何かを実行する前に、コード、およびエラーを探します。
python2コードがpython3が使用されているかどうかをチェックする良い方法はありますか?
'if __name__ ==" foo "'ブロックを使うこともできます。これは 'if __name__ ==" __main __ "'のように動作しますが、 'foo'をインポートすると実行します。 – inspectorG4dget
もっと考えないでしょうか?Pythonic * EAFPを使用し、the_real_thingのインポートを 'try'ブロックの中に置くだけですか? – martineau
@martineau:手元にある場合はこれをしません。 'import'はうまくいくかもしれませんし、' main() 'で他のエラーが起こるかもしれません。 'the_real_thing.main() 'をtry/exceptで囲むことは望ましくありません。 –