Tengo una gran parte del código Python 2 solamente. Quiere comprobar Python 3 al principio y salir si se usa python3. Así que probé:código python 2: si python 3 luego 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
Sin embargo, la salida no ocurre. La salida es:
$ python3 testing.py
File "testing.py", line 8
print "Here comes a lot of pure Python 2.x stuff ..."
^
SyntaxError: invalid syntax
Por lo tanto, parece que los cheques pitón del toda código antes de ejecutar cualquier cosa, y por lo tanto el error.
¿Hay alguna manera agradable para que el código python2 compruebe que se está utilizando python3, y si es así, imprima algo amigable y luego salga?
También podría usar un bloque 'if __name__ ==" foo "', que funciona como 'if __name__ ==" __main __ "' pero se ejecuta cuando se importa 'foo' – inspectorG4dget
¿No lo consideraría más * Pythonic * para usar EAFP y simplemente poner la importación de the_real_thing dentro de un bloque 'try'? – martineau
@martineau: No haría esto en el caso que nos ocupa. La 'importación' podría muy bien tener éxito, y otros errores podrían ocurrir en' main() '. No desea adjuntar 'the_real_thing.main() ' en try/except. –