이전 인터프리터 버전으로 인해 실패한 향후 기능 (__future__) 가져 오기를 정상적으로 처리하는 방법은 무엇입니까?
실패한 향후 기능 가져 오기를 어떻게 정상적으로 처리합니까? 사용자가 Python 2.5를 사용하여 실행 중이고 내 모듈의 첫 번째 명령문은 다음과 같습니다.
from __future__ import print_function
Python 2.5 용으로이 모듈을 컴파일하면 다음과 같은 오류가 발생합니다.
File "__init__.py", line 1
from __future__ import print_function
SyntaxError: future feature print_function is not defined
사용자에게 Python> = 2.6으로 프로그램을 다시 실행해야 함을 알리고 방법에 대한 지침을 제공 할 수 있습니다. 그러나 PEP 236 을 인용하면 다음과 같습니다.
future_statement 앞에 나타날 수있는 유일한 줄은 다음과 같습니다.
- 모듈 독 스트링 (있는 경우).
- 코멘트.
- 빈 줄.
- 기타 future_statements.
그래서 나는 다음과 같은 것을 할 수 없습니다.
import __future__
if hasattr(__future__, 'print_function'):
from __future__ import print_function
else:
raise ImportError('Python >= 2.6 is required')
산출하기 때문에 :
File "__init__.py", line 4
from __future__ import print_function
SyntaxError: from __future__ imports must occur at the beginning of the file
PEP의이 스 니펫은 인라인으로 수행 할 수있는 희망을주는 것 같습니다.
Q : try / except 블록으로 future_statements를 래핑하고 싶습니다. 실행중인 Python 버전에 따라 다른 코드를 사용할 수 있습니다. 왜 안돼?
A : 죄송합니다! try / except는 런타임 기능입니다. future_statements는 주로 컴파일 타임 기믹이며 컴파일러가 완료된 후 오랫동안 try / except가 발생합니다. 즉, 시도 / 예외를 수행 할 때 모듈에 적용되는 의미는 이미 완료된 거래입니다. try / except가 달성 해야하는 것처럼 보이는 것을 달성하지 못하기 때문에 단순히 허용되지 않습니다. 우리는 또한 이러한 특별한 진술을 매우 쉽게 찾고 인식하기를 원합니다.
당신이주의 할 수 직접 __future__ 수입 및 방출이 주어진 기능의 상태와 관련하여 스탠드에서 실행하고있는 곳을 파악, sys.version_info과 함께 그 안에 정보를 사용합니다.
아이디어?
"사용자에게 Python> = 2.6으로 프로그램을 다시 실행해야 함을 알리고 방법에 대한 지침을 제공 할 수 있습니다."
README 파일의 용도가 아닙니까?
여기에 대안이 있습니다. "래퍼": 대상 aop을 실행하기 전에 환경을 확인하는 Python의 작은 덩어리.
파일 : appwrapper.py
import sys
major, minor, micro, releaselevel, serial = sys.version_info
if (major,minor) <= (2,5):
# provide advice on getting version 2.6 or higher.
sys.exit(2)
import app
app.main()
"직접 수입"이 의미하는 것. 의 내용을 검사 할 수 있습니다 __future__
. a from __future__ import print_function
가 컴파일러에 대한 정보 라는 사실에 여전히 묶여 있지만 실제 작업을 수행하는 모듈을 가져 오기 전에 살펴볼 수 있습니다.
import __future__, sys
if hasattr(__future__, 'print_function'):
# Could also check sys.version_info >= __future__. print_function.optional
import app
app.main()
else:
print "instructions for upgrading"
A rather hacky but simple method I've used before is to exploit the fact that byte literals were introduced in Python 2.6 and use something like this near the start of the file:
b'This module needs Python 2.6 or later. Please do xxx.'
This is harmless in Python 2.6 or later, but a SyntaxError
in any earlier versions. Anyone trying to compile your file will still get an error, but they also get whatever message you want to give.
You might think that as you will have to have this line after your from __future__ import print_function
then it will be the import that generates the SyntaxError
and you won't get to see the useful error message, but strangely enough the later error takes precedence. I suspect that as the error from the import isn't really a syntax error in itself it isn't raised on the first compilation pass, and so real syntax errors get raised first (but I'm guessing).
This might not meet you criteria for being 'graceful', and it is very Python 2.6 specific, but it is quick and easy to do.
Just put a comment on the same line with the "from __future__ import ..."
, like this:
from __future__ import print_function, division # We require Python 2.6 or later
Since Python displays the line containing the error, if you try to run the module with Python 2.5 you'll get a nice, descriptive error:
from __future__ import print_function, division # We require Python 2.6 or later
SyntaxError: future feature print_function is not defined
'Nice programing' 카테고리의 다른 글
마우스를 올려도 "youtube"상단의 막대를 숨기는 방법은 무엇입니까? (0) | 2020.11.07 |
---|---|
Entity Framework Core에서 데이터베이스 자동 생성 (0) | 2020.11.07 |
List (of object)를 List (of string)로 변환 (0) | 2020.11.07 |
MySQL. (0) | 2020.11.07 |
Core-Data의 사용자 지정 setter 메서드 (0) | 2020.11.07 |