Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Friday, 5 March 2021

Python: how to use enum in python

Description:

  • Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi.
  • For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as enum34. Code is not perfectly compatible between py2 and py3, e.g. you'll need __order__ in python 2).  
  • To use enum34, do $ pip install enum34
  • To use aenum, do $ pip install aenum

Program:

  # Python enum usage
# Check : http://velrajcoding.blogspot.in
#

# Below is supported from python 3.4 onwards.
from enum import Enum

class Animal(Enum):
    DOG = 1
    CAT = 2
    LION = 3


class EnumAssign():
    def __init__(self):
        self.Animal_enum = Animal

    def display_ani(self, value):
        print("The EnumAssign Animal.DOG  : ")
        print(self.Animal_enum.DOG)

        print("The EnumAssign Animal.DOG value : %d" % self.Animal_enum.DOG.value)

        print("The EnumAssign Animal.DOG  name : %s" % self.Animal_enum.DOG.name)
        if self.Animal_enum.DOG.value == value:
            print("The requested value is DOG")
        elif (self.Animal_enum.CAT.value == value):
            print("The requested value is CAT")
        elif (self.Animal_enum.LION.value == value):
            print("The requested value is LION")
def main():
    print()
    print("****************** Starting Main fun ******************************")
    print()
    obj = EnumAssign();
    obj.display_ani(Animal.CAT.value)

#print("The value of enum is    : %d " % Animal.DOG)
print("The display Outside function Direct access Animal.DOG : ")
print(Animal.DOG)

print("The display Outside function Direct access Animal.DOG value : %d" % Animal.DOG.value)

print("The display Outside function Direct access Animal.DOG  name : %s" % Animal.DOG.name)


if __name__ == "__main__":
    main()

   

Output

h]$ python3 py_enum.py
The display Outside function Direct access Animal.DOG :
Animal.DOG
The display Outside function Direct access Animal.DOG value : 1
The display Outside function Direct access Animal.DOG  name : DOG

****************** Starting Main fun ******************************

The EnumAssign Animal.DOG  :
Animal.DOG
The EnumAssign Animal.DOG value : 1
The EnumAssign Animal.DOG  name : DOG
The requested value is CAT


Reference:
     https://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python


Friday, 31 July 2020

python: how to use pexpect without installing

