Tutorial

How To Install Python 3 and Set Up a Local Programming Environment on Ubuntu 16.04

How To Install Python 3 and Set Up a Local Programming Environment on Ubuntu 16.04
Not using Ubuntu 16.04?Choose a different version or distribution.
Ubuntu 16.04

Introduction

This tutorial will get you up and running with a local Python 3 programming environment in Ubuntu 16.04.

Python is a versatile programming language that can be used for many different programming projects. First published in 1991 with a name inspired by the British comedy group Monty Python, the development team wanted to make Python a language that was fun to use. Easy to set up, and written in a relatively straightforward style with immediate feedback on errors, Python is a great choice for beginners and experienced developers alike. Python 3 is the most current version of the language and is considered to be the future of Python.

This tutorial will guide you through installing Python 3 on your local Linux machine and setting up a programming environment via the command line. This tutorial will explicitly cover the installation procedures for Ubuntu 16.04, but the general principles apply to any other distribution of Debian Linux.

Prerequisites

You will need a computer with Ubuntu 16.04 installed, as well as have administrative access to that machine and an internet connection.

Step 1 — Setting Up Python 3

We’ll be completing our installation and setup on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well. The command line, also known as a shell, can help you modify and automate many of the tasks you do on a computer every day, and is an essential tool for software developers. There are many terminal commands to learn that can enable you to do more powerful things. The article “[An Introduction to the Linux Terminal] (https://www.digitalocean.com/community/tutorials/an-introduction-to-the-linux-terminal)” can get you better oriented with the terminal.

On Ubuntu 16.04, you can find the Terminal application by clicking on the Ubuntu icon in the upper-left hand corner of your screen and typing “terminal” into the search bar. Click on the Terminal application icon to open it. Alternatively, you can hit the CTRL, ALT, and T keys on your keyboard at the same time to open the Terminal application automatically.

Ubuntu Terminal

Ubuntu 16.04 ships with both Python 3 and Python 2 pre-installed. To make sure that our versions are up-to-date, let’s update and upgrade the system with apt-get:

  1. sudo apt-get update
  2. sudo apt-get -y upgrade

The -y flag will confirm that we are agreeing for all items to be installed, but depending on your version of Linux, you may need to confirm additional prompts as your system updates and upgrades.

Once the process is complete, we can check the version of Python 3 that is installed in the system by typing:

  1. python3 -V

You will receive output in the terminal window that will let you know the version number. The version number may vary, but it will look similar to this:

Output
Python 3.5.2

To manage software packages for Python, let’s install pip:

  1. sudo apt-get install -y python3-pip

A tool for use with Python, pip installs and manages programming packages we may want to use in our development projects. You can install Python packages by typing:

  1. pip3 install package_name

Here, package_name can refer to any Python package or library, such as Django for web development or NumPy for scientific computing. So if you would like to install NumPy, you can do so with the command pip3 install numpy.

There are a few more packages and development tools to install to ensure that we have a robust set-up for our programming environment:

  1. sudo apt-get install build-essential libssl-dev libffi-dev python-dev

Once Python is set up, and pip and other tools are installed, we can set up a virtual environment for our development projects.

Step 2 — Setting Up a Virtual Environment

Virtual environments enable you to have an isolated space on your computer for Python projects, ensuring that each of your projects can have its own set of dependencies that won’t disrupt any of your other projects.

Setting up a programming environment provides us with greater control over our Python projects and over how different versions of packages are handled. This is especially important when working with third-party packages.

You can set up as many Python programming environments as you want. Each environment is basically a directory or folder in your computer that has a few scripts in it to make it act as an environment.

We need to first install the venv module, part of the standard Python 3 library, so that we can create virtual environments. Let’s install venv by typing:

  1. sudo apt-get install -y python3-venv

With this installed, we are ready to create environments. Let’s choose which directory we would like to put our Python programming environments in, or we can create a new directory with mkdir, as in:

  1. mkdir environments
  2. cd environments

Once you are in the directory where you would like the environments to live, you can create an environment by running the following command:

  1. python3 -m venv my_env

Essentially, this sets up a new directory that contains a few items which we can view with the ls command:

  1. ls my_env
Output
bin include lib lib64 pyvenv.cfg share

Together, these files work to make sure that your projects are isolated from the broader context of your local machine, so that system files and project files don’t mix. This is good practice for version control and to ensure that each of your projects has access to the particular packages that it needs. Python Wheels, a built-package format for Python that can speed up your software production by reducing the number of times you need to compile, will be in the Ubuntu 16.04 share directory.

To use this environment, you need to activate it, which you can do by typing the following command that calls the activate script:

  1. source my_env/bin/activate

Your prompt will now be prefixed with the name of your environment, in this case it is called my_env. Your prefix may look somewhat different, but the name of your environment in parentheses should be the first thing you see on your line:

This prefix lets us know that the environment my_env is currently active, meaning that when we create programs here they will use only this particular environment’s settings and packages.

Note: Within the virtual environment, you can use the command python instead of python3, and pip instead of pip3 if you would prefer. If you use Python 3 on your machine outside of an environment, you will need to use the python3 and pip3 commands exclusively.

After following these steps, your virtual environment is ready to use.

Step 3 — Creating a Simple Program

Now that we have our virtual environment set up, let’s create a simple “Hello, World!” program. This will make sure that our environment is working and gives us the opportunity to become more familiar with Python if we aren’t already.

To do this, we’ll open up a command-line text editor such as nano and create a new file:

  1. nano hello.py

Once the text file opens up in the terminal window we’ll type out our program:

print("Hello, World!")

Exit nano by typing the control and x keys, and when prompted to save the file press y.

Once you exit out of nano and return to your shell, let’s run the program:

  1. python hello.py

The hello.py program that you just created should cause your terminal to produce the following output:

Output
Hello, World!

To leave the environment, simply type the command deactivate and you will return to your original directory.

Conclusion

Congratulations! At this point you have a Python 3 programming environment set up on your local Ubuntu machine and can begin a coding project!

To set up Python 3 on another computer, follow the local programming environment guides for Debian 8, CentOS 7, Windows 10, or macOS. You can also read about installing Python and setting up a programming environment on an Ubuntu 16.04 server, which is especially useful when working on development teams.

With your local machine ready for software development, you can continue to learn more about coding in Python by following “Understanding Data Types in Python 3” and “How To Use Variables in Python 3”.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
17 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Another flawless victory. Can you tell I’m on a roll setting up Python environments? ;)

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
September 1, 2016

