python呼び出しlibvirt APIとアクセサリーアプリケーション

171586 ワード

環境
カーネルおよびOSバージョン
cat /etc/redhat-release 
CentOS Linux release 7.6.1810 (Core) 
[root@localhost python]# uname -r
3.10.0-957.el7.x86_64

pythonバージョン
python -V
Python 2.7.5

libvirt-pythonのインストール
pythonがlibvirtを呼び出すにはlibvirtモジュールが必要なので、まずこのモジュールをインストールします.
yum -y install libvirt-python

モジュールをインストールすると、追加されたパッケージが表示されます.
[root@localhost python]# ll /usr/lib64/python2.7/site-packages/|grep libvirt
-rw-r--r--  1 root root   1738 11   2 2018 libvirt_lxc.py
-rw-r--r--  2 root root   1680 11   2 2018 libvirt_lxc.pyc
-rw-r--r--  2 root root   1680 11   2 2018 libvirt_lxc.pyo
-rwxr-xr-x  1 root root  28496 11   2 2018 libvirtmod_lxc.so
-rwxr-xr-x  1 root root  28760 11   2 2018 libvirtmod_qemu.so
-rwxr-xr-x  1 root root 314712 11   2 2018 libvirtmod.so
-rw-r--r--  1 root root 330338 11  26 09:59 libvirt.py
-rw-r--r--  1 root root 366575 11  26 10:16 libvirt.pyc
-rw-r--r--  1 root root 366575 11   2 2018 libvirt.pyo
-rw-r--r--  1 root root   3213 11   2 2018 libvirt_qemu.py
-rw-r--r--  2 root root   3226 11   2 2018 libvirt_qemu.pyc
-rw-r--r--  2 root root   3226 11   2 2018 libvirt_qemu.pyo

書き込みコードlibvirtのAPIを呼び出す
エラーコード
cat /python/libvirt_python.py 
#!/usr/bin/python
#-*-coding:utf-8-*- 
import libvirt
import sys
 
def createConnection():
    conn = libvirt.openReadOnly(None)
    if conn == None:
        print '  KVM  '
        sys.exit(1)
    else:
        print '  KVM  '
        return conn
 
def closeConnection(conn):
    print ''
    try:
        conn.close()
    except:
        print '  KVM    '
        return 1
    print 'KVM    '
 
def getDomInfoByName(conn, name):
    print ''
    print '  KVM            '
    try:
        domain = conn.lookupByName(name)
    except:
        print ("  KVM   {}".format(name))
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStatus())
    print "   CPU  :{}".format(domain.maxVcpus())
def getDomInfoByID(conn, id):
    print ''
    print '  KVM   ID       '
    try:
        domain = conn.lookupByID(id)
    except:
        print 'Failed to find the Domain with ID "%"' % id
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStatus())
    print "   CPU  :{}".format(domain.maxVcpus())
if __name__ == '__main__':
    name1 = sys.argv[2]
    #name2 = "notExist"
    id1 = int(sys.argv[1])
    #id2 = 9999
    print "       libvirt python API"
    conn = createConnection()
    getDomInfoByName(conn, name1)
    #getDomInfoByName(conn, name2)
    getDomInfoByID(conn, id1)
    #getDomInfoByID(conn, id2)
    closeConnection(conn)

コードを実行する前にvirshで仮想マシン情報を表示します
virsh  list
 Id                                 
----------------------------------------------------
 3     CentOS7                        running

実行
[root@localhost python]# python libvirt_python.py 3 CentOS7
       libvirt python API
  KVM  

  KVM            
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 47080000000L]
       :1024 MB
Traceback (most recent call last):
  File "libvirt_python.py", line 61, in <module>
    getDomInfoByName(conn, name1)
  File "libvirt_python.py", line 37, in getDomInfoByName
    print "       :{}".format(domain.memoryStatus())
AttributeError: 'virDomain' object has no attribute 'memoryStatus'

