如何在使用循环时在 python3 字典中使用制表

How to use tabulate in python3 dictionary while using loops

我正在尝试将字典数据打印成表格形式,现在我认为 tabulate 模块是一种简单的测试方法,但不知何故,我得到的数据是个好方法,但是header 信息在用户 ID 的每个 运行 上重复,请指导或建议如何做......

$ 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

作为一名学习者,在努力学习之后,我想到了以下代码变体来解决我自己的问题:

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()

结果输出如下...

$ ./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()

结果输出如下....

$ ./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()

上面的结果输出如下...

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