简体   繁体   English

Python中的Perl的BEGIN {}块

[英]Perl's BEGIN{} block in Python

I have Python code that uses the "with" keyword (new in 2.6) and I want to check if the interpreter version is at least 2.6, so I use this code: 我有使用“ with”关键字(2.6中的新增功能)的Python代码,并且我想检查解释器版本是否至少为2.6,所以我使用以下代码:

import sys
if sys.version < '2.6':
    raise Exception( "python 2.6 required" )

However, the 2.4 interpreter chokes on the with keyword (later in the script) because it doesn't recognize the syntax, and it does this before it evaluates my check. 但是,2.4解释器在with关键字(在脚本的后面)中阻塞了它,因为它无法识别语法,并且在评估我的检查之前就这样做了。

Is there something in Python analogous to Perl's BEGIN{} block? Python中是否有类似于Perl的BEGIN {}块的内容?

Perhaps someone has a better answer, but my first thought would be to have a separate script to perform the check, then import the "real" script once the check has passed. 也许有人有更好的答案,但是我的第一个想法是要有一个单独的脚本来执行检查,然后在检查通过后导入“真实”脚本。 Python won't check the syntax until the import happens. 在导入之前,Python不会检查语法。

import sys
if sys.version < '2.6':
    raise Exception( "python 2.6 required" )

import myscript  # runs myscript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM