Skip to content

Installing new modules in Python

Tags:

Python offers the option of expanding their functionality by installing new packages, something similar to DLLs in Visual Basic. This way, you haved more resources for using within your scripst and software.

In this post I will install two popular packages: NumPy is the fundamental package for scientific computing with Python, and MySQL-Python is a package for working against MySQL databases.

Let’s open a MS-DOS console, and go to the directory that constains Python, in my case c:\python27, for versión 2.7.

First, let’s ckeck inside the scripts directory if we can use easy_install:

Directorio Scripts de Python

Scripts directory on Python

Let’s install pip, another tool that allow the user to install and work with packages, by using easy_install:

Instalando pip

Installing pip

Again, let’s list the files on the scripts directory, and now we can use both, either pip either easy_install:

Instaladores en Python

Instaladores en Python

Let’s install “uncertainties” package for working with standart desviations.

Paquete Uncertainty

Installing Uncertainty

Let’s verify we still cannot use NumPy:

Falta paquete NumPy

Error when importing NumPy

So, let’s install with easy_install:

Instalando NumPy

Installing NumPy

Let’s open a new console, and let’s check again:

NumPy

NumPy

To install MySQLDb, we can execute the command:

pip install mysql-python

Instalando MySQL-Python

Instalando MySQL-Python

But,nothing is installed because we already have it installed (lucky me!!)

Let’s use it in a small script, trying to connect to a MySQL database, and let’s print a few records for one table. Just code something like this (modify the options to your user, password, server and database):

import MySQLdb
db=MySQLdb.connect(host='localhost',user='root',passwd='forever',db='solar_comun')
cursor=db.cursor()
sql='SELECT idparametro, parametro FROM parametros LIMIT 5;'
cursor.execute(sql)
resultado=cursor.fetchall()
for registro in resultado:
print registro[0] , '|' , registro[1]

And the results:

Probando MySQL-Python

Testing MySQL-Python

And that’s it! This is the way (two ways) of adding new packages and modules to Python!

Have a nice day!

Manejando Datos Newsletter

Noticias, entradas, eventos, cursos, … News, entrances, events, courses, …


Gracias por unirte a la newsletter. Thanks for joining the newsletter.