2017-05-31 57 views
0

運行我在想,如果是這樣的可能:允許一個腳本來通過多個版本的Python

import sys  
if sys.version[0] == '2': 
    print 'this would fail in python3' 
if sys.version[0] == '3': 
    print("and this would fail in 2") 

現在,如果這個被執行或者python2還是python3運行該代碼時會失敗。有沒有辦法只有在正確版本的情況下才能運行一段代碼,如果它是錯誤的版本,完全忽略它?

+0

如果試圖用這個Python3,你得由於缺少括號(第3行)肯定是錯誤 – Nuageux

+0

是的,就是這一點。有沒有辦法不讓python3檢查python2的代碼片段,反之亦然? –

+1

將L3更改爲'print('這將在python3'中失敗)'並且它將運行(對於Python 2和Python 3) – Nuageux

回答

1

如果我正確地理解了你的答案是否定的,你不能通過python3來運行python代碼,並且忽略python2運行的那些位,就像沒有括號的print聲明一樣。

但是,您可以將代碼拆分爲2個獨立的模塊,並在使用python3或python2運行它們之前進行檢查。

更好的選擇是編寫與python3和python2兼容的代碼。

0

您也可以在python 2中導入python 3的打印功能。

from __future__ import print_function 
import sys  
if sys.version[0] == '2': 
    print('this would fail in python3') 
if sys.version[0] == '3': 
    print("and this would fail in 2") 

它將在兩個python版本中都能很好地工作。

1

這是不可能使Python 3忽略行

print 'this would fail in python3' 

,因爲從Python3的觀點是語法錯誤。程序首先作爲一個整體進行解析(甚至是在運行時不執行的行),然後執行。語法錯誤導致無法解析。

你必須讓你的代碼語法都正確的Python 2 & 3。例如,你可以做

from __future__ import print_function 

然後

print(…) 

將同時在Python 2和3相同的工作。

+0

你不需要打印函數來使Python 2和3中的語法正確,只需要在兩個打印調用 –

+0

@Chris_Rands周圍使用圓括號,是的,這是正確的。但是這種行爲在2和3中會有所不同,這可能會導致錯誤,所以我寧願導入'print_function'。 –

0

我用的地方下面的代碼片段,我真的必須有多個代碼,以支持兩個版本2和3

from __future__ import print_function 
from __future__ import print_function 
from __future__ import unicode_literals 
from __future__ import division 

import sys 

if (sys.version_info > (3, 0)): 
    # Python 3 code here 
    print("Code for Python3 won't work in py2") 
else: 
    # Python 2 code here 
    print("Code for python3 won't work here")