Setting up Python and Virtual Environments in Visual Studio Code on Ubuntu

Hello World,

I’m writing this article because believe it or not, this process is a pain in the neck and not completely documented in any one place. Lets start with why in the world you would want to do this. For me, I want to use Tensor Flow and NVidia embedded robotics SDKs. Unfortunately the only supported dev environment for this is Ubuntu. Not anything against Ubuntu it just appears to be fairly unstable in comparison to Mac and Windows, but that is neither here nor there, if you want to build intelligent robots, you need these tools.

Installing Ubuntu

There is a bit of a trick to this.  I managed to put my machine into a non-recoverable state 3 times doing this.  You need to follow these steps and these steps exactly.

  1. Go to the Ubuntu website and download the Ubuntu image file for Ubuntu 16.04 LTS.
  2. Download Rufus and create a bootable USB stick.  Instructions here.
  3. Boot your machine from USB, usually restarting and holding f-12 does the trick.
  4. Here is where it gets a bit tricky.  The instructions found here are fine.  The only caveat is when they say they “recommend” you connect your machine to the Internet to install updates, what they mean is that if you don’t, you are completely screwed.  You had better ensure that checkbox is checked.
    1. download-desktop-install-ubuntu-desktop_2
  5. The rest of the instructions are fine, you will get Ubuntu to come up nice and happy.  But we aren’t done yet.  Use the Search Functionality to search your box and find the “Updater”.  You will find several updates available.  You should install these updates next.  Failing to do so will cause issues.
  6. The Ubuntu Software App is evil.  Do not install the OS updates before this step.  If you do, your box will be non-recoverable.  I haven’t even tried to install the O.S.  updates to this point, so if you do, let me know if it destroys your box or works.  At this point, your box is updated enough to install a few tools, but for some reason not Chrome still.

Installing Visual Studio Code

This is stupid easy, just download and follow the instructions from here.  You will download the .deb file and use the Software App to install it.  Don’t worry, it all works fine.

Basic Python Setup in VS Code

This section will get you up and running so you have intellisense, debugging etc against the global python version.

  1. The first thing to do here is to install the Python extensions in visual studio code.
    1. Press Ctrl + P inside Visual Studio Code to bring up the command window.
    2. Type: “ext install Python”.
  2. Next is to set up tasks so you can quickly run tests and the current code file.  These instructions are great.
  3. The only thing you need to do different, is is to specify the global python version you wish to use; “Python3” or “Python3.5” if you wish to not use Python 2.7.

What are Virtual Environments?

In Python, this is a way to keep your project dependencies separate.  This is crucial in ensuring that there are no global package conflicts, such as one project relying on v1 of numpy and another requiring v2 of numpy.  This can create issues when managing and deploying your projects.  In this example, I have created a “global” TensorFlow environment.  I recommend that you create a virtual environment inside the directory your project exists for specific projects, and global environments are good for experimentation and bootstrapping various projects.

Creating a Virtual Environment & Install Numpy

 

  1. Start by opening a command terminal.
  2. Ensure virtual environments & pip are installed
    1. sudo apt install python3-venv
      sudo apt install python-pip
  3. Navigate to your target directory and create a new environments folder.
    1. cd projects
      mkdir python-virtual-environments
      cd python-virtual-environments
      
  4. Once inside the virtual environments folder, create a new virtual environment and activate it.
    1. pyvenv tfenv
      cd tfenv
      ./bin source activate
  5. You should see (tfenv) precede the machine name in the terminal window.
  6. Install a package.  We will do numpy for example.
    1. pip3.5 install numpy
  7. To verify the package has installed do the following
    1. cd bin/lib/pythong3.5/site-packages
      ls
  8. You should now see output indicating numpy is in the current directory.

Using Virtual Environments in Visual Studio Code

You need to do this on a project by project basis.  In fact, I sort of like this type of setup as opposed to a drop down.  If I have many projects I am maintaining and developing, it can get cluttered.  This sets up an environment in a project by project basis.  There are 3 files you need.  Launch.json (for debugging), Settings.json (for development) and Task.json (for auto build).

Settings.json

{
    "python.pythonPath": "/home/drcrook/projects/python-virtual-environments/tfenv/bin/python3.5",
    "python.autoComplete.extraPaths": [
        "/home/drcrook/projects/python-virtual-environments/tfenv/lib/python3.5",
        "/home/drcrook/projects/python-virtual-environments/tfenv/lib/python3.5/site-packages"
    ]
}

Basically you just need to point the python path to the fully qualified path of the python you wish to use.  Since we are using virtual environments, just use the one from the virtual environment path you created.  Notice also the autoComplete paths.

Launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            	"name": "Launch",
                "type": "python",
                "request": "launch",
                "stopOnEntry": false,
                "program": "${workspaceRoot}/.vscode/HelloWorld.py",
                "pythonPath": "/home/drcrook/projects/python-virtual-environments/tfenv/bin/python3.5",
                "debugOptions": [
                    "WaitOnAbnormalExit",
                    "WaitOnNormalExit",
                    "RedirectOutput"
                ]  
        }
    ]
}

Again, just specify the fully qualified path of the python version in your virtual environment.  I am pointing to HelloWorld.py here, but you can alternatively use ${file} for the currently focused file.

Task.json

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "/home/drcrook/projects/python-virtual-environments/tfenv/bin/python3.5",
    "isShellCommand": true,
    "args": ["${file}"],
    "showOutput": "always"
}

Again, just notice, fully qualified path to the python version in the virtual environment.  Notice we use ${file}, you could replace this with the actual file similar to Launch.json.

Testing The Setup

So now lets just test the setup.  Create a new file “HelloWorld.py”.  Put this code into it to ensure numpy was picked up.

# ctrl + Shift + B will run the file.
print("hello world")

#Test Importing Numpy
import numpy as np
 
#define a vector size 4
a = np.array([1,2,3,4])
 
#define a 2x4 matrix
b = np.array([[ 1, 2, 3, 9], 
              [ 4, 5, 6, 9]])

print( a.dot(b.transpose()) ) 

Go ahead, set break points, ctrl+shift+b, execute debugging etc.  Notice it works and gives you a print out of “hello world” as well as the 1×2 matrix [50 68] by having multiplied axb’.

Summary

Alright, there you have it.  Now you have a nice solid light-weight python development environment.  Now go crazy and build some cool shit.  I will be working on autonomous vehicles in my spare time using Tensor Flow and NVidia’s dev kits, so keep an eye out for that.

 

3 thoughts on “Setting up Python and Virtual Environments in Visual Studio Code on Ubuntu

  1. Pingback: Becoming a Functional Data Scientist | DaCrook

    • Can you add the error messages you are seeing? I tested on Ubuntu 16.04 though I doubt that makes much difference. It is likely a matter of the django dependencies not being installed into your virtual environment if I were to guess blindly.

Leave a Reply

Your email address will not be published. Required fields are marked *