Awesome!

Heads up! The step where you install additional development tools…

sudo apt-get install build-essential libssl-dev libffi-dev python-dev

… will make python 2.7 as your default python setup, instead of python 3, so the following python 3 packages installation will fail.

I’ve omitted this step, but I don’t know exactly if it is recommended the installation of any other extra development tools to have a solid environment. Do you recommend any?

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
January 12, 2017

Hi there, that line was added based on feedback received from dependency requirements for other Python tutorials. You could alternately use python3-dev.

That said, you don’t need the line to install Python, and since this tutorial sets up a Python 3 programming environment it won’t affect how Python 3 works when you’re in the active environment you’ve set up.

How can I connect a mysql database to this as well?

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
January 17, 2017

thanks, the second link done it!

Hi,

Thank you for this. Should I be seeing GNU nano 2.7.3 when I enter the text screen? Shouldn’t it show 3.5.0 or something along those lines?

Also, is downloading and running python in this way different from downloading the package from the python website and installing through the terminal or synaptic? Sorry…I am very much a noob.

Thanks again!

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
January 19, 2017

Thanks for reading :)

The GNU nano 2.7.3 you see at the top of the screen when you’re in the text editor refers to the version of nano you have installed, not the version of Python. You can learn more about the nano text editor from the GNU nano homepage.

The choice behind using a teminal-based installation can be a personal choice, but in the long-run it is worthwhile as a developer to become proficient in using the terminal as it gives you greater control over your environments and set ups, and makes it more straightforward to move to production on servers.

Excited to see what projects you come up with, happy coding!

Great Tutorial! Thanks!

The following command fails for me though:

$ sudo apt-get install -y python3-venv
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python3-venv

