Posts Tagged Under: 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 – 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 – 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 – 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


Python – The Standard Library

Python comes with a large number of builtin functions. However these alone only provides a limited functionality of python. The true power of python comes from the python’s standard library.

Python comes included with an extensive library of modules. modules extends python’s features, in the same way as installing an app on smart phone, will extend what the smart phone can do. However unlike smart phone which requires downloading followed by installing and activating, you don’t need to download python modules since they are already in the standard library which comes with python as standard. The only thing you need to do is activate the modules you want to using in your current python session, or inside your python script.

You use the “import” keyword to activate/access a module, like


Python – Data Types

Python comes with the following built-in data types:

 

  1. integer
  2. floating points
  3. null object
  4. boolean (true/false)

You can find the type of variable using the “type()” builtin function:

=>=>=> x = 10
=>=>=> type(x)
<class 'int'=>
=>=>=> y = 10.2345
=>=>=> type(y)
<class 'float'=>
=>=>=> z = "hello world"
=>=>=> type(z)
<class 'str'=>
=>=>=>

As you can, python automatically recognised that automatically assigns a type, after it evaluates it.