We can use the pexpect without installing, below is the best way to use:

  1. Downloaded Pexpect 2.4 ( https://pypi.org/project/pexpect/2.4/#files).
    • We tested on python 2.7.10 version, need to check in latest python version, not sure this will work on latest.
    • Also seems not support in latest pexpect version because latest version doesn't have pexpect.py file iteself. so best use pexpect 2.4 version. 
       2. Place pexpect.py next to my script
       3. import pexpect in my script.


It will work.

Tuesday, 6 November 2018

python: script to install Minimal requirements to compile the Kernel

Install the minimal requirment to compile the kernel which are declared in below sites:
      https://www.kernel.org/doc/html/v4.15/process/changes.html



Program:

# install Kernel minimal requriment compilation by Velraj.K
# Check : http://velrajcoding.blogspot.in

import subprocess
import shutil
import os

APT_INSTALL_COMMAND = "sudo apt-get --assume-yes install "
APT_UPDATE      = "sudo apt update --assume-yes"

DICT_NAME      = 'name'
DICT_CMD       = 'command'
DICT_CMD_INST  = 'command_install'

existing_sofware = []
installing_list  = []
installing_err   = []

def is_tool_present(name):
    # var = os.system('which vim') will display the output on console and store success value 0 to var
    # store the output of which in command line value into the var.
    var = os.popen('which ' + name).read()
    ret = var.find(name)
    return ret != -1


def install_software(software):
    #subprocess.call("sudo apt-get update", shell=True)
    if is_tool_present(software[DICT_CMD]):
        print(software[DICT_NAME] + " is already installed in the system, so not installing \n");
        existing_sofware.append(software)

    else:
        # run the install command in the shell,
        ret = subprocess.call(APT_INSTALL_COMMAND + software[DICT_CMD_INST], shell=True)
        # check is the software is installed successfully, if success add in installing_list otherwise add in _err.
        if ret == 0:
            print "Installed " + software[DICT_NAME] + " Successfully"
            installing_list.append(software)
        else:
            installing_err.append(software)

# Display the table header.
def table_header():
    # The value 1,20,25 & 20 are constant based on the column name
    print "{:<15} {:20} {:<20} {:<25} {:<20}".format('Package', '\"Command Name\"', '\"Newly Installed\"', '\"Error while installing\"', '\"Existing package\"')
    line = []
    for i in range(1, 82):
        # creat the list with - for display a line
        line.append('-')
    # convert the list into a string other wise display as ['-', '-', '-', ...]
    str1 = ''.join(str(e) for e in line)
    print str1

# To display the row content in the table
def table_row(table_row):
    # The value 22, 23,23 & 20 are constant based on the column adjust value row
        print "{:<22} {:<22} {:<23} {:<23} {:<20}".format(table_row[0], table_row[1], table_row[2], table_row[3], table_row[4])


def result_tablular():
    # Display the result table header
    table_header()
    # Display the row value in the tabl
    for name in installing_list:
        table_row([name[DICT_NAME], name[DICT_CMD_INST], 'Yes', 'NA', 'NA'])

    for name in installing_err:
        table_row([name[DICT_NAME], name[DICT_CMD_INST], 'NA', 'Yes', 'NA'])

    for name in existing_sofware:
        table_row([name[DICT_NAME], name[DICT_CMD_INST], 'NA', 'NA', 'Yes'])

def main():
    software_name = ['gcc', 'make', 'ld', 'fdformat', 'depmod', 'e2fsck',
                     'pccardctl', 'pppd', 'ps', 'iptables', 'openssl', 'bc',
                     'fsck.jfs', 'reiserfsck', 'xfs_db', 'mksquashfs', 'btrfsck',
                     'quota', 'iudnctrl', 'showmount', 'oprofiled', 'udevd', 'grub',
                     'mcelog', 'sphinx-build' ]

    dict_list_software = [ {DICT_NAME:'GNU C', DICT_CMD:'gcc', DICT_CMD_INST:'gcc'},
                       {DICT_NAME:'GNU make', DICT_CMD:'make', DICT_CMD_INST:'make'},
                       {DICT_NAME:'binutils', DICT_CMD:'ld', DICT_CMD_INST:'binutils'},
                       {DICT_NAME:'util-linux', DICT_CMD:'fdformat', DICT_CMD_INST:'util-linux'},
                       {DICT_NAME:'module-init-tools', DICT_CMD:'depmod', DICT_CMD_INST:'module-init-tools'},
                       {DICT_NAME:'e2fsprogs', DICT_CMD:'e2fsck', DICT_CMD_INST:'e2fsprogs'},
                       {DICT_NAME:'jfsutils', DICT_CMD:'fsck.jfs', DICT_CMD_INST:'jfsutils'},
                       {DICT_NAME:'reiserfsprogs', DICT_CMD:'reiserfsck', DICT_CMD_INST:'reiserfsprogs'},
                       {DICT_NAME:'xfsprogs', DICT_CMD:'xfs_db', DICT_CMD_INST:'xfsprogs'},
                       {DICT_NAME:'squashfs-tools', DICT_CMD:'mksquashfs', DICT_CMD_INST:'squashfs-tools'},
                       {DICT_NAME:'btrfs-progs', DICT_CMD:'btrfsck', DICT_CMD_INST:'btrfs-progs'},
                       {DICT_NAME:'pcmciautils', DICT_CMD:'pccardctl', DICT_CMD_INST:'pccardctl'},
                       {DICT_NAME:'quota-tools', DICT_CMD:'quota', DICT_CMD_INST:'quota'},
                       {DICT_NAME:'PPP', DICT_CMD:'pppd', DICT_CMD_INST:'pppd'},
                       {DICT_NAME:'isdn4k-utils', DICT_CMD:'isdnctrl', DICT_CMD_INST:'isdnutils-base'},
                       {DICT_NAME:'nfs-utils', DICT_CMD:'showmount', DICT_CMD_INST:'nfs-common'},
                       {DICT_NAME:'procps', DICT_CMD:'ps', DICT_CMD_INST:'procps'},
                       {DICT_NAME:'oprofile', DICT_CMD:'oprofiled', DICT_CMD_INST:'oprofile'},
                       {DICT_NAME:'udev', DICT_CMD:'udevd', DICT_CMD_INST:'udev'},
                       {DICT_NAME:'grub', DICT_CMD:'grub', DICT_CMD_INST:'grub-pc'},
                       {DICT_NAME:'mcelog', DICT_CMD:'mcelog', DICT_CMD_INST:'mcelog'},
                       {DICT_NAME:'iptables', DICT_CMD:'iptables', DICT_CMD_INST:'iptables'},
                       {DICT_NAME:'openssl & libcrypto', DICT_CMD:'openssl', DICT_CMD_INST:'openssl'},
                       {DICT_NAME:'bc', DICT_CMD:'bc', DICT_CMD_INST:'bc'},
                       {DICT_NAME:'Sphinx', DICT_CMD:'sphinx', DICT_CMD_INST:'python-sphinx'} ]
    ret = subprocess.call(APT_UPDATE, shell=True)
    # Check and install the list of software available in the software_name
    for name in dict_list_software:
        install_software(name)

    # Package installed due to kernal compilation error
    # sign-file.c:25:30: fatal error: openssl/opensslv.h: No such file or directorycompilation terminated.
    #    for install libssl-dev
    dict_list_soft_cmp_err = [ {DICT_NAME:'OpenSSL Dev pkg', DICT_CMD:'libssl-dev', DICT_CMD_INST:'libssl-dev'} ]
    for name in dict_list_soft_cmp_err:
       install_software(name)


    result_tablular()

if __name__ == "__main__":
    main()

python: script to check Minimal requirements to compile the Kernel

Used to check the minimal requirment to compile the kernel which are declared in below sites:
      https://www.kernel.org/doc/html/v4.15/process/changes.html


Program:

# Kernel minimal requriment check by Velraj.K
# Check : http://velrajcoding.blogspot.in

import subprocess
import shutil
import os

APT_INSTALL_COMMAND = "sudo apt-get --assume-yes install "
APT_UPDATE      = "sudo apt update --assume-yes"

DICT_NAME      = 'name'
DICT_CMD       = 'command'
existing_sofware = []
not_available_list  = []
installing_err   = []

def is_tool_present(name):
    # var = os.system('which vim') will display the output on console and store success value 0 to var
    # store the output of which in command line value into the var.
    var = os.popen('which ' + name).read()
    ret = var.find(name)
    return ret != -1


def install_software(software):
    # Check the command is present in Linux OS
    if is_tool_present(software[DICT_CMD]):
        existing_sofware.append(software)
    else:
        not_available_list.append(software)

# Display the table header.
def table_header():
    # The value 1,20,25 & 20 are constant based on the column name
    print "{:<20} {:<15} {:<20} {:<20}".format('Program Name', '\"Command\"', '\"Available\"', '\"Not available\"')
    line = []
    for i in range(1, 72):
        # creat the list with - for display a line
        line.append('-')
    # convert the list into a string other wise display as ['-', '-', '-', ...] 
    str1 = ''.join(str(e) for e in line)
    print str1

# To display the row content in the table
def table_row(table_row):
    # The value 22, 23,23 & 20 are constant based on the column adjust value row
        print "{:<23} {:<15} {:<21} {:<20}".format(table_row[0], table_row[1], table_row[2], table_row[3])


def result_tablular():
    # Display the result table header
    table_header()
    # Display the row value in the tabl
    for name in existing_sofware:
        table_row([name[DICT_NAME], name[DICT_CMD], 'Yes', 'NA'])
    for name in not_available_list:
        table_row([name[DICT_NAME], name[DICT_CMD], 'NA', 'Yes'])


def main():

    # Dictionary usage example: 
    #    myStruct = {'field1': 'some val', 'field2': 'some val'}
    #    print myStruct['field1']
    #    myStruct['field2'] = 'some other values'
    # List of Minimum requirement package
    dict_list_software = [ {DICT_NAME:'GNU C', DICT_CMD:'gcc'},
                           {DICT_NAME:'GNU make', DICT_CMD:'make'},
                           {DICT_NAME:'binutils', DICT_CMD:'ld'},
                           {DICT_NAME:'util-linux', DICT_CMD:'fdformat'},
                           {DICT_NAME:'module-init-tools', DICT_CMD:'depmod'},
                           {DICT_NAME:'e2fsprogs', DICT_CMD:'e2fsck'},
                           {DICT_NAME:'jfsutils', DICT_CMD:'fsck.jfs'},
                           {DICT_NAME:'reiserfsprogs', DICT_CMD:'reiserfsck'},
                           {DICT_NAME:'xfsprogs', DICT_CMD:'xfs_db'},
                           {DICT_NAME:'squashfs-tools', DICT_CMD:'mksquashfs'},
                           {DICT_NAME:'btrfs-progs', DICT_CMD:'btrfsck'},
                           {DICT_NAME:'pcmciautils', DICT_CMD:'pccardctl'},
                           {DICT_NAME:'quota-tools', DICT_CMD:'quota'},
                           {DICT_NAME:'PPP', DICT_CMD:'pppd'},
                           {DICT_NAME:'isdn4k-utils', DICT_CMD:'isdnctrl'},
                           {DICT_NAME:'nfs-utils', DICT_CMD:'showmount'},
                           {DICT_NAME:'procps', DICT_CMD:'ps'},
                           {DICT_NAME:'oprofile', DICT_CMD:'oprofiled'},
                           {DICT_NAME:'udev', DICT_CMD:'udevd'},
                           {DICT_NAME:'grub', DICT_CMD:'grub'},
                           {DICT_NAME:'mcelog', DICT_CMD:'mcelog'},
                           {DICT_NAME:'iptables', DICT_CMD:'iptables'},
                           {DICT_NAME:'openssl & libcrypto', DICT_CMD:'openssl'},
                           {DICT_NAME:'bc', DICT_CMD:'bc'},
                           {DICT_NAME:'Sphinx', DICT_CMD:'sphinx-build'} ]

    # Check and install the list of software available in the software_name
    for name in dict_list_software:
        install_software(name)

    result_tablular()

if __name__ == "__main__":
    main()

Monday, 5 November 2018

python: script to install C Linux development needed packages

The Following C linux development packages are installed using python script:
  • Vim
  • cscope
  • screen
  • make
  • cmake
  • gdb
  • gcc


Program:



import subprocess
import shutil
import os

APT_INSTALL_COMMAND = "sudo apt-get --assume-yes install "
APT_UPDATE      = "sudo apt update --assume-yes"

existing_sofware = []
installing_list  = []
installing_err   = []

def is_tool_present(name):
    # var = os.system('which vim') will display the output on console and store success value 0 to var
    # store the output of which in command line value into the var.
    var = os.popen('which ' + name).read()
    ret = var.find(name)
    return ret != -1

def install_software(software):
    #subprocess.call("sudo apt-get update", shell=True)
    if is_tool_present(software):
        print(software + " is already installed in the system, so not installing \n");
        existing_sofware.append(software)

    else:
        # run the install command in the shell,
        ret = subprocess.call(APT_INSTALL_COMMAND + software, shell=True)
        # check is the software is installed successfully, if success add in installing_list otherwise add in _err.
        if ret == 0:
            print "Installed " + software + " Successfully"
            installing_list.append(software)
        else:
            installing_err.append(software)

# Display the table header.
def table_header():
    # The value 1,20,25 & 20 are constant based on the column name
    print "{:<15} {:<20} {:<25} {:<20}".format('Package', '\"Newly Installed\"', '\"Error while installing\"', '\"Existing package\"')
    line = []
    for i in range(1, 82):
        # creat the list with - for display a line
        line.append('-')
    # convert the list into a string other wise display as ['-', '-', '-', ...]
    str1 = ''.join(str(e) for e in line)
    print str1

# To display the row content in the table
def table_row(table_row):
    # The value 22, 23,23 & 20 are constant based on the column adjust value row
        print "{:<22} {:<23} {:<23} {:<20}".format(table_row[0], table_row[1], table_row[2], table_row[3])


def result_tablular():
    # Display the result table header
    table_header()
    # Display the row value in the tabl
    for name in installing_list:
        table_row([name, 'Yes', 'NA', 'NA'])

    for name in installing_err:
        table_row([name, 'NA', 'Yes', 'NA'])

    for name in existing_sofware:
        table_row([name, 'NA', 'NA', 'Yes'])

def main():
    # The follwoing software used for automake
    #      automake, automake1.11
    #      libtool --> Used in automake file as libtoolize command
    # binutils-dev --> includes header files and static libraries necessary to build programs which use the GNU BFD library
    # build-essential --> for libc-devel
    software_name = ['vim', 'cscope', 'screen', 'make', 'cmake', 'gdb', 'gcc', 'git', 'automake', 'libtool',
                     'binutils-dev', 'libc6', 'build-essential']

    ret = subprocess.call(APT_UPDATE, shell=True)
    # Check and install the list of software available in the software_name
    for name in software_name:
        install_software(name)

    result_tablular()

if __name__ == "__main__":
    main()

  

Tuesday, 26 June 2018

python - Split the file name from git diff


Program:

import sys   # For command line argument
import os.path # To check file existing

def generate_writefile(file_name):
    count = 1
    while True:                      # in True T must be capital
        file_name_new = file_name
        file_name_new += "_" + str(count)
        count += 1
        if not os.path.isfile(file_name_new):
            return file_name_new
        if count >=10 :
            print "Error while creating file"
            return None


def main():
    cmd_len = len(sys.argv)
    if(cmd_len <2):
        print "\t\tVel Error, provide the git file name\n\n"
        return

    name =  sys.argv[1]
    file_name = generate_writefile(sys.argv[1])
    if file_name == None:
        return
    file_write = open(file_name, 'w')
    if  not os.path.isfile(sys.argv[1]):
        print "Vel Error, provided file is not existing\n\n"
        return

    count_file = 0
    with open(sys.argv[1]) as openfileobject:
        for line in openfileobject:
            spl_for_com = line.split()      # convert the list of array into an separated string
            length = len(spl_for_com)
            if((length >=4) and (spl_for_com[0] == "diff") and (spl_for_com[1] == "--git")):
#        print "Got the match velraj ", spl_for_com[2][1:], spl_for_com[3]
                file_write.write(spl_for_com[2][1:])
                file_write.write("\n")
                count_file += 1
    print "Number of file = ", str(count_file), "Output file name is = ", file_name

    if count_file == 0:
        os.remove(file_name)

main()


# API to read from file.
    #    message = file_read.read()   # It read a whole file in  1 time
    #    message = file_read.readline()  # Its read only single line

Thursday, 14 June 2018

python - Execute the system Linux command on remote Linux machine

python - Execute the system Linux command on remote Linux machine


Python Program:


mport pexpect
import getpass
import sys

PASSWORD = "admin123"

def child_kill(child_pro):
    if child_pro.isalive():
        print "Still child is live 1 \n"
        child_pro.close()       # Kill the child, give argument as force=true then also same behaviour
    if child_pro.isalive():
        print "Still child is live 2\n\n"
    else:
        print "Child is dead"

def child_read_command(child_pro, command, expect_str):
    child_pro.sendline (command)
    child_pro.expect (expect_str)

# use list format, string format is not working
    output = []
    done = False
    while True:
        try:
            if not child_pro.isalive():
                line = child_pro.readline()
                done = True
            else:
# Wait on multiple expect eg: i = child.expect(['first', 'second'])
# i retrun 0 for first, and 1 for second
                i = child_pro.expect(['\n', expect_str])
                if i == 0:
                    line = child_pro.before
                    print(line)
                else:
                    line = child_pro.before
                    print(line)
                    break
            output.append(line)
            if done:
                raise pexpect.EOF(0)
                print "Rasie the pexect EOF"
        except pexpect.EOF:
            print "Break of EOF"
            break

    print "\n\nOutput value = ", output
    child_kill(child_pro)

def ssh_login(host_address):
    child = pexpect.spawn ('ssh '+host_address)
    child.logfile = open("/home/labuser/mylog", "w")   # This will store the output logs into the file
#    child.logfile = sys.stdout
    child.expect ('password: ')
    child.sendline (PASSWORD)
    child.expect ('machine:')
    return child


def main():
    child = ssh_login("192.168.1.50")
    child_read_command(child,'ls','machine:')


main()



python - pexpect - multiple expect, spawn, kill child

python - pexpect - multiple expect, spawn, kill child


pexpect - multiple expect:


i = child.expect(['first', 'second'])
The expect() method returns the index of the pattern that was matched. So in your example:
if i == 0:
    # do something with 'first' match
else: # i == 1
    # do something with 'second' match

Spawn:

  • The more powerful interface is the spawn class. 
  • You can use this to spawn an external child command and then interact with the child by sending lines and expecting responses.
child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:')
child.sendline (mypassword)

close(force=True)
  • This closes the connection with the child application. 
  • Note that calling close() more than once is valid. 
  • This emulates standard Python behavior with files. 
  • Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT).
