From Ever changing code

Learning Python scratch pad


Virtual environment

needs rewriting [ venv]

The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories.

Install venv, requires python3.3+
python3 -V
sudo apt-get install build-essential libssl-dev libffi-dev python-dev
sudo apt-get install -y python3-pip
sudo apt install python3-venv
python3 -m venv my_env             #create virtual environment
source my_env/bin/activate         #activate env
(my_env) piotr@ubuntu ~/scripts $  #prompt change to acknowledge activated environment

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.

Syntax, semantics and functions


Print in v3 is a function, it uses arguments with variables like below:

%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)


print("%s is %d years old." % (name, age))

Simple HTTP Server

It provides the local files browser over http protocol and access logs

sudo python  -m SimpleHTTPServer 80 #python 2
sudo python3 -m http.server      80 #python 3

Install Selenium lib on Ubuntu

$ which python python3
sudo apt-get install python3-pip        # install pip for python3
sudo python3 -m pip install -U selenium # install selenium for python3
sudo python3 -m pip install -U pip      # upgrade pip

Install geckodriver on Ubuntu

It's required if you use Selenium in Python, webdriver function:

default_browser = webdriver.Firefox()


## Geckodriver (verified on Ubuntu 16.04 running on Vagrant)
sudo sh -c 'tar -x geckodriver -zf geckodriver-v0.21.0-linux64.tar.gz -O > /usr/bin/geckodriver'
sudo chmod +x /usr/bin/geckodriver
rm geckodriver-v0.21.0-linux64.tar.gz

## Chromedriver
sudo chmod +x chromedriver
sudo mv chromedriver /usr/bin/

Selenium - Website automation test to mimic human interaction - page login

Script below demonstrate usage of Selenium automation through Mozilla Geckodriver. It will open Firefox, navigate to a give URL, fill in a form, click a login button and take a screenshot.

Credentials file

cat creds.yaml
wpUser: user
wpPass: pass123

Main script

from selenium import webdriver
import yaml
driver = webdriver.Firefox()
creds = yaml.safe_load(open('creds.yaml','r'))

user_field = driver.find_element_by_name("wpName")
pass_field = driver.find_element_by_name("wpPassword")
# find login button and click on it