エラー解決
新聞の間違いから見るとmemoryStatusという関数はありませんlibvirt.pyコードは/usr/lib 64/python 2.7/site-packages/ディレクトリの下.grepはこの関数名をフィルタリングし,本当にこの関数がないことを発見した.
[root@localhost python]# grep memoryStatus /usr/lib64/python2.7/site-packages/libvirt.py
grep   memory     ,   memoryStats    。  libvirt_python    memoryStatus   memoryStats  。
[root@localhost python]# grep memory /usr/lib64/python2.7/site-packages/libvirt.py
        """This method will suspend a domain and save its memory contents to
        """Retrieve the maximum amount of physical memory allocated to a
        domain. If domain is None, then this get the amount of memory reserved
    def memoryParameters(self, flags=0):
        """Get the memory parameters """
    def memoryPeek(self, start, size, flags=0):
        """Read the contents of domain's memory """
    def memoryStats(self):
        """Extracts memory statistics for a domain """
                    repeatedly transferred memory pages during live migration. """
        transferred memory pages during live migration. It's supposed to be called
        Traditional pre-copy migration iteratively walks through guest memory
        memory pages.
        unpaused on destination. The source keeps sending all remaining memory pages
        guest tries to read a memory page which has not been migrated yet, the
             running on the destination host while some of its memory pages still
        this, any runtime changes, such as device hotplug or memory settings,
        """This method will suspend a domain and save its memory contents to
        """This method will suspend a domain and save its memory contents to
    def setMaxMemory(self, memory):
        """Dynamically change the maximum amount of physical memory allocated to a
        domain. If domain is None, then this change the amount of memory reserved
        ret = libvirtmod.virDomainSetMaxMemory(self._o, memory)
    def setMemory(self, memory):
        """Dynamically change the target amount of physical memory allocated to a
        domain. If domain is None, then this change the amount of memory reserved
        ret = libvirtmod.virDomainSetMemory(self._o, memory)
    def setMemoryFlags(self, memory, flags=0):
        """Dynamically change the target amount of physical memory allocated to a
        domain. If domain is None, then this change the amount of memory reserved
        If VIR_DOMAIN_MEM_MAXIMUM is set, the change affects domain's maximum memory
        size rather than current memory size.
        ret = libvirtmod.virDomainSetMemoryFlags(self._o, memory, flags)
        """Change the memory tunables """
        """Dynamically change the domain memory balloon driver statistics collection
        of the memory dump file, but reduces downtime of the guest while
        in the much rarer cases of running out of memory or disk space).
        to CPU resources and I/O but the memory used by the domain at the
        """Returns the available memory for a list of cells """
        """provides the free memory available on the Node
        Note: most libvirt APIs provide memory sizes in kibibytes, but in this
        """Extract hardware information about the Node. Note that the memory size is reported in MiB instead of KiB. """
        """Get the node memory parameters """
        """Extract node's memory statistics. """
        """Change the node memory tunables """
VIR_DOMAIN_JOB_MEMORY_BPS = "memory_bps"
VIR_DOMAIN_JOB_MEMORY_CONSTANT = "memory_constant"
VIR_DOMAIN_JOB_MEMORY_DIRTY_RATE = "memory_dirty_rate"
VIR_DOMAIN_JOB_MEMORY_ITERATION = "memory_iteration"
VIR_DOMAIN_JOB_MEMORY_NORMAL = "memory_normal"
VIR_DOMAIN_JOB_MEMORY_NORMAL_BYTES = "memory_normal_bytes"
VIR_DOMAIN_JOB_MEMORY_PAGE_SIZE = "memory_page_size"
VIR_DOMAIN_JOB_MEMORY_PROCESSED = "memory_processed"
VIR_DOMAIN_JOB_MEMORY_REMAINING = "memory_remaining"
VIR_DOMAIN_JOB_MEMORY_TOTAL = "memory_total"

正しいコード
変更後のコードは
cat /python/libvirt_python.py 
#!/usr/bin/python
#-*-coding:utf-8-*- 
import libvirt
import sys
 
def createConnection():
    conn = libvirt.openReadOnly(None)
    if conn == None:
        print '  KVM  '
        sys.exit(1)
    else:
        print '  KVM  '
        return conn
 