Just for reference, here is my info:

$ uname -a
Linux OPONE 3.4.0+ #1 PREEMPT Thu Aug 1 17:06:05 CST 2013 x86_64 x86_64 x86_64 GNU/Linux
Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
February 28, 2017

You may be having an issue because you are on version 3.4.0, would it be possible for you to use 4.4.0?

Thank you so much! the instructions are very clear and logical! I solved my problem within minutes!

I’ve having an issue with Python3 on my Ubuntu 16.04 droplet. It’s set up to be used with shiny (and a shiny server), and of course, python3.5 is already installed. I’m having an issue with getting python3.5 to connect to the internet in scripts. I’m thinking that’s an issue with requests or some other package, but I don’t have any clue where to begin.

When I run the scripts, they get ‘stuck’ - they just won’t access the internet. If I manually end them, I get the following code:

 File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connectionpool.py", line 379, in _make_request
    httplib_response = conn.getresponse(buffering=True)
TypeError: getresponse() got an unexpected keyword argument 'buffering'



During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "nba_rookie_stats.py", line 38, in <module>
    x = req.get(url,headers=_HTTP_HEADERS)
  File "/usr/local/lib/python3.5/dist-packages/requests/api.py", line 70, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/requests/api.py", line 56, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 488, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 630, in send
    history = [resp for resp in gen] if allow_redirects else []
  File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 630, in <listcomp>
    history = [resp for resp in gen] if allow_redirects else []
  File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 190, in resolve_redirects
    **adapter_kwargs
  File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 609, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/requests/adapters.py", line 423, in send
    timeout=timeout
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connectionpool.py", line 382, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/lib/python3.5/http/client.py", line 1197, in getresponse
    response.begin()
  File "/usr/lib/python3.5/http/client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.5/http/client.py", line 258, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.5/socket.py", line 575, in readinto
    return self._sock.recv_into(b)

My guess is there is some kind of issue with the ip/server configuration, but I’m not sure exactly where to start with testing this.

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
April 13, 2017

You may want to take a look at the Shiny Server documentation. Perhaps you should be using a version of Python 2 instead of Python 3 for this use case.

