野子科技python3代码兼容python2

野子电竞数据官网改版https://www.xxe.io/全新登场
python3代码兼容python2的方式
1.使用future特性
Python的每个新版本都会增加一些新的功能,或者对原来的功能作一些改动。有些改动是不兼容旧版本的,也就是在当前版本运行正常的代码,到下一个版本运行就可能不正常了。

Python提供了__future__模块,把下一个新版本的特性导入到当前版本,于是我们就可以在当前版本中测试一些新版本的特性。

例如在python2.7中使用python3的print(“xxx”),就需要在文件开头引用future模块,不然报错:

SyntaxError: from future imports must occur at the beginning of the file
1

使用高版本的print与除法

from future import print_function
from future import division
1
2
3
Python 2.7.12 (default, Nov 12 2018, 14:36:49)
[GCC 5.4.0 20160609] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.

import
future

print ‘aaa’

aaa

print(aa)

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

NameError: name ‘aa’ is not defined

print(“aa”)

aa

print(‘aa’)

aa

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2.使用脚本将py2转为py3
转换python2代码到python3代码,网络上大部分答案是通过python安装目录下的 Tools/scripts/2to3.py脚本;

如果是在windows系统下,2to3.py在[python或anaconda安装目录]scripts目录下;

但是在ubuntu16.04系统中,通过apt-get install安装的python3.5.2,系统中并没有2to3.py文件。
在/usr/bin/目录下, 有若干 2to3 的命令,这些命令可以被直接调用。

2to3 -w /path/a/file.py

1
2
3
4
5
6
7
2to3命令的参数:

Usage: 2to3 [options] file|dir …

Options:
-h, –help show this help message and exit
-d, –doctests_only Fix up doctests only
-f FIX, –fix=FIX Each FIX specifies a transformation; default: all
-j PROCESSES, –processes=PROCESSES

                    Run 2to3 concurrently

-x NOFIX, –nofix=NOFIX

                    Prevent a transformation from being run

-l, –list-fixes List available transformations
-p, –print-function Modify the grammar so that print() is a function
-v, –verbose More verbose logging
–no-diffs Don’t show diffs of the refactoring
-w, –write Write back modified files
-n, –nobackups Don’t write backups for modified files
-o OUTPUT_DIR, –output-dir=OUTPUT_DIR

                    Put output files in this directory instead of
                    overwriting the input files.  Requires -n.

-W, –write-unchanged-files

                    Also write files even if no changes were required
                    (useful with --output-dir); implies -w.

–add-suffix=ADD_SUFFIX

                    Append this string to all output filenames. Requires
                    -n if non-empty.  ex: --add-suffix='3' will generate
                    .py3 files.
    原文作者:待你幼稚完
    原文地址: https://segmentfault.com/a/1190000020360285
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