def closeConnection(conn):
    print ''
    try:
        conn.close()
    except:
        print '  KVM    '
        return 1
    print 'KVM    '
 
def getDomInfoByName(conn, name):
    print ''
    print '  KVM            '
    try:
        domain = conn.lookupByName(name)
    except:
        print ("  KVM   {}".format(name))
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
def getDomInfoByID(conn, id):
    print ''
    print '  KVM   ID       '
    try:
        domain = conn.lookupByID(id)
    except:
        print 'Failed to find the Domain with ID "%"' % id
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
if __name__ == '__main__':
    name1 = sys.argv[2]
    #name2 = "notExist"
    id1 = int(sys.argv[1])
    #id2 = 9999
    print "       libvirt python API"
    conn = createConnection()
    getDomInfoByName(conn, name1)
    #getDomInfoByName(conn, name2)
    getDomInfoByID(conn, id1)
    #getDomInfoByID(conn, id2)
    closeConnection(conn)

コードを実行する前にvirshで仮想マシン情報を表示します
virsh  list
 Id                                 
----------------------------------------------------
 3     CentOS7                        running

実行
[root@localhost python]# python libvirt_python.py 3 CentOS7
       libvirt python API
  KVM  

  KVM            
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 45570000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337104L}
   CPU  :1

  KVM   ID       
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 45570000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337104L}
   CPU  :1

KVM    

デコライザ出力メモリ詳細
出力からは仮想マシンのメモリ状態の出力が多く見られますが、さらに細かくして出力してもらえませんか.まず、コードにprint「仮想マシンのメモリ状態から出力データ型{}」を1行追加する.format(type(domain.memoryStats())では、メモリ状態で出力されるデータ型を表示します.
[root@localhost python]# cat /python/libvirt_python.py 
#!/usr/bin/python
#-*-coding:utf-8-*- 
import libvirt
import sys
 
def createConnection():
    conn = libvirt.openReadOnly(None)
    if conn == None:
        print '  KVM  '
        sys.exit(1)
    else:
        print '  KVM  '
        return conn
 
def closeConnection(conn):
    print ''
    try:
        conn.close()
    except:
        print '  KVM    '
        return 1
    print 'KVM    '
 
def getDomInfoByName(conn, name):
    print ''
    print '  KVM            '
    try:
        domain = conn.lookupByName(name)
    except:
        print ("  KVM   {}".format(name))
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))
def getDomInfoByID(conn, id):
    print ''
    print '  KVM   ID       '
    try:
        domain = conn.lookupByID(id)
    except:
        print 'Failed to find the Domain with ID "%"' % id
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))
if __name__ == '__main__':
    name1 = sys.argv[2]
    #name2 = "notExist"
    id1 = int(sys.argv[1])
    #id2 = 9999
    print "       libvirt python API"
    conn = createConnection()
    getDomInfoByName(conn, name1)
    #getDomInfoByName(conn, name2)
    getDomInfoByID(conn, id1)
    #getDomInfoByID(conn, id2)
    closeConnection(conn)

メモリステータスの表示出力を実行するデータ型
python libvirt_python.py 3 CentOS7
       libvirt python API
  KVM  

  KVM            
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 55140000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337088L}
   CPU  :1
              <type 'dict'>

  KVM   ID       
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 55140000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337088L}
   CPU  :1
              <type 'dict'>

KVM    

出力されるデータ型が辞書であることがわかりますので、メモリの詳細な出力情報を取得するには、辞書メソッドを使用します.また,ここの関数は既に作成されており,元の関数のコードを変更しない場合には,アクセラレータを用いて関数の出力を変更することができる.
デコレーション関数getDomInfoByName
cat /python/libvirt_python.py 
#!/usr/bin/python
#-*-coding:utf-8-*- 
import libvirt
import sys
 
def createConnection():
    conn = libvirt.openReadOnly(None)
    if conn == None:
        print '  KVM  '
        sys.exit(1)
    else:
        print '  KVM  '
        return conn
 
def closeConnection(conn):
    print ''
    try:
        conn.close()
    except:
        print '  KVM    '
        return 1
    print 'KVM    '
 
