Bash alias –> Python 2.7 to Python 3.3

Question:

I am trying to make Python 3.4.2 the default in Linux (currently it is 2.7.6). I am not very knowledgeable on this stuff, but I have read in several places online that you can simply put an alias in the ~/.bashrc or ~/.bash_aliases file like this:

alias python='python3'

I don’t have either the ~/.bashrc or ~/.bash_aliases file . . . I am assuming you can just create them. I have done that, but the alias doesn’t seem to be working. Am I missing something? Do you need the shebang at the beginning of the file? I have tried it both ways.

Thanks for any help you can give!

Asked By: laurenll

||

Answers:

DON’T DO IT!

Some linux utilities depend on python2.x currently. It will probably break your system if you make that change since python3.x is not backward compatible with python2.x. Unless you are fully aware of the consequences, don’t do it!

Similar question is asked here : https://askubuntu.com/questions/103469/how-do-i-change-my-pythonpath-to-make-3-2-my-default-python-instead-of-2-7-2

Answered By: Seçkin Savaşçı

In a bash file the following will not work:

alias python=’python3′

The alias syntax is not available in sh script execution. In order to execute python commands with bash that work on both python and python3. I wrote a function that checks if python3 or python is available and then pass on the function argument to that local installation of python.

The example code is taken from a script that runs on machines that sometimes do not have python but do have python3 installed.

This code was tested on Ubuntu 18 and 16 (Windows Subsystem Linux 2).

#!/bin/bash
function local_python() {
  _python=$(which python)
  _python3=$(which python3)
  python=${_python3:-_python}
}

curl "http://www.geoplugin.net/json.gp" 
  -X GET 
  -H "Accept: application/json" |
  local_python "import sys, json; print(json.loads(sys.stdin.read())['geoplugin_request'])"

The above code can be copied and pasted into an example.sh file and should (as long as url is available) return with your IP address.

Answered By: Kwuite
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.