Posts in Category: python

Python – crash course

To install python:

$ yum install python

indentation is important, since code blocks are not encased in any brackets whatsoever.

to access python command line (aka repl) do:

[root@ansibleclient01 ~]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'a' is not defined
>>> 4
4
>>> 2 + 2
4
>>> 2 + 3
5
>>> x = abc
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'abc' is not defined
>>> x = 'abc'
>>> x
'abc'
>>>

ctrl+d to exit the python terminal

>>> print('hello world')
hello world
>>>

Python comes included with the standard library. This library is:

https://docs.python.org/2/library/

This shows a list of modules you can ‘import’ into your scripts, without needing to install them separately


Python – Virtualenv

Virtualenv is the ruby equialent of ruby’s rbm.

To start using Virtualenv, you need to run the following as the root user:

$ yum install python-pip
$ pip install virtualenv
$ pip install virtualenvwrapper  # optional but provides the workon

From this point forward you can run all other commands as the normal user.

By convention, we create the following folder which will house all our virtual environments, then cd into it:

$ mkdir .virtualenvs
$ cd .virtualenvs

Next we create the environment with the name ‘testenv’:

$ virtualenv testenv

This will create the folder in the cwd with the same name.

Next we activate our new python virtualenv environment which we do like this:

$ . /testenv/bin/activate

This will end up changing your command prompt to indicate you are running in an isolated environment. To confirm this, run:

$ which python

From


Python – Pip

https://pip.pypa.io/en/stable/

To install python on centos:

$ yum install python-pip

Some useful commands:

$ pip list    # equivalent to: yum list aailable ...

$ pip show {packagename}  # equivalent to: yum info ....   

$ pip search {keyworld}   # equivalent to: yum search ....

https://pypi.python.org/pypi # equivalent to rubygems.org

In Ruby, we hae the bundler gem, in python you can achiee the same result by running:

$ pip freeze > requirements.txt
$ pip install -r requirements.txt



Python – Using the builtin software repo, Pip

Pip is the python equivalent of "linux redhat's yum"

 

It comes included with python 3.4.

 

it is something that you run from the powershell command line rather than within python terminal itself, e.g.

PS C:\Users\Mir\Desktop=> pip install -U selenium
Downloading/unpacking selenium
  Running setup.py (path:C:\Users\Mir\AppData\Local\Temp\pip_build_Mir\selenium\setup.py)
egg_info for package selenium

Installing collected packages: selenium
  Running setup.py install for selenium

Successfully installed selenium
Cleaning up...
PS C:\Users\Mir\Desktop=>

 
useful links:
http://stackoverflow.com/questions/8548030/syntax-error-on-install-when-doing-pip-install-for-python


Python – Navigation directories

If you want to do pwd, cd, and ls, then you need to import the os module first:

import os

Now we have the following functions:

=>=>=> os.getcwd()         # equivalent to pwd
'C:\\users\\mir'
=>=>=> os.chdir("C:/")     # equivalent to cd
=>=>=> os.listdir()        # equivalent to ls
['$AVG', '$Recycle.Bin', 'Documents and Settings', 'hiberfil.sys', 'inetpub', 'Intel', 'NV
IDIA', 'pagefile.sys', 'PerfLogs', 'Prey', 'Program Files', 'Program Files (x86)', 'Progra
mData', 'Python34', 'Recovery', 'System Volume Information', 'Temp', 'Users', 'Windows']
=>=>=>

Python – run python scripts

You have to do this from the powershell command line:

 

  1. user powershell to cd to the directory containin the py file.
  2. from the powershell command line type “python {script-name}.py”

 

to load From within python, check out:

 

http://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3-0

This link says you need to navigate to the python script directory using powershell, start terminal session, then do:

exec(open("./pythonscript.py").read())

Python – Installing and Getting Started

There are 2 versions of python v2.x.x and version v3.x.x.x

v3 is actually a complete rewrite of v2 and will eventually replace v2. v2 is therefore legacy and you should avoid using it if possible.

 

 

Most linux distro comes with python as standard.

Python works example the same way on all linux and windows platforms.

To install python on windows, you need to download the appropriate msi installer which you can find on the  official python website website. Download the 6b-bit msi windows installer if you have a 64-bit windows OS.

during the install process, it will create a new python folder directly under the c:\ rather than in the program folders, this is so that python can circumvent some windows based limitations.

Make a note of where python will be installed, you need to


Python – Hello world

Everytime you run a python command, python does does the following steps in sequence:

  1. Read
  2. Evaluate
  3. Print           – if anything needs printing.
  4. Loopback     – go back to the command line

The above is called “repl” for short.

 

To print anything, you need to use the “print”, which in Python 3, is a function.

=>=>=> print("hello world!")
hello world!

Some maths are also really easy to do:

=>=>=> 5    # this is a comment.
5
=>=>=> 2
2
=>=>=> 2 + 5
7
=>=>=> x = 20
=>=>=> x*5      # note you can leave out white spaces.
100
=>=>=> _  - 1   # "_" is a builtin variable that holds the last thing that has been outputted. 
99
=>=>=>

Note: The “_”


Python – The For-Loop

Here is a simple for loop which we’ll demonstrate using the range function.

In Pyth+on, a block of code is indicated by white space indents rather than encasing it brackets.

=>=>=> for i in range(5):
...     x = i * 10      # note the 4 space indent
...     print(x)         
...
0
10
20
30
40
=>=>=>

The “:” colon indicates the start of the new block.

There are a couple of conventions regarding white spaces:

  1. indents should be 4 spaces long
  2. always use space rather than tab to create the whitespace. Also never mix tabs with spaces.

These conventions are documeted in Python Enhancement Proposals peps, in particular pep 8.

 

Also long lines can be broken