def decorator(func):
   def innerfun(conn,name):
      try:
         print ''
         func(conn,name)
         print("      ,        ======================================")
         domain = conn.lookupByName(name)
         for k,v in domain.memoryStats().items():
            print(k,v)
         print("          ================================================")
      except:
         print('              ,        ')
         print ''
   return innerfun
@decorator
def getDomInfoByName(conn, name):
    print ''
    print '  KVM            '
    try:
        domain = conn.lookupByName(name)
    except:
        print ("  KVM   {}".format(name))
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))

def getDomInfoByID(conn, id):
    print ''
    print '  KVM   ID       '
    try:
        domain = conn.lookupByID(id)
    except:
        print 'Failed to find the Domain with ID "%"' % id
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))

if __name__ == '__main__':
    name1 = sys.argv[2]
    #name2 = "notExist"
    id1 = int(sys.argv[1])
    #id2 = 9999
    print "       libvirt python API"
    conn = createConnection()
    getDomInfoByName(conn, name1)
    #getDomInfoByName(conn, name2)
    getDomInfoByID(conn, id1)
    #getDomInfoByID(conn, id2)
    closeConnection(conn)

うんてん
python libvirt_python.py 3 CentOS7
       libvirt python API
  KVM  


  KVM            
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 60950000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337104L}
   CPU  :1
              <type 'dict'>======================================
('swap_out', 0L)
('available', 1015000L)
('actual', 1048576L)
('major_fault', 192L)
('swap_in', 0L)
('last_update', 1606358542L)
('unused', 918512L)
('minor_fault', 578127L)
('rss', 337104L)
          ================================================

  KVM   ID       
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 60960000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337104L}
   CPU  :1
              <type 'dict'>

KVM    

注意:どの関数を装飾したいかは、どの関数の前に装飾器を定義し、装飾関数の前に@装飾器を定義します.このように操作すると、@装飾器の後ろの最初の関数だけが装飾され、他の関数を装飾したい場合は、直接関数の前に@装飾器があります.
別の関数getDomInfoByIDをデコレーションでデコレーション
cat /python/libvirt_python.py 
#!/usr/bin/python
#-*-coding:utf-8-*- 
import libvirt
import sys
 
def createConnection():
    conn = libvirt.openReadOnly(None)
    if conn == None:
        print '  KVM  '
        sys.exit(1)
    else:
        print '  KVM  '
        return conn
 
def closeConnection(conn):
    print ''
    try:
        conn.close()
    except:
        print '  KVM    '
        return 1
    print 'KVM    '
 
def decorator(func):
   def innerfun(conn,name):
      try:
         print ''
         func(conn,name)
         print("      ,        ======================================")
         domain = conn.lookupByName(name)
         for k,v in domain.memoryStats().items():
            print(k,v)
         print("          ================================================")
      except:
         print('              ,        ')
         print ''
   return innerfun
@decorator
def getDomInfoByName(conn, name):
    print ''
    print '  KVM            '
    try:
        domain = conn.lookupByName(name)
    except:
        print ("  KVM   {}".format(name))
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))

@decorator
def getDomInfoByID(conn, id):
    print ''
    print '  KVM   ID       '
    try:
        domain = conn.lookupByID(id)
    except:
        print 'Failed to find the Domain with ID "%"' % id
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))

if __name__ == '__main__':
    name1 = sys.argv[2]
    #name2 = "notExist"
    id1 = int(sys.argv[1])
    #id2 = 9999
    print "       libvirt python API"
    conn = createConnection()
    getDomInfoByName(conn, name1)
    #getDomInfoByName(conn, name2)
    getDomInfoByID(conn, id1)
    #getDomInfoByID(conn, id2)
    closeConnection(conn)

実行
python libvirt_python.py 3 CentOS7
       libvirt python API
  KVM  


  KVM            
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 61940000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337088L}
   CPU  :1
              <type 'dict'>======================================
('swap_out', 0L)
('available', 1015000L)
('actual', 1048576L)
('major_fault', 192L)
('swap_in', 0L)
('last_update', 1606358542L)
('unused', 918512L)
('minor_fault', 578127L)
('rss', 337088L)
          ================================================


  KVM   ID       
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 61950000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337088L}
   CPU  :1
              <type 'dict'>======================================
              ,        


