我想制作一个在2.7和3.4版本上运行的Python程序。例如,我只做了一些改变,使其像print(“”,end =“”)那样工作。如何在多个Python版本中使用一个源代码?
有没有像
if __name__ == "__main__":
什么标签,我可以把我的代码得到的东西,如:
1. python_version = platform.version_tuple()
2. if python_version[0] == 3:
3. print("myprint", end="")
4. else:
5. print "my second print",
我怎样才能避免这种代码的编译错误?
谢谢你所有的答案,我的问题不是很清楚,但你确实帮了忙。我发现这个网站的相关详细阅读你的答案后:
http://python3porting.com/noconv.html
它说明了如何处理这两个python2和python3到相同的代码,而无需将其划分在2级冗余的部件。
做正确的方法是使用内容sys.version
1. import sys
2. if sys.version < '3':
3. #some code for python 3.X
4. else:
5. #some code for older python
或者使用print_function从打印问题未来图书馆
1. from __future__ import print_function
和导入错误错误如下
1. try:
2. from urllib.request import urlopen
3. except ImportError:
4. from urllib import urlopen
再次感谢您的帮助
另请参见:http://stackoverflow.com/questions/12162629/using-print-in-python2-x – mgilson
你也可以在python2的print语句中使用parens。但是,如果您想在一个版本中使用不与其他版本编译的语法,则必须将其放入单独的模块中,并且只有在版本匹配时才导入它。 – l4mpi
另请参见:[Python 2和Python 3双重开发](http://stackoverflow.com/questions/11372190/python-2-and-python-3-dual-development) – Trilarion