我们有相关的问题,一个支持Jython和CPython的大型系统返回到2.4。基本上,您需要将需要以不同方式编写的代码隔离到一组希望很小的模块中,并有条件地导入内容。
# module svn.py
import sys
if sys.platform.startswith('java'):
from jythonsvn import *
else:
from nativesvn import *
在您的示例中,您可能会对sys.version_info使用测试。您可以在实用程序模块中定义一些简单的东西,例如:from util import*
# module util.py
import sys
if sys.exc_info[0] == 2:
if sys.exc_info[1] == 4:
from util_py4 import *
...
然后util_py4.py中的内容如下:
def any(seq): # define workaround functions where possible
for a in seq:
if a: return True
return False
...
虽然这是一个不同于移植的问题(因为您希望继续支持),但是这个链接提供了一些有用的指导
http://python3porting.com/preparing.html
(与其他关于移植Python2.x的文章一样)。
你说没有上下文管理器你就活不下去,这有点让人困惑。
虽然上下文管理器功能强大,使代码更具可读性,并将错误风险降至最低,但在2.4版本的代码中却无法使用它们。
### 2.5 (with appropriate future import) and later
with open('foo','rb')as myfile:
# do something with myfile
### 2.4 and earlier
myfile = None
try:
myfile = open('foo','rb')
# do something with myfile
finally:
if myfile: myfile.close()
既然您想支持2.4,那么您将拥有一个只需使用第二种语法的代码体。两种写法真的会更优雅吗?