KVM    

2番目の関数を飾るのに失敗したのは、2番目の関数でメモリを取得する方法が1番目の関数とは異なり、1番目の関数はconn.lookupByName()で、2番目の関数はconn.lookupByID()なので、ここで改善して、入力した関数名がどれなのかを判断して、対応する方法を呼び出せばいいのです.関数名を動的に取得するのは簡単なことではありません.犯しやすいエラーは直接func==「関数名」です.成功するかどうか説明します.
cat /python/libvirt_python.py 
#!/usr/bin/python
#-*-coding:utf-8-*- 
import libvirt
import sys
 
def createConnection():
    conn = libvirt.openReadOnly(None)
    if conn == None:
        print '  KVM  '
        sys.exit(1)
    else:
        print '  KVM  '
        return conn
 
def closeConnection(conn):
    print ''
    try:
        conn.close()
    except:
        print '  KVM    '
        return 1
    print 'KVM    '
 
def decorator(func):
   def innerfun(conn,name):
      try:
         print ''
         func(conn,name)
         print("      ,        ======================================")
         if func=='getDomInfoByName':
            domain = conn.lookupByName(name)
            for k,v in domain.memoryStats().items():
               print(k,v)
         elif func=='getDomInfoByID':
            domain = conn.lookupByID(name)
            for k,v in domain.memoryStats().items():
               print(k,v)
         else:
            print '        '
         print("          ================================================")
      except:
         print('              ,        ')
         print ''
   return innerfun
@decorator
def getDomInfoByName(conn, name):
    print ''
    print '  KVM            '
    try:
        domain = conn.lookupByName(name)
    except:
        print ("  KVM   {}".format(name))
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))

@decorator
def getDomInfoByID(conn, id):
    print ''
    print '  KVM   ID       '
    try:
        domain = conn.lookupByID(id)
    except:
        print 'Failed to find the Domain with ID "%"' % id
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))

if __name__ == '__main__':
    name1 = sys.argv[2]
    #name2 = "notExist"
    id1 = int(sys.argv[1])
    #id2 = 9999
    print "       libvirt python API"
    conn = createConnection()
    getDomInfoByName(conn, name1)
    #getDomInfoByName(conn, name2)
    getDomInfoByID(conn, id1)
    #getDomInfoByID(conn, id2)
    closeConnection(conn)

実行結果から,funcは実際には関数のメモリアドレス情報であり,関数の名前ではないため,関数の名前を取得する方法がある__name__であることが分かった.
python3.5 libvirt_python.py 3 CentOS7
       libvirt python API
  KVM  


  KVM            
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 68200000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337088L}
   CPU  :1
              <type 'dict'>======================================
        
          ================================================


  KVM   ID       
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 68200000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337088L}
   CPU  :1
              <type 'dict'>======================================
        
          ================================================

KVM    

で_name__メソッド関数名を取得して2つの関数を装飾する
cat /python/libvirt_python.py 
#!/usr/bin/python
#-*-coding:utf-8-*- 
import libvirt
import sys
 
def createConnection():
    conn = libvirt.openReadOnly(None)
    if conn == None:
        print '  KVM  '
        sys.exit(1)
    else:
        print '  KVM  '
        return conn
 
def closeConnection(conn):
    print ''
    try:
        conn.close()
    except:
        print '  KVM    '
        return 1
    print 'KVM    '
 
def decorator(func):
   def innerfun(conn,name):
      try:
         print ''
         func(conn,name)
         print("      ,        ======================================")
         if func.__name__=='getDomInfoByName':
            domain = conn.lookupByName(name)
            for k,v in domain.memoryStats().items():
               print(k,v)
         elif func.__name__=='getDomInfoByID':
            domain = conn.lookupByID(name)
            for k,v in domain.memoryStats().items():
               print(k,v)
         else:
            print '        '
         print("          ================================================")
      except:
         print('              ,        ')
         print ''
   return innerfun