Thank you so much. Very helpfull !! (<8|

Works like a charm! Thank you so much!

Thanks , practical post…

I got this error (solution maybe useful for others):

jimmy@KEVIN:~/environments$ python3 -m venv my_env Error: Command ‘[’/home/jimmy/environments/my_env/bin/python3’, ‘-Im’, ‘ensurepip’, ‘–upgrade’, ‘–default-pip’]’ returned non-zero exit status 1.

(This error come from a “broken pyvenv”)

Solution:

python3 -m venv --without-pip my_env

and after, get pip:

source my_env/bin/activate curl https://bootstrap.pypa.io/get-pip.py | python deactivate source my_env/bin/activate

Full solution, please read this: https://stackoverflow.com/questions/26215790/venv-doesnt-create-activate-script-python3

Thanks for this amazing article, congrats!

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
November 24, 2017

Thank you for sharing your solution. I was not able to replicate the error, I would check if you are using a different version of Ubuntu, and ensure that prerequisite updates and upgrades are run before completing this tutorial. At the time of writing, Python 3.5.2 is still the version currently pre-installed with Ubuntu 16.04

Thanks for your help! Please, don’t worry, my mistake!

I want share my solution (with all due respect and if the DigitalOcean’s moderators let it)

I was thinking and thinking, a lot of people have this problem too: https://stackoverflow.com/questions/26215790/venv-doesnt-create-activate-script-python3 https://github.com/ContinuumIO/anaconda-issues/issues/6917 https://github.com/ContinuumIO/anaconda-issues/issues/952 https://askubuntu.com/questions/879437/ensurepip-is-disabled-in-debian-ubuntu-for-the-system-python

Even include a long formal bug! : https://bugs.launchpad.net/ubuntu/+source/python3.4/+bug/1290847?comments=all

Reading and reading I found this: «Conda manages python itself as a package, so that conda update python is possible, in contrast to pip, which only manages Python packages. Conda is available in Anaconda and Miniconda (an easy-to-install download with just Python and conda).» «CONDA MANAGES PYTHON ITSELF AS A PACKAGE…» very disturbing for me but well, hands to the keyboard in a terminal window:

jimmy@KEVIN:~$ conda update python
Fetching package metadata ...........
Solving package specifications: .

Package plan for installation in environment /home/jimmy/miniconda3:

The following packages will be UPDATED:

    conda:   4.3.29-py36ha26b0c0_0 --> 4.3.30-py36h5d9f9f4_0
    openssl: 1.0.2l-h9d1a558_3     --> 1.0.2m-h26d622b_1    
    python:  3.6.2-hdfe5801_15     --> 3.6.3-h6c0c0dc_5     

Proceed ([y]/n)? y

openssl-1.0.2m 100% |################################| Time: 0:00:04 828.45 kB/s
python-3.6.3-h 100% |################################| Time: 0:00:35 857.86 kB/s
conda-4.3.30-p 100% |################################| Time: 0:00:00 923.76 kB/s
jimmy@KEVIN:~$ python -m ensurepip
Requirement already satisfied: setuptools in ./miniconda3/lib/python3.6/site-packages
Requirement already satisfied: pip in ./miniconda3/lib/python3.6/site-packages
jimmy@KEVIN:~$ python -m ensurepip --user
Requirement already satisfied: setuptools in ./miniconda3/lib/python3.6/site-packages
Requirement already satisfied: pip in ./miniconda3/lib/python3.6/site-packages
jimmy@KEVIN:~$ python3 -m venv my_env
jimmy@KEVIN:~$ source my_env/bin/activate
(my_env) jimmy@KEVIN:~$ ^C
(my_env) jimmy@KEVIN:~$ 

Problem solved, thanks for your attention!

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
November 27, 2017

Glad that you got everything working! For more guidance on working with Anaconda, you can read our tutorial on How To Install the Anaconda Python Distribution on Ubuntu 16.04

Thanks for the article. One hiccup that I’ve searched endlessly for…

I can’t replicate making a virtualenv without sudo:

Error: [Errno 13] Permission denied:```

This makes it so when I'm in the virtualenv I can't add packages without sudo, which using sudo adds the packages to the global environment and not the virtual one.  Any thoughts?
Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
December 20, 2017

I just fully tested the tutorial on a clean Ubuntu 16.04 server and can’t replicate your issue. I would try a new installation and ensure that everything is up to date.

Thanks, was it with a non-root user with sudo privileges?

“as well as have administrative access to that machine”

Seeing if I need to change privileges or not

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
December 22, 2017

Yes, any user with sudo privileges should be able to follow the tutorial. Hope that that helps.

Thank you very much for the tutorial, it works great! I just had an issue on a fresh Ubuntu Server 16.04.3 LTS installation when I tried to create the virtualenv with:

$ sudo python3 -m venv django_tuts

and got the following output:

The virtual environment was not created successfully because ensurepip is not
available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.

    apt-get install python3-venv

You may need to use sudo with that command.  After installing the python3-venv
package, recreate your virtual environment.

Failing command: ['/home/raffaele/virtualenvs/django_tuts/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']

My python3-venv package was already installed so I managed to solve with:

$ sudo apt-get install python-virtualenv

Hope this might help somebody, thanks again for the tutorial …now I can install django on my brand new virtualenv! :]

Another method id to use virtualenv. sudo pip3 install virtualenv will install it.Here is a blog explain the full setup with video tutorial.Click here

WOW! This is amazing! Worked like a charm! Thank you!

The "nano hello.py is not working for me

Lisa Tagliaferri
DigitalOcean Employee
DigitalOcean Employee badge
June 26, 2018

Hi there, if you’re using Ubuntu, you should have nano already installed. If not, you can install it via terminal with the following command:

  1. sudo apt-get install nano

If you’re using an operating system other than Ubuntu, you should choose the correct distribution from our How To Install Python 3 series.

You can also download nano via the GNU nano official website. Or, you can use an alternate text editor of your choice to create the hello.py file.

Thank you so much! I’ve read a lot of articles before this, and only this one was helpful, great work! So appreciate it.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.