Python - Working with Libraries and Virtual Environment

What are Libraries and How to Use them

Python Libraries (Modules, Applications, etc.)

• Any Python code outside of your script you want to use
• Provide some capability or data you need
• Included with statements
• Example on using datetime library:

# Syntax
from <library> import <name>

import <library>

Where to Get Libraries

• Write them yourself
◇ Example: common_vars
• Included with Python itself
◇ Example: datetime, os, sys, json
• From Python Package Index (PyPI)
◇ Example: pip install requests
• Download and install manually
◇ Example: ACI ToolKit from Github


Using pip to Install Libraries

Working with Libraries


Virtual Environments

What is a Virtual Environment (venv)?

• Build isolated, fully functional Python environments on a single workstation
• Virtual environment can
◇ Run different version of Python
◇ Have different libraries installed
◇ Have different version of libraries installed

Setting up a VIrtual Environment

Environment setup


Foundational Libraries

# Pretty Print
from pprint import pprint

# Python Interpreter Utilities
import sys

# Operating System Interfaces
import os

# Date and Time libraries
import datetime

• Library: Pretty Print
◇ Better formatting than default print() function
◇ For example, print each list element on a single line

from pprint import pprint
from common_vars import *


• Library: sys
◇ Access to some details / variables concerning running state

import sys

# Access command line argument

# Exit Python with specific error message

• Library: os
◇ Access and manipulate directories and files
▪ Note: Opening file can be done with open(filename)
◇ Access and manipulate environment variables

import os

os.getcwd()             # pwd
os.chdir('../')         # cd

# echo $USER

# Set environment variable
os.environ["VAR_FROM_PYTHON"] = "Set from Python"

• Library: datetime
◇ Create, format and manipulate dates and times
◇ Time arithmetic!
◇ Work with timestamps and other representations

import datetime

right_now =

four_weeks_from_now = right_now + datetime.timedelta(weeks=4)

date_display_format = "%T % %n %p on %d %m, %Y"




Search for Packages