Conda python=2环境使用python 3



我安装了Miniconda3(默认为Python 3(,并使用conda创建了Python 2虚拟环境:

~$ conda create -n myenv python=2
...
~$ source activate myenv
(myenv) ~$ conda list
# packages in environment at ~/miniconda3/envs/myenv:
#
# Name                    Version                   Build  Channel
ca-certificates           2018.03.07                    0  
certifi                   2018.10.15               py27_0  
libedit                   3.1.20170329         h6b74fdf_2  
libffi                    3.2.1                hd88cf55_4  
libgcc-ng                 8.2.0                hdf63c60_1  
libstdcxx-ng              8.2.0                hdf63c60_1  
ncurses                   6.1                  he6710b0_1  
openssl                   1.1.1a               h7b6447c_0  
pip                       18.1                     py27_0  
python                    2.7.15               h9bab390_4  
readline                  7.0                  h7b6447c_5  
setuptools                40.6.2                   py27_0  
sqlite                    3.25.3               h7b6447c_0  
tk                        8.6.8                hbc83047_0  
wheel                     0.32.3                   py27_0  
zlib                      1.2.11               h7b6447c_3  

然而,如果我尝试运行Python,它会使用Python3:

(myenv) ~$ python
Python 3.7.1 (default, Oct 23 2018, 19:19:42) 
[GCC 7.3.0] :: Anaconda, Inc. on linux

如果我尝试在环境中使用Python 2代码运行脚本,也会发生同样的情况。

(myenv) ~$ python hello2.py
File "hello2.py", line 1
print "Hello World in Python 2"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello World in Python 2")?

我试着删除并重新创建环境,但没有什么不同。为什么会发生这种情况?

附录

评论中要求的附加信息:

(myenv) ~$ which python
~/miniconda3/envs/myenv/bin/python
(myenv) ~$ ls ~/miniconda3/envs/myenv/bin/python -l
lrwxrwxrwx 1 user user 9 Dec  3 22:43 ~/miniconda3/envs/myenv/bin/python -> python2.7
(myenv) ~$ echo $PATH
~/miniconda3/envs/myenv/bin:~/miniconda3/bin:[rest of usual PATH]
(myenv) ~$ alias
[...]
alias python='python3'

问题在于别名:

alias python='python3'

这个别名将设置在您的shell启动脚本中的某个位置。如果使用bash,则为.bashrc.bash_profile.profile。找到它并将其移除。

别名扩展优先于PATH查找(首先进行别名扩展(。如果您找不到别名的设置位置,您可以在.bashrc(或.profile,或两者兼有(中显式取消别名python:

unalias python

在任何情况下,当您想运行Python时,都可以通过引用Python令牌来避免使用别名:

python hello2.py

最新更新