@decorator
def getDomInfoByName(conn, name):
    print ''
    print '  KVM            '
    try:
        domain = conn.lookupByName(name)
    except:
        print ("  KVM   {}".format(name))
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))

@decorator
def getDomInfoByID(conn, id):
    print ''
    print '  KVM   ID       '
    try:
        domain = conn.lookupByID(id)
    except:
        print 'Failed to find the Domain with ID "%"' % id
        return 1
         
    print "   ID: {}     : {}".format ( domain.ID(), domain.name())
    print "     : {}".format(domain.state(0))
    print "     : {}".format(domain.info())
    print "       :{} MB".format((domain.maxMemory()/1024))
    print "       :{}".format(domain.memoryStats())
    print "   CPU  :{}".format(domain.maxVcpus())
    print "              {}".format(type(domain.memoryStats()))

if __name__ == '__main__':
    name1 = sys.argv[2]
    #name2 = "notExist"
    id1 = int(sys.argv[1])
    #id2 = 9999
    print "       libvirt python API"
    conn = createConnection()
    getDomInfoByName(conn, name1)
    #getDomInfoByName(conn, name2)
    getDomInfoByID(conn, id1)
    #getDomInfoByID(conn, id2)
    closeConnection(conn)

[root@localhost python]# python3.5 libvirt_python.py 3 CentOS7
       libvirt python API
  KVM  
  KVM            
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 69200000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337088L}
   CPU  :1
              <type 'dict'>======================================
('swap_out', 0L)
('available', 1015000L)
('actual', 1048576L)
('major_fault', 192L)
('swap_in', 0L)
('last_update', 1606358542L)
('unused', 918512L)
('minor_fault', 578127L)
('rss', 337088L)
          ================================================


  KVM   ID       
   ID: 3     : CentOS7
     : [1, 1]
     : [1, 1048576L, 1048576L, 1, 69210000000L]
       :1024 MB
       :{
     'swap_out': 0L, 'available': 1015000L, 'actual': 1048576L, 'major_fault': 192L, 'swap_in': 0L, 'last_update': 1606358542L, 'unused': 918512L, 'minor_fault': 578127L, 'rss': 337088L}
   CPU  :1
              <type 'dict'>======================================
('swap_out', 0L)
('available', 1015000L)
('actual', 1048576L)
('major_fault', 192L)
('swap_in', 0L)
('last_update', 1606358542L)
('unused', 918512L)
('minor_fault', 578127L)
('rss', 337088L)
          ================================================

KVM    

libvirtd.pyその他の関数の使用方法
cat /python/test.py 
#!/usr/bin/python
#-*-coding:utf-8-*- 
import libvirt
import sys
 
def createConnection():
    conn = libvirt.openReadOnly(None)
    if conn == None:
        print '  KVM  '
        sys.exit(1)
    else:
        print '  KVM  '
        return conn
 
def closeConnection(conn):
    print ''
    try:
        conn.close()
    except:
        print '  KVM    '
        return 1
    print 'KVM    '
    
def test(conn):
   print "   (virsh net-list     ){}".format(conn.listNetworks())
   print "      {}".format(conn.getHostname())
   print "       (virsh net-list --all         ){}".format(conn.listDefinedNetworks())
   print "       {}".format(conn.getFreeMemory()/1024/1024/1024)
   print "     {}".format(conn.getInfo())
   print "         {}".format(type(conn.getInfo()))
   print "    uri{}".format(conn.getURI())
   print "     {}".format(conn.getType())
   print "   id{}".format(conn.listDomainsID())
   print "        {}".format(conn.listInterfaces())
   print "       {}".format(conn.numOfNetworks())
   
if __name__ == '__main__':
    conn = createConnection()
    test(conn)
    closeConnection(conn)
[root@kvm python]# python test.py 
  KVM  
   (virsh net-list     )['default']
      kvm
       (virsh net-list --all         )['CentOS7-net']
       1
     ['x86_64', 4095L, 2, 3691, 1, 1, 2, 1]
         <type 'list'>
    uriqemu:///system
     QEMU
   id[6]
        ['br0', 'lo']
       1

KVM