乐趣区

野子科技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.
退出移动版