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: example1.py
# 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
• 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
• 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 *
pprint(books)
• Library: sys ◇ Access to some details / variables concerning running state
import sys
# Access command line argument sys-argv[1]
# Exit Python with specific error message sys.exit("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 os.getcwd()
# echo $USER os.environ["USER"]
# Set environment variable os.environ["VAR_FROM_PYTHON"] = "Set from Python" os.environ["VAR_FROM_PYTHON"]
• Library: datetime ◇ Create, format and manipulate dates and times ◇ Time arithmetic! ◇ Work with timestamps and other representations