python in liunx

          Installing Python-3 ,Running the Python interactive-console,Passing arguments to a script

 Installing python-3 in centos-6 in Traditional Way and using yum
Before this just add an EPEL repo to your cent-os yum list.
Traditional way


# yum install gcc  --> Its a just dependency package
Down load here
# cd /usr/src
# wget https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tgz

Now extract the downloaded package.

# tar xzf Python-3.4.3.tgz

# cd Python-3.4.3
# ./configure
# make altinstall

make altinstall is used to prevent replacing the default python binary file /usr/bin/python.
Now remove downloaded source archive file from your system
# rm Python-3.4.3.tgz
Check the latest version installed of python using below command
# python3.4 -V
Python 3.4.3
 

Using yum package:

#sudo yum install https://centos6.iuscommunity.org/ius-release.rpm
#sudo yum search python3
Most probably, you would install Python 3.4:
#sudo yum install python34u

# python3.4 -V
Python 3.4.3
 
you can run python using scripts and interactive console as well...if you want to go to interactive console just type a #python3 in command line it takes you as below.... in order to print something in interactive console you don't have to say print statements and all...since you are in interactive console you just type what ever you want it displays for you.

[root@bharath bharath]# python3
Python 3.4.4 (default, Jan  8 2016, 14:29:51)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> "Hello World"
'Hello World'
>>>
Define variable in interactive console...python treats string variable as arrays as below and it prints like below...
here is a variable called message, you can slice it as below
>>> message = "hello world"
>>> message[0:5]
'hello'
>>> message[:5]
'hello'
>>> message[5:]
' world'
>>>
You can concatenate the strings using the + symbol as below

>>> message[5:] + message
' worldhello world'
>>> message[5:] + " " +  message
' world hello world'
>>> message[5:] + "  BHARATH   " +  message
' world  BHARATH   hello world'
>>>

one more helpful feature is the help()>>> help()

Welcome to Python 3.4's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.4/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help>
help> modules
Please wait a moment while I gather a list of all available modules...
CDROM               array               http                sched
DLFCN               ast                 idlelib             select
IN                  asynchat            imaplib             selectors
TYPES               asyncio             imghdr              setuptools
__future__
etc.........
for example type a module name as "os" you can be displayed as below.
help> os
Help on module os:
NAME
    os - OS routines for NT or Posix depending on what system we're on.
DESCRIPTION
    This exports:
      - all functions from posix, nt or ce, e.g. unlink, stat, etc.
      - os.path is either posixpath or ntpath
      - os.name is either 'posix', 'nt' or 'ce'.
      - os.curdir is a string representing the current directory ('.' or ':')
      - os.pardir is a string representing the parent directory ('..' or '::')
      - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
      - os.extsep is the extension separator (always '.')
      - os.altsep is the alternate pathname separator (None or '/')
      - os.pathsep is the component separator used in $PATH etc
      - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
      - os.defpath is the default search path for executables
      - os.devnull is the file path of the null device ('/dev/null', etc.)
help>:
it gives info about the slicings.

How to run using a script ....
 sys.argv[0] = script name
sys.argv[1] = first argument passed to the script as below.
[root@bharath bharath]# cat hello.py
import sys
message = "hello world"
print(message)
print (sys.argv[0])
print ( "hi" +" "+ sys.argv[1] +" "+ sys.argv[2] )
[root@bharath bharath]#
to run the above script i am gonna pass the two command line arguments.
[root@bharath bharath]#  python3 hello.py bharath raju
hello world
hello.py
hi bharath raju
[root@bharath bharath]#

 
Single line comments starts with pound sign i.e. #
multi line coments are starts with triple single quotes i.e.  ' ' '   and ends with ' ' '

[root@bharath bharath]# cat hello.py
import sys
message = "hello world"
#print(message)
print (sys.argv[0])
print ( "hi" +" "+ sys.argv[1] +" "+ sys.argv[2] )
'''
hi hello
its multi-line
comments
'''
[root@bharath bharath]#
 
 Basic File System Functions In Python


>>> import os
>>> os.getcwd()
'/home/bharath'
>>> os.listdir()
['epel-release-6-8.noarch.rpm', 'hello.py', '.bash_logout', '.bash_profile', '.bashrc', '.bash_history', 'filemanage.py']
>>> os.listdir("/var/log")
['audit', 'maillog-20160129', 'lastlog', 'tallylog', 'yum.log', 'btmp', 'wtmp', 'messages-20160129', 'cron', 'maillog', 'messages', 'dmesg.old', 'dmesg', 'boot.log', 'dracut.log', 'secure-20160129', 'spooler-20160129', 'secure', 'spooler', 'cron-20160129']
>>>

In Eclipse you can write a pydev project as below...

