티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보) 된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 주요 키워드를 미리 확인하세요.

How can I check for Python version in a program that uses new language features?

새로운 언어 기능을 사용하는 프로그램에서 파이썬 버전을 확인하려면 어떻게 해야 합니까?

 문제 내용 

If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?

적어도 특정한 것을 요구하는 Python 스크립트가 있다면 파이썬 버전, 우아하게 실패하는 올바른 방법은 무엇입니까? 이전 버전의 Python이 스크립트를 실행하는 데 사용되는 경우?

 

How do I get control early enough to issue an error message and exit?

오류 메시지를 표시할 수 있을 정도로 빨리 제어하려면 어떻게 해야 합니까? 그리고 퇴장?

 

For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.

예를 들어, 나는 테리어 연산자(2.5에서 새로 추가)와 "with" 블록을 사용하는 프로그램이 있다. (2.6에서 새로 추가됨) 나는 간단한 작은 통역사 버전을 썼다. 스크립트가 가장 먼저 수행하는 검사 루틴 …을 부르다 그렇게 멀리 가지 않는다는 것만 빼면요. 대신에, 내 루틴 전에 파이썬 컴파일 중에 스크립트가 실패함 라고도 불린다. 따라서 스크립트의 사용자는 일부를 매우 본다. 불분명한 시낙스 오류 추적 - 이것은 매우 많이 필요하다. 그것이 단순히 달리기의 경우라고 추론하는 전문가 잘못된 버전의 파이썬입니다.

 

I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:

나는 파이썬 버전을 확인할 줄 안다. 문제는 이전 버전의 파이썬에서 일부 구문이 불법이라는 것이다. 이 프로그램을 고려해 보십시오.

 

import sys
if sys.version_info < (2, 4):
    raise "must use python 2.5 or greater"
else:
    # syntax error in 2.4, ok in 2.5
    x = 1 if True else 2
    print x

When run under 2.4, I want this result

2.4 미만으로 실행할 때 이 결과를 원합니다.

 

$ ~/bin/python2.4 tern.py 
must use python 2.5 or greater

and not this result:

이 결과가 아닌 경우:

 

$ ~/bin/python2.4 tern.py 
  File "tern.py", line 5
    x = 1 if True else 2
           ^
SyntaxError: invalid syntax

(Channeling for a coworker.)

(동료를 위한 채널링)

 

 

 

 높은 점수를 받은 Solution 

You can test using eval:

eval을 사용하여 테스트할 수 있습니다.

 

try:
  eval("1 if True else 2")
except SyntaxError:
  # doesn't have ternary

Also, with is available in Python 2.5, just add from __future__ import with_statement.

또한 와 함께 파이썬 2.5에서 사용할 수 있으며 __future_import with_statement에서 추가하기만 하면 됩니다.

 

EDIT: to get control early enough, you could split it into different .py files and check compatibility in the main file before importing (e.g. in __init__.py in a package):

편집: 컨트롤을 충분히 일찍 얻으려면 가져오기 전에 다른 .py 파일로 분할하고 메인 파일의 호환성을 확인할 수 있습니다(예: 패키지의 __init_.py).

 

# __init__.py

# Check compatibility
try:
  eval("1 if True else 2")
except SyntaxError:
  raise ImportError("requires ternary support")

# import from another module
from impl import *

 

 

 가장 최근 달린 Solution 

import sys
sys.version

will be getting answer like this

이렇게 답변을 받을 것이다.

 

'2.7.6 (default, Oct 26 2016, 20:30:19) \n[GCC 4.8.4]'

'2.7.6(기본값, 2016년 10월 26일, 20:30:19) \n[GCC 4.8.4]'

 

here 2.7.6 is version

여기서 2.7.6은 버전입니다.

 

 

 

출처 : https://stackoverflow.com/questions/446052/how-can-i-check-for-python-version-in-a-program-that-uses-new-language-features

반응형
댓글
공지사항
최근에 올라온 글