簡體   English   中英

從python腳本中檢查python版本,如果/則基於它

[英]check python version(s) from within a python script and if/else based on that

基本上我想知道是否有辦法知道腳本在腳本中使用的python版本是什么? 這是我當前想要使用它的示例:

如果使用python 2,我想讓python腳本使用unicode,否則不使用unicode。 我目前安裝了python 2.7.5和python 3.4.0,並在python 3.4.0下運行我當前的項目。 以下scirpt:

_base = os.path.supports_unicode_filenames and unicode or str

正在返回錯誤:

    _base = os.path.supports_unicode_filenames and unicode or str
NameError: name 'unicode' is not defined

所以我將其更改為此以使其工作:

_base = os.path.supports_unicode_filenames and str

有沒有辦法將其更改為此效果:

if python.version == 2:

    _base = os.path.supports_unicode_filenames and unicode or str

else:

    _base = os.path.supports_unicode_filenames and str

你非常接近:

import sys
sys.version_info

會回來:

sys.version_info(major=2, minor=7, micro=4, releaselevel='final', serial=0)

你可以做這樣的事情:

import sys
ver = sys.version_info[0]
if ver == 2:
    pass

使用sys.version_info檢查Python版本。 例如:

import sys

if sys.version_info[0] == 2:
    ... stuff
else:
    ... stuff

您應該查看six庫以更好地支持Python 2和3之間的差異。

您可以為Python 3定義unicode

try:
    unicode = unicode
except NameError: # Python 3 (or no unicode support)
    unicode = str # str type is a Unicode string in Python 3

要檢查版本,可以使用sys.versionsys.hexversionsys.version_info

import sys

if sys.version_info[0] < 3:
   print('before Python 3 (Python 2)')
else: # Python 3
   print('Python 3 or newer')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM