野子科技python3代码兼容python2
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了野子科技python3代码兼容python2,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2448字,纯文字阅读大概需要4分钟。
内容图文
![野子科技python3代码兼容python2](/upload/InfoBanner/zyjiaocheng/717/e265f2d08aa249aca4ea6de0d5c41d1f.jpg)
野子电竞数据官网改版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’
aaaprint(aa)
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘aa’ is not definedprint(“aa”)
aaprint(‘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.
内容总结
以上是互联网集市为您收集整理的野子科技python3代码兼容python2全部内容,希望文章能够帮你解决野子科技python3代码兼容python2所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。