child.close() 
or child.close(force=true)

Program:

import pexpect
import getpass
import sys

PASSWORD = "admin123"

def child_kill(child_pro):
    if child_pro.isalive():
        print "Still child is live 1 \n"
        child_pro.close()       # Kill the child, give argument as force=true then also same behaviour
    if child_pro.isalive():
        print "Still child is live 2\n\n"
    else:
        print "Child is dead"

def child_read_command(child_pro, command, expect_str):
    child_pro.sendline (command)
    child_pro.expect (expect_str)

# use list format, string format is not working
    output = []
    done = False
    while True:
        try:
            if not child_pro.isalive():
                line = child_pro.readline()
                done = True
            else:
# Wait on multiple expect eg: i = child.expect(['first', 'second'])
# i retrun 0 for first, and 1 for second
                i = child_pro.expect(['\n', expect_str])
                if i == 0:
                    line = child_pro.before
                    print(line)
                else:
                    line = child_pro.before
                    print(line)
                    break
            output.append(line)
            if done:
                raise pexpect.EOF(0)
                print "Rasie the pexect EOF"
        except pexpect.EOF:
            print "Break of EOF"
            break

    print "\n\nOutput value = ", output
    child_kill(child_pro)



Reference: http://www.bx.psu.edu/~nate/pexpect/pexpect.html