import sys
import os
print(os.getcwd())
print(os.listdir())
print ("hello")
print ("hi" +"    "+sys.argv[0]

For loop in python. There is no specific end of control statements in python, You can use Four white spaces or a tab to indicate the end of control statements.

>>> for dirpath, dirnames, filenames in os.walk(os.getcwd(), topdown="true"):
...    print(dirpath, filenames)
...
/home/bharath ['epel-release-6-8.noarch.rpm', 'hello.py', '.bash_logout', '.bash_profile', '.bashrc', '.bash_history', 'filemanage.py']
/home/bharath/hanuman []

How to use two for loops.



>>> for dirpath, dirnames, filenames in os.walk(os.getcwd(), topdown="true"):
...     for f in filenames:
...             print(dirpath, f)
...
/home/bharath epel-release-6-8.noarch.rpm
/home/bharath hello.py
/home/bharath .bash_logout
/home/bharath .bash_profile
/home/bharath .bashrc
/home/bharath .bash_history
/home/bharath filemanage.py
>>>


Opening Files, Creating Files and Reading Files:

File modes are read, write, readwrite....below command

>>> file = open("/home/bharath/hanuman/testfile" , "w")
>>>
>>> os.chdir("hanuman")
>>> os.getcwd()
'/home/bharath/hanuman'
>>> os.listdir()
['testfile']
>>>

>>> file = open("/home/bharath/hanuman/raju1","w")
>>> print(file)
<_io.TextIOWrapper name='/home/bharath/hanuman/raju1' mode='w' encoding='UTF-8'>
>>>

How to write contents to a file ..see below command


>>> file.write("this is raju1 file")
18
>>>
We just written a file called raju and now we have to read it.


>>> file.close()
>>> file = None
>>> file = open("/home/bharath/hanuman/raju1", "r")  # making raju1 file for reading
>>> file.read()
'this is raju1 file'
>>>
There is a convenient way to check the file exists or not? There is a module called os.path.exists()


>>> if os.path.exists("/home/bharath/hanuman/raju1"):
...      print("Found it!!!!")
... else:
...     print("Nope, Not Found it!!!")
...
Found it!!!!
>>>
>>> if os.path.exists("/home/bharath/hanumaxyzn/raju1"):
...      print("Found it!!!!")
... else:
...     print("Nope, Not Found it!!!")
...
Nope, Not Found it!!!
>>>

>>> dir = "/home/bharath/hanuman"
>>> if os.path.isfile(dir):
...     print("It's a file")
... else:
...     print("It's a directory")
...
It's a directory
>>>

>>> dir = "/home/bharath/hanuman/raju1"
>>> if os.path.isfile(dir):
...     print("It's a file")
... else:
...     print("It's a directory")
...
It's a file
>>>

Copy and moving files in python
 
to copy and move you should have to import the shutil module as below...

>>> import shutil
>>> shutil.copy("/home/bharath/hanuman/raju1" , "/home/bharath")
'/home/bharath/raju1'
>>> os.listdir("/home/bharath")
['hanuman', 'epel-release-6-8.noarch.rpm', 'hello.py', 'raju1', '.bash_logout', '.bash_profile', '.bashrc', '.bash_history', 'filemanage.py']
>>>

how to rename raju1 , we can do it using the os.rename module as below.

>>> os.rename("/home/bharath/raju1", "/home/bharath/raju123456789")
>>> os.listdir("/home/bharath")
['raju123456789', 'hanuman', 'epel-release-6-8.noarch.rpm', 'hello.py', '.bash_logout', '.bash_profile', '.bashrc', '.bash_history', 'filemanage.py']
>>>

moving the new file raju123456789 to the directory /home/bharath/hanuman/.

>>> shutil.move("/home/bharath/raju123456789", "/home/bharath/hanuman/")
'/home/bharath/hanuman/raju123456789'
>>>
>>> os.listdir("/home/bharath/hanuman/")
['raju123456789', 'testfile', 'raju1']
>>>

Let's delete a file os.remove() and os.removedir() modules...

>>> os.remove("/home/bharath/hanuman/raju123456789")
>>> os.listdir("/home/bharath/hanuman/")
['testfile', 'raju1']

>>> os.remove("/home/bharath/hanuman/raju1")
>>> os.listdir("/home/bharath/hanuman/")
['testfile']

>>> os.removedirs("/home/bharath/hanuman")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.4/os.py", line 255, in removedirs
    rmdir(name)
OSError: [Errno 39] Directory not empty: '/home/bharath/hanuman'

>>> os.remove("/home/bharath/hanuman/testfile")
>>> os.removedirs("/home/bharath/hanuman")

>>> os.listdir("/home/bharath/")
['epel-release-6-8.noarch.rpm', 'hello.py', '.bash_logout', '.bash_profile', '.bashrc', '.bash_history', 'filemanage.py']
>>>
 



exception handling, logging, and zipping file with the zipfile module in python

Crate a file like below to make your life easier in while writing python scripts. Cause in python everything is space-sensitive

#vim .vimrc

set ts=4
set shiftwidth=4
set expandtab

A sample python script for backup with exception handling and the logging mechanism....

File_Name: backup.py

import zipfile
import sys
import os
import logging
logging.basicConfig(filename='file_ex.log', level = logging.DEBUG)
logging.info("check to see the if the backup.zip exists")
if os.path.exists("backup.zip"):
    logging.info("backup.zip exists")
    try:
        zip_file = zipfile.ZipFile('backup.zip','a')
    except:
        err = sys.exc_info()
        logging.error("unable to open backup.zip in append mode!")
        logging.error("Error Num: " + str(err[1].args[0]))
        logging.error("Error Msg: " + err[1].args[1])
        sys.exit()
else:
    logging.info("Creating backup.zip")
    try:
        zip_file = zipfile.ZipFile('backup.zip', 'w')
    except:
        err = sys.exc_info()
        logging.error("unable to create  backup.zip ")
        logging.error("Error Num: " + str(err[1].args[0]))
        logging.error("Error Msg: " + err[1].args[1])
        sys.exit()

logging.info("adding test.txt to a backup.zip file")
try:
    zip_file.write('test.txt', 'test.txt' , zipfile.ZIP_DEFLATED)
except:
    err = sys.exc_info()
    logging.error("unable to create  backup.zip ")
    logging.error("Error Num: " + str(err[1].args[0]))
    logging.error("Error Msg: " + err[1].args[1])
zip_file.close()











If we run the above file as below it creates a backup.zip file and sends all the log info/Debug  to the file called file_ex.log 

[root@bharath bharath]# python3 backup.py
[root@bharath bharath]# 

 [root@bharath bharath]# cat file_ex.log
INFO:root:check to see the if the backup.zip exists
INFO:root:Creating backup.zip
INFO:root:adding test.txt to a backup.zip file
ERROR:root:unable to create  backup.zip
ERROR:root:Error Num: 2
ERROR:root:Error Msg: No such file or directory
INFO:root:check to see the if the backup.zip exists
INFO:root:backup.zip exists
INFO:root:adding test.txt to a backup.zip file
INFO:root:check to see the if the backup.zip exists
INFO:root:backup.zip exists
INFO:root:adding test.txt to a backup.zip file
INFO:root:check to see the if the backup.zip exists
INFO:root:backup.zip exists
INFO:root:adding test.txt to a backup.zip file
[root@bharath bharath]#

 Now just change the backup.zip file permissions as chmod 100 so that it won't allow to append so that let's check our error handling works or not in the script?






[root@bharath bharath]# rm -f backup.zip
[root@bharath bharath]# rm -f test.txt
[root@bharath bharath]# rm -f file_ex.log
[root@bharath bharath]# python3 backup.py
[root@bharath bharath]# cp -ipr /tmp/test.txt .
[root@bharath bharath]# chmod 100 backup.zip

[root@bharath bharath]# python3 backup.py
[root@bharath bharath]# cat file_ex.log
INFO:root:check to see the if the backup.zip exists
INFO:root:Creating backup.zip
INFO:root:adding test.txt to a backup.zip file
ERROR:root:unable to create  backup.zip
ERROR:root:Error Num: 2
ERROR:root:Error Msg: No such file or directory
INFO:root:check to see the if the backup.zip exists
ERROR:root:unable to open backup.zip in append mode!
ERROR:root:Permission denied
[root@bharath bharath]#

A Sample python script to handle the process and sub process:

 
 

 

 

Comments

  1. BKR, Very good...you have nicely written the article. Indeed useful.

    ReplyDelete
  2. I really like your blog. You make it interesting to read and entertaining at the same time. I cant wait to read more from you.
    DevOps Training in Pune

    DevOps Online Training

    ReplyDelete
  3. Thanks for providing such a great information. It’s really Helpful for me.
    DevOps Course Videos

    ReplyDelete
  4. Amazing blog. Amazing stuff contained on this website. great admin continue.

    Best Training Institute in Bangalore BTM. My Class Training Bangalore training center for certified course, learning on Software Training Course by expert faculties, also provides job placement for fresher, experience job seekers.
    Software Training Institute in Bangalore

    ReplyDelete
  5. Nice and good article.Thanks for sharing this useful information.
    DevOps Training
    DevOps Online Training

    ReplyDelete

Post a Comment

Popular posts from this blog

Ansible for Devops

How to check the hardware information in Linux Systems?