Search code examples
python-3.xdictionarytabular

How to use tabulate in python3 dictionary while using loops


I'm trying to print the dictionary data into a tabular form , for now i see tabulate module as a easy way to test but somehow the data i'm getting thats coming the good way but the header informaion is repeating on each run for the user ID, please guide or suggest how to do that.....

$ cat checktable.py
#!/usr/bin/python3
import subprocess
import pandas as pd
from tabulate import tabulate

def CheckUid(user):
    proc = subprocess.Popen("ldapsearch -h ldapserver  -D 'cn=directory manager' -w pass123 -LLLb 'ou=people,o=rraka.com'  'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    split_str = info_str.split()
    if len(split_str) > 1:
      raw_data = {'UserID': [split_str[1].split(',')[0].split('=')[1]], 'MangerID': [split_str[-1]]}
      headers = ["UserID", "MangerID"]
      return tabulate(raw_data, headers, tablefmt="simple")
    else:
      split_str = 'null'

def CallUid():
      with open('hh', mode='rt', encoding='utf-8') as f:
        for line in f.readlines():
         print(CheckUid(line))


if __name__ == '__main__':
    CallUid()

This returns the below data:

$ ./checktable.py
UserID    MangerID
--------  ----------
aashishp  rpudota
UserID    MangerID
--------  ----------
abaillie  davem
UserID    MangerID
--------  ----------
abishek   kalyang
UserID    MangerID

Expected output:

$ ./checktable.py
UserID    MangerID
--------  ----------
aashishp  rpudota
abaillie  davem
abishek   kalyang

Another alternative code:

#!/usr/bin/python3
import sys
import subprocess
from tabulate import tabulate

def CheckUid(user):
    proc = subprocess.Popen("ldapsearch -h its3  -D 'cn=directory manager' -w JatetRE3 -LLLb 'ou=people,o=cadence.com'  'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    split_str = info_str.split()
    if len(split_str) > 1:
      raw_data = {'UserID': split_str[1].split(',')[0].split('=')[1], 'Manger': split_str[-1]}
      for key, value in raw_data.items():
        print(key, ":", value)
    else:
      split_str = 'null'

def CallUid():
  with open('hh', mode='rt', encoding='utf-8') as f:
    for line in f.readlines():
      CheckUid(line)

if __name__ == '__main__':
  CallUid()

It comes as below, where i need every two line two be into one..

$ ./checktable2.py
UserID : aashishp
Manger : rpudota
UserID : abaillie
Manger : davem

While desired would be:

$ ./checktable2.py
UserID : aashishp Manger : rpudota
UserID : abaillie Manger : davem

Solution

  • After Struggling as a learner, I came around with the below variant of codes as a solution to my own questions:

    1) The First code is using the pandas module:

    $ cat check_ldapUserdata.py
    #!/usr/bin/python3
    import pandas as pd
    import subprocess
    
    user_list = []
    mngr_list = []
    
    def CheckUid(user):
        proc = subprocess.Popen("ldapsearch -h ldapserver -D 'cn=directory manager' -w JatetRE3 -LLLb 'ou=people,o=rraka.com' 'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
        info_str = proc.stdout.read().decode('utf8')
        split_str = info_str.split()
        if len(split_str) > 1:
          user = split_str[1].split(',')[0].split('=')[1]
          manager = split_str[-1]
          user_list.append(user)
          mngr_list.append(manager)
        else:
          split_str = 'null'
    
    def DataList():
          df = pd.DataFrame({'User':user_list, 'Manager':mngr_list})
          df = df[['User', 'Manager']]  # To keep the order of columns
          #return df
          print(df)
    
    def CallUid():
      with open('testu', mode='rt', encoding='utf-8') as f:
        for line in f.readlines():
          CheckUid(line)
    
    if __name__ == '__main__':
      CallUid()
      DataList()
    

    Result Output is as Follows...

    $ ./check_ldapUserdata.py
           User   Manager
    0      karn  benjamin
    1     niraj   vikashg
    2  vaithees  benjamin
    3      mauj  benjamin
    

    2) The another way I achived it with using Regular Expression & BeautifulTable module to get the table Format..

    $ cat check_ldapUserdata2.py
    #!/usr/bin/python3
    import re
    import subprocess
    from beautifultable import BeautifulTable
    table = BeautifulTable()
    table.column_headers = ["User", "Manager"]
    
    def CheckUid(user):
        proc = subprocess.Popen("ldapsearch -h ldapserver  -D 'cn=directory manager' -w pass123 -LLLb 'ou=people,o=rraka.com' 'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
        info_str = proc.stdout.read().decode('utf8')
        pat_match = re.match(".*uid=(.*?)\,.*\nmanagerlogin:\s+(.*)",info_str)
        if pat_match:
            table.append_row([pat_match.group(1), pat_match.group(2)])
    
    def CallUid():
      input_file=input("Please enter the file name : ")
      with open(input_file, mode='rt', encoding='utf-8') as f:
        for line in f.readlines():
          CheckUid(line)
      print(table)
    
    if __name__ == '__main__':
      CallUid()
    

    Result Output as as below....

    $ ./check_ldapUserdata2.py
    Please enter the file name : testu
    +----------+----------+
    |   User   | Manager  |
    +----------+----------+
    |   karn   | benjamin |
    +----------+----------+
    |  niraj   | vikashg  |
    +----------+----------+
    | vaithees | benjamin |
    +----------+----------+
    |   mauj   | benjamin |
    +----------+----------+
    

    3) Another Simple non tabular Form but working ..

    $ cat check_table_working1.py
    #!/usr/bin/python3
    import subprocess
    
    def CheckUid(user):
        proc = subprocess.Popen("ldapsearch -h ldapserver -D 'cn=directory manager' -w pass123 -LLLb 'ou=people,o=rraka.com' 'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
        info_str = proc.stdout.read().decode('utf8')
        split_str = info_str.split()
        if len(split_str) > 1:
          raw_data = {split_str[1].split(',')[0].split('=')[1] :  split_str[-1]}
          #raw_data = {'UserID': split_str[1].split(',')[0].split('=')[1], 'Manger': split_str[-1]}
          for key, value in raw_data.items():
            #print(key, ":", value)
            print('{} : {}'.format(key, value))
        else:
          split_str = 'null'
    
    def CallUid():
      with open('hh', mode='rt', encoding='utf-8') as f:
        for line in f.readlines():
          CheckUid(line)
    
    if __name__ == '__main__':
      CallUid()
    

    Result output of the above is as below...

    $ ./check_table_working1.py
    aashishp : rpudota
    abaillie : davem
    abishek : kalyang
    adik : venky
    adithya : jagi