Thursday, 26 April 2018

python - The message packer reads a string

The message packer reads a string

You need to implement a Message Packer. The message packer reads a string

Rules:

  • adds two chars ZZ to mark the beginning of the message
  • add number 0 to mark the end of the message.
  • The input string is reversed inside the message.
  • If the input string contains char Z then it is replaced by # in the message. The lower case character z is retained
  • If the input string contains numeric character 0 then it is replaced by $.
  • Only lower case letter ([a-z]), upper case letter ([A-Z]) and numeric characters ([0-9]) are accepted. If the string contains any other characters an error message Invalid String
  • Maximum number of characters accepted in the string is 8. If the number exceeds 8 then Exceeded Limit   is output

Sample:

  • Input : You need to read a string from STDIN.
  • Output :  Message Packed as per rules above or Invalid String or Exceeded Limit is  printed.

  • Input: PQRS
  • Output: ZZSRQP0

  • Input: ABbcZdz
  • Output: ZZzd#cbBA0

  • Input: X1340yZ
  • Output: ZZ#y$431X0

  • Input: AB*D1$34
  • Output: Invalid String

  • Input: ABCD12345
  • Output: Exceeded Limit

Program:

def main():
    message = raw_input("Enter value :")

    count = 0
    reverse = ''.join(reversed(message))    # Reversed the string , must need join

    lis = list(reverse)          # Reverse the string

    lengh = len(reverse)
    if lengh > 8:                # Length should be less than 8
        print "Exceeded Limit"
        return

    count = 0
    for char in lis:
        if char == 'Z':
            lis[count] = '#'
        elif char == '0':
            lis[count] = '$'
        elif not (char.isupper() or char.islower() or char.isdigit()):
            print "Invalid String"
            return
        count = count + 1

    lis.append('0')
    lis = ['Z'] + lis                 # Append the Z to the begging of the list
    lis = ['Z'] + lis

    result = ''.join(lis)            # Convert list to the string

    print result

main()

Output:

acp_python$ python messagePacker.py
Enter value :ABbcZdz
ZZzd#cbBA0
acp_python$ vi messagePacker.py
acp_python$ python messagePacker.py
Enter value :X1340yZ
ZZ#y$431X0
acp_python$ python messagePacker.py
Enter value :AB*D1$34
Invalid String
acp_python$ python messagePacker.py
Enter value :ABCD12345
Exceeded Limit

python - Password validity checker using python

Password validity checker using python


  • You need to implement a password validity checker.  A password is valid if all the given rules are satisfied, else it is invalid.
    •  At least 1 (one) lower case letter ([a-z]) is present
    •  At least 1 numeric character ([0-9]) is present  
    •  At least 1 (one) upper  case letter ([A-Z]) is present
    •  At least 1 character from [$#@] is present
    •  Minimum and Maximum length allowed must be 6 and 12 respectively
  • Input : You need to read a string from STDIN and check if it is a valid or invalid password.
  • Output : The string valid or invalid printed.

  • Test Cases:

    • Input: ABCDa$$$$$56
    • Output: valid

    • Input: 12345abcd111
    • Output: invalid
    • Input: 2w3E*
    • Output: invalid

Program:

def main():
    password = raw_input("Enter value :")

    digit = 0
    upper = 0
    lower = 0
    special = 0
    flag_len = 0

    for char in password:
        if char.isdigit():
            digit = 1
        if char.isupper():
            upper = 1
        if char.islower():
            lower = 1
        if char == '$' or  char == '#' or char == '@':
            special = 1

    length = len(password)
    if length >= 6 and length <= 12:
        flag_len = 1

    if digit and upper and lower and special and flag_len:
       print "valid"
    else:
       print "invalid"

main()


Output:

python$ python passwordVali.py
Enter value :Velraj
invalid
python$
python$
python$ python passwordVali.py
Enter value :Velraj12#
valid

Friday, 30 March 2018

python - Extract the number from the string line

Have to build a new string which is of the form numeric_token1  numeric_token2 print this in ascending order. (A single space is the separator) (If no numeric tokens are found you need to print  NONE FOUND)


Input : 

        You need to read a line from STDIN to extract the numeric tokens only

Output :

 The string composed of number1  number2 in ascending order   .  Or  NONE FOUND

Test Cases:


Input: velraj hai 123  789 45 done
Output: 45 123 789

Input: 20 new old 90 67
Output: 20 67 90

Program:

def main():
#b = "vel 444 sdfdf 55 sdfdf 44 sdfdf 22 "
#   value = "vel 444 s 5 sdfdf 10 newver 3 sdfdf 1 sdfdf 2 "
   value = raw_input("Enter value :")
   list_array = value.split()

   digit_list = []
   for digit in list_array:
        if digit.isdigit():
#         print digit
            digit_list.append(int(digit))    # Make list to contain the number as interger type

   digit_list.sort()
   print digit_list

#str_ass = " vel "

   str1 = ' '.join(str(e) for e in digit_list)  # This line is used to convert the list into an string formate with space between digits
   if str1:
      print str1
   else:
      print "NONE FOUND"

#   for lis_to_dig in digit_list:
#      str_ass = ' ' + str(lis_to_dig)
#       print lis_to_dig
#    lis_to_arry = digit_list.split()


main()

Output:

$ python extra-num-from-str.py
Enter value :sdfdf 432 vel 22 hsdf 33 sdfdf 1 sdf 5
[1, 5, 22, 33, 432]
1 5 22 33 432

python - Extract First Name, Middle Name and Last Name

Input: 

       You need to read a line from STDIN to extract First Name, Middle Name and Last Name

Output: 

       First Name, Middle Name and Last Name (separated by a single comma)

Test Cases:

Input: Velraj Kutralam
Output: Velraj,,Kutralam

Input: vel raj kutralam
Output: vel,raj,kutralam

Program:

#input function in Python 2.7, evaluates whatever your enter, as a Python expression(that is python variable).
# If you simply want to read strings, then use raw_input function in Python 2.7, which will not evaluate the read strings.
line = raw_input("Enter the string:")
print line
#comma = ','.join(line)

spl = line.split()      # convert the list of array into an separated string
print spl
spl_for_com = spl[:3]  # copy the first 3 string
print spl_for_com

leng = len(spl_for_com)
#print leng

if(leng == 2):
    join = ',,'.join(spl_for_com)
else:
    join = ','.join(spl_for_com)

remainin = ' '.join(spl[3:])
#remainin = spl[3:].split()
result = join + ' ' + remainin
print "After join = %s " % result
print "Read value = %s " % line


Output:

$ python readStdin-str-opr.py
Enter the string:velraj kutralam
velraj kutralam
['velraj', 'kutralam']
['velraj', 'kutralam']
After join = velraj,,kutralam
Read value = velraj kutralam