下面列举了搭建一个兼容python2和3的环境,介绍python2 和 python3 的一些区别,利于写出兼容python2和3的代码,同时能够了解一些python3的特性。
选择anaconda搭建环境,访问anaconda官网,下载anaconda3(即默认使用python3环境, https://www.continuum.io/downloads/)。
# 安装anaconda3 bash Anaconda3-4.3.1-Linux-x86_64.sh # 安装路径 /opt/anaconda3 bashrc 添加 export PATH=/opt/anaconda3/bin:$PATH
# 创建py2 命名的python2环境 conda create -n py2 python=2 # 默认安装路径 /opt/anaconda3/envs/py2 # 可用以下命令激活和退出环境 source activate py2 source deactivate py2 # 删除该环境 conda remove -n py2 --all # conda remove -n py2 numpy # 删除该环境下某个模块 # 安装 matplotlib conda install matplotlib # 激活某个环境(如py2)后,在py2下安装matplotlib # 查看已安装的包 conda list # 包更新 conda update matplotlib # 删除包 conda remove matplotlib 对于那些用 pip 无法安装成功的模块你都可以尝试用 conda 来安装,如果用 conda 找不到相应的包,当然你继续选择 pip 来安装包也是没问题的。 ## 其他命令 #查看版本 conda info --envs || conda env list # 创建只有django的python2环境,名字py2-dj,注意,python=2 django是连续参数 conda create python=2 django -n py2-dj # 对所有工具包进行升级 conda upgrade --all # 查看所有的 packages conda list # 删除名为 env_name 的环境: conda env remove -n env_name # 当分享代码的时候,同时也需要将运行环境分享给大家,执行如下命令可以将当前环境下的 package 信息存入名为 environment 的 YAML 文件中。 conda env export > environment.yaml # 创建相同环境 conda env create -f environment.yaml # 更新python conda update python # 添加Anaconda的TUNA镜像 conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ # TUNA的help中镜像地址加有引号,需要去掉 # 设置搜索时显示通道地址 conda config --set show_channel_urls yes
也可以先安装anaconda2,再搭建python3的环境,取决于你主要用哪个版本的python
2to3 example.py # 提示修改 2to3 -w example.py # 源文件保存成.bak
中国 = 'china' print(中国)
//
2.X: print "The answer is", 2*2 3.X: print("The answer is", 2*2) 2.X: print x, # 使用逗号结尾禁止换行 3.X: print(x, end=" ") # 使用空格代替换行 2.X: print # 输出新行 3.X: print() # 输出新行 2.X: print >>sys.stderr, "fatal error" 3.X: print("fatal error", file=sys.stderr) 2.X: print (x, y) # 输出repr((x, y)) 3.X: print((x, y)) # 不同于print(x, y)!
2.X的方式如下: >>> 0666 438 >>> oct(438) '0666' 3.X这样: >>> 0666 SyntaxError: invalid token (<pyshell#63>, line 1) >>> 0o666 438 >>> oct(438) '0o666'
>>> bin(438) '0b110110110' >>> _438 = '0b110110110' >>> _438 '0b110110110'
>>> class C(object): def __init__(self, a): print('C', a) >>> class D(C): def __init__(self, a): super().__init__(a) # 无参数调用super() >>> D(8) C 8 <__main__.D object at 0x00D7ED90>
class Foo(*bases, **kwds): pass
>>> def foo(cls_a): def print_func(self): print('Hello, world!') cls_a.print = print_func return cls_a >>> @foo class C(object): pass >>> C().print() Hello, world!
>>> b = b'china' >>> type(b) <type 'bytes'> str对象和bytes对象可以使用.encode() (str -> bytes) or .decode() (bytes -> str)方法相互转化。 >>> s = b.decode() >>> s 'china' >>> b1 = s.encode() >>> b1 b'china'
>>> import collections >>> print('\n'.join(dir(collections))) Callable Container Hashable ItemsView Iterable Iterator KeysView Mapping MappingView MutableMapping MutableSequence MutableSet NamedTuple Sequence Set Sized ValuesView __all__ __builtins__ __doc__ __file__ __name__ _abcoll _itemgetter _sys defaultdict deque
>>> try: ... raise NotImplementedError('Error') ... except NotImplementedError, error: ... print error.message ... Error 在Py3.0中: >>> try: raise NotImplementedError('Error') except NotImplementedError as error: #注意这个 as print(str(error)) Error
>>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b.strip(b'\n\t\r \f')和b.split(b' ')来达到相同目的
可以使用hasattr()来替换 callable(). hasattr()的语法如:hasattr(string, '__name__')
__getslice__
系列成员被废弃。a[i:j]根据上下文转换为a.__getitem__(slice(I, j))
或 __setitem__
和 __delitem__
调用
>>> file <type 'file'> 在Py3.X中: >>> file Traceback (most recent call last): File "<pyshell#120>", line 1, in <module> file NameError: name 'file' is not defined