简体   繁体   中英

Problem with changing python statement with python3 in macOS Catalina

By default when I type python in terminal it goes to python using the 2.7.x version. In oldest versions of macOS once I typed 'alias pyhton=python3' it changed forever and every time I typed python it goes to python version 3. But in macOS Catalina, I need to type the statement every time I open the terminal. Any suggestion?

First up, confirm what your default "python" links to, so you can reference it, and ensure that which and the shell agree:

user:~> which python
/usr/bin/python
user:~> type python
python is /usr/bin/python
user:~> ls -la /usr/bin/python
lrwxrwxrwx 1 root root 7 Oct  8 13:26 /usr/bin/python -> python2

Now you can either add an alias to override this in your shell... .

Open your ~/.bash_profile file for bash or ~/.zshrc file for zsh ( look here for historical reasons behind the files used ) as suggested by shahaf, and add a line with the alias — for example, quick method:

echo "alias python=/usr/bin/python3" >> ~/.bash_profile
echo "alias python=/usr/bin/python3" >> ~/.zshrc

The new alias will be set for the next shell you start, or, open a new Terminal window and source the profile file to make it active. Eg. in bash:

source ~/.bash_profile

Or, change the symlink to point by default to python3, and remember the change (I use a simple toggle script, else any install of a missing python2 package can result in complaints about the configure script, which uses the python symlink directly):

#!/bin/bash
TOGGLE=$HOME/.python3Active
if [ ! -e $TOGGLE ]; then
        touch $TOGGLE
        sudo ln -fs python3 /usr/bin/python
        ls -la /usr/bin/python
        echo "Press any key to continue..."
        read
else
        rm $TOGGLE
        sudo ln -fs python2 /usr/bin/python
        ls -la /usr/bin/python
        echo "Press any key to continue..."
        read
fi

Catalina now uses zsh as the default rather than Bash.

To verify which shell you are using type echo $0 in the terminal

Add alias python='python3' to $HOME/.zshrc

you will have to edit the terminal's profile file, usually reside under ~/.profile

add the alias line there, this files get loaded when a terminal session is started and export environment variables and methods so they will be accessible in that session

I suggest to use a more robust and powerful terminal enhancement like Z-Shell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM